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