]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/feature_gate/check.rs
pre-expansion gate exclusive_range_pattern
[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, NodeId, PatKind, VariantData};
7 use crate::attr::{self, check_builtin_attribute};
8 use crate::edition::{ALL_EDITIONS, Edition};
9 use crate::visit::{self, FnKind, Visitor};
10 use crate::parse::token;
11 use crate::sess::ParseSess;
12 use crate::symbol::{Symbol, sym};
13 use crate::tokenstream::TokenTree;
14
15 use errors::{Applicability, DiagnosticBuilder, Handler};
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_target::spec::abi::Abi;
18 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
19 use log::debug;
20
21 use std::env;
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<u32> {
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.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
67             .find(|t| t.name == feature);
68         match found {
69             Some(&Feature { issue, .. }) => issue,
70             None => panic!("Feature `{}` is not declared anywhere", feature),
71         }
72     }
73 }
74
75 pub enum GateIssue {
76     Language,
77     Library(Option<u32>)
78 }
79
80 #[derive(Debug, Copy, Clone, PartialEq)]
81 pub enum GateStrength {
82     /// A hard error. (Most feature gates should use this.)
83     Hard,
84     /// Only a warning. (Use this only as backwards-compatibility demands.)
85     Soft,
86 }
87
88 pub fn emit_feature_err(
89     sess: &ParseSess,
90     feature: Symbol,
91     span: Span,
92     issue: GateIssue,
93     explain: &str,
94 ) {
95     feature_err(sess, feature, span, issue, explain).emit();
96 }
97
98 pub fn feature_err<'a, S: Into<MultiSpan>>(
99     sess: &'a ParseSess,
100     feature: Symbol,
101     span: S,
102     issue: GateIssue,
103     explain: &str,
104 ) -> DiagnosticBuilder<'a> {
105     leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
106 }
107
108 fn leveled_feature_err<'a, S: Into<MultiSpan>>(
109     sess: &'a ParseSess,
110     feature: Symbol,
111     span: S,
112     issue: GateIssue,
113     explain: &str,
114     level: GateStrength,
115 ) -> DiagnosticBuilder<'a> {
116     let diag = &sess.span_diagnostic;
117
118     let issue = match issue {
119         GateIssue::Language => find_lang_feature_issue(feature),
120         GateIssue::Library(lib) => lib,
121     };
122
123     let mut err = match level {
124         GateStrength::Hard => {
125             diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
126         }
127         GateStrength::Soft => diag.struct_span_warn(span, explain),
128     };
129
130     match issue {
131         None | Some(0) => {}  // We still accept `0` as a stand-in for backwards compatibility
132         Some(n) => {
133             err.note(&format!(
134                 "for more information, see https://github.com/rust-lang/rust/issues/{}",
135                 n,
136             ));
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: Abi, span: Span) {
192         match abi {
193             Abi::RustIntrinsic => {
194                 gate_feature_post!(&self, intrinsics, span,
195                                    "intrinsics are subject to change");
196             },
197             Abi::PlatformIntrinsic => {
198                 gate_feature_post!(&self, platform_intrinsics, span,
199                                    "platform intrinsics are experimental and possibly buggy");
200             },
201             Abi::Vectorcall => {
202                 gate_feature_post!(&self, abi_vectorcall, span,
203                                    "vectorcall is experimental and subject to change");
204             },
205             Abi::Thiscall => {
206                 gate_feature_post!(&self, abi_thiscall, span,
207                                    "thiscall is experimental and subject to change");
208             },
209             Abi::RustCall => {
210                 gate_feature_post!(&self, unboxed_closures, span,
211                                    "rust-call ABI is subject to change");
212             },
213             Abi::PtxKernel => {
214                 gate_feature_post!(&self, abi_ptx, span,
215                                    "PTX ABIs are experimental and subject to change");
216             },
217             Abi::Unadjusted => {
218                 gate_feature_post!(&self, abi_unadjusted, span,
219                                    "unadjusted ABI is an implementation detail and perma-unstable");
220             },
221             Abi::Msp430Interrupt => {
222                 gate_feature_post!(&self, abi_msp430_interrupt, span,
223                                    "msp430-interrupt ABI is experimental and subject to change");
224             },
225             Abi::X86Interrupt => {
226                 gate_feature_post!(&self, abi_x86_interrupt, span,
227                                    "x86-interrupt ABI is experimental and subject to change");
228             },
229             Abi::AmdGpuKernel => {
230                 gate_feature_post!(&self, abi_amdgpu_kernel, span,
231                                    "amdgpu-kernel ABI is experimental and subject to change");
232             },
233             // Stable
234             Abi::Cdecl |
235             Abi::Stdcall |
236             Abi::Fastcall |
237             Abi::Aapcs |
238             Abi::Win64 |
239             Abi::SysV64 |
240             Abi::Rust |
241             Abi::C |
242             Abi::System => {}
243         }
244     }
245
246     fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
247         let has_fields = variants.iter().any(|variant| match variant.data {
248             VariantData::Tuple(..) | VariantData::Struct(..) => true,
249             VariantData::Unit(..) => false,
250         });
251
252         let discriminant_spans = variants.iter().filter(|variant| match variant.data {
253             VariantData::Tuple(..) | VariantData::Struct(..) => false,
254             VariantData::Unit(..) => true,
255         })
256         .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
257         .collect::<Vec<_>>();
258
259         if !discriminant_spans.is_empty() && has_fields {
260             let mut err = feature_err(
261                 self.parse_sess,
262                 sym::arbitrary_enum_discriminant,
263                 discriminant_spans.clone(),
264                 crate::feature_gate::GateIssue::Language,
265                 "custom discriminant values are not allowed in enums with tuple or struct variants",
266             );
267             for sp in discriminant_spans {
268                 err.span_label(sp, "disallowed custom discriminant");
269             }
270             for variant in variants.iter() {
271                 match &variant.data {
272                     VariantData::Struct(..) => {
273                         err.span_label(
274                             variant.span,
275                             "struct variant defined here",
276                         );
277                     }
278                     VariantData::Tuple(..) => {
279                         err.span_label(
280                             variant.span,
281                             "tuple variant defined here",
282                         );
283                     }
284                     VariantData::Unit(..) => {}
285                 }
286             }
287             err.emit();
288         }
289     }
290 }
291
292 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
293     fn visit_attribute(&mut self, attr: &ast::Attribute) {
294         let attr_info =
295             attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
296         // Check feature gates for built-in attributes.
297         if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
298             gate_feature_fn!(self, has_feature, attr.span, name, descr, GateStrength::Hard);
299         }
300         // Check input tokens for built-in and key-value attributes.
301         match attr_info {
302             // `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
303             Some((name, _, template, _)) if name != sym::rustc_dummy =>
304                 check_builtin_attribute(self.parse_sess, attr, name, template),
305             _ => if let Some(TokenTree::Token(token)) = attr.tokens.trees().next() {
306                 if token == token::Eq {
307                     // All key-value attributes are restricted to meta-item syntax.
308                     attr.parse_meta(self.parse_sess).map_err(|mut err| err.emit()).ok();
309                 }
310             }
311         }
312         // Check unstable flavors of the `#[doc]` attribute.
313         if attr.check_name(sym::doc) {
314             for nested_meta in attr.meta_item_list().unwrap_or_default() {
315                 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
316                     $(if nested_meta.check_name(sym::$name) {
317                         let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
318                         gate_feature!(self, $feature, attr.span, msg);
319                     })*
320                 }}
321
322                 gate_doc!(
323                     include => external_doc
324                     cfg => doc_cfg
325                     masked => doc_masked
326                     spotlight => doc_spotlight
327                     alias => doc_alias
328                     keyword => doc_keyword
329                 );
330             }
331         }
332     }
333
334     fn visit_name(&mut self, sp: Span, name: ast::Name) {
335         if !name.as_str().is_ascii() {
336             gate_feature_post!(
337                 &self,
338                 non_ascii_idents,
339                 self.parse_sess.source_map().def_span(sp),
340                 "non-ascii idents are not fully supported"
341             );
342         }
343     }
344
345     fn visit_item(&mut self, i: &'a ast::Item) {
346         match i.kind {
347             ast::ItemKind::ForeignMod(ref foreign_module) => {
348                 self.check_abi(foreign_module.abi, i.span);
349             }
350
351             ast::ItemKind::Fn(..) => {
352                 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
353                     gate_feature_post!(&self, plugin_registrar, i.span,
354                                        "compiler plugins are experimental and possibly buggy");
355                 }
356                 if attr::contains_name(&i.attrs[..], sym::start) {
357                     gate_feature_post!(&self, start, i.span,
358                                       "a `#[start]` function is an experimental \
359                                        feature whose signature may change \
360                                        over time");
361                 }
362                 if attr::contains_name(&i.attrs[..], sym::main) {
363                     gate_feature_post!(&self, main, i.span,
364                                        "declaration of a non-standard `#[main]` \
365                                         function may change over time, for now \
366                                         a top-level `fn main()` is required");
367                 }
368             }
369
370             ast::ItemKind::Struct(..) => {
371                 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
372                     for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
373                         if item.check_name(sym::simd) {
374                             gate_feature_post!(&self, repr_simd, attr.span,
375                                                "SIMD types are experimental and possibly buggy");
376                         }
377                     }
378                 }
379             }
380
381             ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
382                 for variant in variants {
383                     match (&variant.data, &variant.disr_expr) {
384                         (ast::VariantData::Unit(..), _) => {},
385                         (_, Some(disr_expr)) =>
386                             gate_feature_post!(
387                                 &self,
388                                 arbitrary_enum_discriminant,
389                                 disr_expr.value.span,
390                                 "discriminants on non-unit variants are experimental"),
391                         _ => {},
392                     }
393                 }
394
395                 let has_feature = self.features.arbitrary_enum_discriminant;
396                 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
397                     self.maybe_report_invalid_custom_discriminants(&variants);
398                 }
399             }
400
401             ast::ItemKind::Impl(_, polarity, defaultness, ..) => {
402                 if polarity == ast::ImplPolarity::Negative {
403                     gate_feature_post!(&self, optin_builtin_traits,
404                                        i.span,
405                                        "negative trait bounds are not yet fully implemented; \
406                                         use marker types for now");
407                 }
408
409                 if let ast::Defaultness::Default = defaultness {
410                     gate_feature_post!(&self, specialization,
411                                        i.span,
412                                        "specialization is unstable");
413                 }
414             }
415
416             ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
417                 gate_feature_post!(&self, optin_builtin_traits,
418                                    i.span,
419                                    "auto traits are experimental and possibly buggy");
420             }
421
422             ast::ItemKind::OpaqueTy(..) => {
423                 gate_feature_post!(
424                     &self,
425                     type_alias_impl_trait,
426                     i.span,
427                     "`impl Trait` in type aliases is unstable"
428                 );
429             }
430
431             _ => {}
432         }
433
434         visit::walk_item(self, i);
435     }
436
437     fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
438         match i.kind {
439             ast::ForeignItemKind::Fn(..) |
440             ast::ForeignItemKind::Static(..) => {
441                 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
442                 let links_to_llvm = match link_name {
443                     Some(val) => val.as_str().starts_with("llvm."),
444                     _ => false
445                 };
446                 if links_to_llvm {
447                     gate_feature_post!(&self, link_llvm_intrinsics, i.span,
448                                        "linking to LLVM intrinsics is experimental");
449                 }
450             }
451             ast::ForeignItemKind::Ty => {
452                     gate_feature_post!(&self, extern_types, i.span,
453                                        "extern types are experimental");
454             }
455             ast::ForeignItemKind::Macro(..) => {}
456         }
457
458         visit::walk_foreign_item(self, i)
459     }
460
461     fn visit_ty(&mut self, ty: &'a ast::Ty) {
462         match ty.kind {
463             ast::TyKind::BareFn(ref bare_fn_ty) => {
464                 self.check_abi(bare_fn_ty.abi, ty.span);
465             }
466             ast::TyKind::Never => {
467                 gate_feature_post!(&self, never_type, ty.span,
468                                    "The `!` type is experimental");
469             }
470             _ => {}
471         }
472         visit::walk_ty(self, ty)
473     }
474
475     fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
476         if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
477             if let ast::TyKind::Never = output_ty.kind {
478                 // Do nothing.
479             } else {
480                 self.visit_ty(output_ty)
481             }
482         }
483     }
484
485     fn visit_expr(&mut self, e: &'a ast::Expr) {
486         match e.kind {
487             ast::ExprKind::Box(_) => {
488                 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
489             }
490             ast::ExprKind::Type(..) => {
491                 // To avoid noise about type ascription in common syntax errors, only emit if it
492                 // is the *only* error.
493                 if self.parse_sess.span_diagnostic.err_count() == 0 {
494                     gate_feature_post!(&self, type_ascription, e.span,
495                                        "type ascription is experimental");
496                 }
497             }
498             ast::ExprKind::TryBlock(_) => {
499                 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
500             }
501             ast::ExprKind::Block(_, opt_label) => {
502                 if let Some(label) = opt_label {
503                     gate_feature_post!(&self, label_break_value, label.ident.span,
504                                     "labels on blocks are unstable");
505                 }
506             }
507             _ => {}
508         }
509         visit::walk_expr(self, e)
510     }
511
512     fn visit_pat(&mut self, pattern: &'a ast::Pat) {
513         match &pattern.kind {
514             PatKind::Slice(pats) => {
515                 for pat in &*pats {
516                     let span = pat.span;
517                     let inner_pat = match &pat.kind {
518                         PatKind::Ident(.., Some(pat)) => pat,
519                         _ => pat,
520                     };
521                     if inner_pat.is_rest() {
522                         gate_feature_post!(
523                             &self,
524                             slice_patterns,
525                             span,
526                             "subslice patterns are unstable"
527                         );
528                     }
529                 }
530             }
531             _ => {}
532         }
533         visit::walk_pat(self, pattern)
534     }
535
536     fn visit_fn(&mut self, fn_kind: FnKind<'a>, fn_decl: &'a ast::FnDecl, span: Span, _: NodeId) {
537         if let Some(header) = fn_kind.header() {
538             // Stability of const fn methods are covered in
539             // `visit_trait_item` and `visit_impl_item` below; this is
540             // because default methods don't pass through this point.
541             self.check_abi(header.abi, span);
542         }
543
544         if fn_decl.c_variadic() {
545             gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
546         }
547
548         visit::walk_fn(self, fn_kind, fn_decl, span)
549     }
550
551     fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
552         match ti.kind {
553             ast::TraitItemKind::Method(ref sig, ref block) => {
554                 if block.is_none() {
555                     self.check_abi(sig.header.abi, ti.span);
556                 }
557                 if sig.decl.c_variadic() {
558                     gate_feature_post!(&self, c_variadic, ti.span,
559                                        "C-variadic functions are unstable");
560                 }
561                 if sig.header.constness.node == ast::Constness::Const {
562                     gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
563                 }
564             }
565             ast::TraitItemKind::Type(_, ref default) => {
566                 // We use three if statements instead of something like match guards so that all
567                 // of these errors can be emitted if all cases apply.
568                 if default.is_some() {
569                     gate_feature_post!(&self, associated_type_defaults, ti.span,
570                                        "associated type defaults are unstable");
571                 }
572                 if !ti.generics.params.is_empty() {
573                     gate_feature_post!(&self, generic_associated_types, ti.span,
574                                        "generic associated types are unstable");
575                 }
576                 if !ti.generics.where_clause.predicates.is_empty() {
577                     gate_feature_post!(&self, generic_associated_types, ti.span,
578                                        "where clauses on associated types are unstable");
579                 }
580             }
581             _ => {}
582         }
583         visit::walk_trait_item(self, ti)
584     }
585
586     fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
587         if ii.defaultness == ast::Defaultness::Default {
588             gate_feature_post!(&self, specialization,
589                               ii.span,
590                               "specialization is unstable");
591         }
592
593         match ii.kind {
594             ast::ImplItemKind::Method(ref sig, _) => {
595                 if sig.decl.c_variadic() {
596                     gate_feature_post!(&self, c_variadic, ii.span,
597                                        "C-variadic functions are unstable");
598                 }
599             }
600             ast::ImplItemKind::OpaqueTy(..) => {
601                 gate_feature_post!(
602                     &self,
603                     type_alias_impl_trait,
604                     ii.span,
605                     "`impl Trait` in type aliases is unstable"
606                 );
607             }
608             ast::ImplItemKind::TyAlias(_) => {
609                 if !ii.generics.params.is_empty() {
610                     gate_feature_post!(&self, generic_associated_types, ii.span,
611                                        "generic associated types are unstable");
612                 }
613                 if !ii.generics.where_clause.predicates.is_empty() {
614                     gate_feature_post!(&self, generic_associated_types, ii.span,
615                                        "where clauses on associated types are unstable");
616                 }
617             }
618             _ => {}
619         }
620         visit::walk_impl_item(self, ii)
621     }
622 }
623
624 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
625                     crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
626     fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
627         let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
628         if let Some(reason) = reason {
629             err.span_note(span, reason);
630         } else {
631             err.span_label(span, "feature has been removed");
632         }
633         err.emit();
634     }
635
636     let mut features = Features::new();
637     let mut edition_enabled_features = FxHashMap::default();
638
639     for &edition in ALL_EDITIONS {
640         if edition <= crate_edition {
641             // The `crate_edition` implies its respective umbrella feature-gate
642             // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
643             edition_enabled_features.insert(edition.feature_name(), edition);
644         }
645     }
646
647     for feature in active_features_up_to(crate_edition) {
648         feature.set(&mut features, DUMMY_SP);
649         edition_enabled_features.insert(feature.name, crate_edition);
650     }
651
652     // Process the edition umbrella feature-gates first, to ensure
653     // `edition_enabled_features` is completed before it's queried.
654     for attr in krate_attrs {
655         if !attr.check_name(sym::feature) {
656             continue
657         }
658
659         let list = match attr.meta_item_list() {
660             Some(list) => list,
661             None => continue,
662         };
663
664         for mi in list {
665             if !mi.is_word() {
666                 continue;
667             }
668
669             let name = mi.name_or_empty();
670
671             let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
672             if let Some(edition) = edition {
673                 if edition <= crate_edition {
674                     continue;
675                 }
676
677                 for feature in active_features_up_to(edition) {
678                     // FIXME(Manishearth) there is currently no way to set
679                     // lib features by edition
680                     feature.set(&mut features, DUMMY_SP);
681                     edition_enabled_features.insert(feature.name, edition);
682                 }
683             }
684         }
685     }
686
687     for attr in krate_attrs {
688         if !attr.check_name(sym::feature) {
689             continue
690         }
691
692         let list = match attr.meta_item_list() {
693             Some(list) => list,
694             None => continue,
695         };
696
697         let bad_input = |span| {
698             struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
699         };
700
701         for mi in list {
702             let name = match mi.ident() {
703                 Some(ident) if mi.is_word() => ident.name,
704                 Some(ident) => {
705                     bad_input(mi.span()).span_suggestion(
706                         mi.span(),
707                         "expected just one word",
708                         format!("{}", ident.name),
709                         Applicability::MaybeIncorrect,
710                     ).emit();
711                     continue
712                 }
713                 None => {
714                     bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
715                     continue
716                 }
717             };
718
719             if let Some(edition) = edition_enabled_features.get(&name) {
720                 struct_span_warn!(
721                     span_handler,
722                     mi.span(),
723                     E0705,
724                     "the feature `{}` is included in the Rust {} edition",
725                     name,
726                     edition,
727                 ).emit();
728                 continue;
729             }
730
731             if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
732                 // Handled in the separate loop above.
733                 continue;
734             }
735
736             let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
737             let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
738             if let Some(Feature { state, .. }) = removed.or(stable_removed) {
739                 if let FeatureState::Removed { reason }
740                 | FeatureState::Stabilized { reason } = state
741                 {
742                     feature_removed(span_handler, mi.span(), *reason);
743                     continue;
744                 }
745             }
746
747             if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
748                 let since = Some(Symbol::intern(since));
749                 features.declared_lang_features.push((name, mi.span(), since));
750                 continue;
751             }
752
753             if let Some(allowed) = allow_features.as_ref() {
754                 if allowed.iter().find(|&f| f == &name.as_str() as &str).is_none() {
755                     span_err!(span_handler, mi.span(), E0725,
756                               "the feature `{}` is not in the list of allowed features",
757                               name);
758                     continue;
759                 }
760             }
761
762             if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
763                 f.set(&mut features, mi.span());
764                 features.declared_lang_features.push((name, mi.span(), None));
765                 continue;
766             }
767
768             features.declared_lib_features.push((name, mi.span()));
769         }
770     }
771
772     features
773 }
774
775 fn active_features_up_to(edition: Edition) -> impl Iterator<Item=&'static Feature> {
776     ACTIVE_FEATURES.iter()
777     .filter(move |feature| {
778         if let Some(feature_edition) = feature.edition {
779             feature_edition <= edition
780         } else {
781             false
782         }
783     })
784 }
785
786 pub fn check_crate(krate: &ast::Crate,
787                    parse_sess: &ParseSess,
788                    features: &Features,
789                    unstable: UnstableFeatures) {
790     maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
791     let mut visitor = PostExpansionVisitor { parse_sess, features };
792
793     macro_rules! gate_all {
794         ($gate:ident, $msg:literal) => { gate_all!($gate, $gate, $msg); };
795         ($spans:ident, $gate:ident, $msg:literal) => {
796             for span in &*parse_sess.gated_spans.$spans.borrow() {
797                 gate_feature!(&visitor, $gate, *span, $msg);
798             }
799         }
800     }
801
802     gate_all!(let_chains, "`let` expressions in this position are experimental");
803     gate_all!(async_closure, "async closures are unstable");
804     gate_all!(yields, generators, "yield syntax is experimental");
805     gate_all!(or_patterns, "or-patterns syntax is experimental");
806     gate_all!(const_extern_fn, "`const extern fn` definitions are unstable");
807     gate_all!(trait_alias, "trait aliases are experimental");
808     gate_all!(associated_type_bounds, "associated type bounds are unstable");
809     gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
810     gate_all!(const_generics, "const generics are unstable");
811     gate_all!(decl_macro, "`macro` is experimental");
812     gate_all!(box_patterns, "box pattern syntax is experimental");
813     gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
814
815     visit::walk_crate(&mut visitor, krate);
816 }
817
818 #[derive(Clone, Copy, Hash)]
819 pub enum UnstableFeatures {
820     /// Hard errors for unstable features are active, as on beta/stable channels.
821     Disallow,
822     /// Allow features to be activated, as on nightly.
823     Allow,
824     /// Errors are bypassed for bootstrapping. This is required any time
825     /// during the build that feature-related lints are set to warn or above
826     /// because the build turns on warnings-as-errors and uses lots of unstable
827     /// features. As a result, this is always required for building Rust itself.
828     Cheat
829 }
830
831 impl UnstableFeatures {
832     pub fn from_environment() -> UnstableFeatures {
833         // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
834         let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
835         // `true` if we should enable unstable features for bootstrapping.
836         let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
837         match (disable_unstable_features, bootstrap) {
838             (_, true) => UnstableFeatures::Cheat,
839             (true, _) => UnstableFeatures::Disallow,
840             (false, _) => UnstableFeatures::Allow
841         }
842     }
843
844     pub fn is_nightly_build(&self) -> bool {
845         match *self {
846             UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
847             UnstableFeatures::Disallow => false,
848         }
849     }
850 }
851
852 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
853     if !unstable.is_nightly_build() {
854         for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
855             span_err!(
856                 span_handler, attr.span, E0554,
857                 "`#![feature]` may not be used on the {} release channel",
858                 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")
859             );
860         }
861     }
862 }