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