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