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