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