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