]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/feature_gate/check.rs
Auto merge of #63871 - BatmanAoD:FloatFnMustUse, r=withoutboats
[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::{
7     self, AssocTyConstraint, AssocTyConstraintKind, NodeId, GenericParam, GenericParamKind,
8     PatKind, RangeEnd, VariantData,
9 };
10 use crate::attr::{self, check_builtin_attribute};
11 use crate::source_map::Spanned;
12 use crate::edition::{ALL_EDITIONS, Edition};
13 use crate::visit::{self, FnKind, Visitor};
14 use crate::token;
15 use crate::sess::ParseSess;
16 use crate::symbol::{Symbol, sym};
17 use crate::tokenstream::TokenTree;
18
19 use errors::{Applicability, DiagnosticBuilder, Handler};
20 use rustc_data_structures::fx::FxHashMap;
21 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
22 use log::debug;
23
24 use std::env;
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<u32> {
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.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
70             .find(|t| t.name == feature);
71         match found {
72             Some(&Feature { issue, .. }) => issue,
73             None => panic!("Feature `{}` is not declared anywhere", feature),
74         }
75     }
76 }
77
78 pub enum GateIssue {
79     Language,
80     Library(Option<u32>)
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     match issue {
134         None | Some(0) => {}  // We still accept `0` as a stand-in for backwards compatibility
135         Some(n) => {
136             err.note(&format!(
137                 "for more information, see https://github.com/rust-lang/rust/issues/{}",
138                 n,
139             ));
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 input tokens for built-in and key-value attributes.
335         match attr_info {
336             // `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
337             Some((name, _, template, _)) if name != sym::rustc_dummy =>
338                 check_builtin_attribute(self.parse_sess, attr, name, template),
339             _ => if let Some(TokenTree::Token(token)) =
340                     attr.get_normal_item().tokens.trees().next() {
341                 if token == token::Eq {
342                     // All key-value attributes are restricted to meta-item syntax.
343                     attr.parse_meta(self.parse_sess).map_err(|mut err| err.emit()).ok();
344                 }
345             }
346         }
347         // Check unstable flavors of the `#[doc]` attribute.
348         if attr.check_name(sym::doc) {
349             for nested_meta in attr.meta_item_list().unwrap_or_default() {
350                 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
351                     $(if nested_meta.check_name(sym::$name) {
352                         let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
353                         gate_feature!(self, $feature, attr.span, msg);
354                     })*
355                 }}
356
357                 gate_doc!(
358                     include => external_doc
359                     cfg => doc_cfg
360                     masked => doc_masked
361                     spotlight => doc_spotlight
362                     alias => doc_alias
363                     keyword => doc_keyword
364                 );
365             }
366         }
367     }
368
369     fn visit_name(&mut self, sp: Span, name: ast::Name) {
370         if !name.as_str().is_ascii() {
371             gate_feature_post!(
372                 &self,
373                 non_ascii_idents,
374                 self.parse_sess.source_map().def_span(sp),
375                 "non-ascii idents are not fully supported"
376             );
377         }
378     }
379
380     fn visit_item(&mut self, i: &'a ast::Item) {
381         match i.kind {
382             ast::ItemKind::ForeignMod(ref foreign_module) => {
383                 self.check_abi(foreign_module.abi);
384             }
385
386             ast::ItemKind::Fn(..) => {
387                 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
388                     gate_feature_post!(&self, plugin_registrar, i.span,
389                                        "compiler plugins are experimental and possibly buggy");
390                 }
391                 if attr::contains_name(&i.attrs[..], sym::start) {
392                     gate_feature_post!(&self, start, i.span,
393                                       "a `#[start]` function is an experimental \
394                                        feature whose signature may change \
395                                        over time");
396                 }
397                 if attr::contains_name(&i.attrs[..], sym::main) {
398                     gate_feature_post!(&self, main, i.span,
399                                        "declaration of a non-standard `#[main]` \
400                                         function may change over time, for now \
401                                         a top-level `fn main()` is required");
402                 }
403             }
404
405             ast::ItemKind::Struct(..) => {
406                 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
407                     for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
408                         if item.check_name(sym::simd) {
409                             gate_feature_post!(&self, repr_simd, attr.span,
410                                                "SIMD types are experimental and possibly buggy");
411                         }
412                     }
413                 }
414             }
415
416             ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
417                 for variant in variants {
418                     match (&variant.data, &variant.disr_expr) {
419                         (ast::VariantData::Unit(..), _) => {},
420                         (_, Some(disr_expr)) =>
421                             gate_feature_post!(
422                                 &self,
423                                 arbitrary_enum_discriminant,
424                                 disr_expr.value.span,
425                                 "discriminants on non-unit variants are experimental"),
426                         _ => {},
427                     }
428                 }
429
430                 let has_feature = self.features.arbitrary_enum_discriminant;
431                 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
432                     self.maybe_report_invalid_custom_discriminants(&variants);
433                 }
434             }
435
436             ast::ItemKind::Impl(_, polarity, defaultness, ..) => {
437                 if polarity == ast::ImplPolarity::Negative {
438                     gate_feature_post!(&self, optin_builtin_traits,
439                                        i.span,
440                                        "negative trait bounds are not yet fully implemented; \
441                                         use marker types for now");
442                 }
443
444                 if let ast::Defaultness::Default = defaultness {
445                     gate_feature_post!(&self, specialization,
446                                        i.span,
447                                        "specialization is unstable");
448                 }
449             }
450
451             ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
452                 gate_feature_post!(&self, optin_builtin_traits,
453                                    i.span,
454                                    "auto traits are experimental and possibly buggy");
455             }
456
457             ast::ItemKind::TraitAlias(..) => {
458                 gate_feature_post!(
459                     &self,
460                     trait_alias,
461                     i.span,
462                     "trait aliases are experimental"
463                 );
464             }
465
466             ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
467                 let msg = "`macro` is experimental";
468                 gate_feature_post!(&self, decl_macro, i.span, msg);
469             }
470
471             ast::ItemKind::OpaqueTy(..) => {
472                 gate_feature_post!(
473                     &self,
474                     type_alias_impl_trait,
475                     i.span,
476                     "`impl Trait` in type aliases is unstable"
477                 );
478             }
479
480             _ => {}
481         }
482
483         visit::walk_item(self, i);
484     }
485
486     fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
487         match i.kind {
488             ast::ForeignItemKind::Fn(..) |
489             ast::ForeignItemKind::Static(..) => {
490                 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
491                 let links_to_llvm = match link_name {
492                     Some(val) => val.as_str().starts_with("llvm."),
493                     _ => false
494                 };
495                 if links_to_llvm {
496                     gate_feature_post!(&self, link_llvm_intrinsics, i.span,
497                                        "linking to LLVM intrinsics is experimental");
498                 }
499             }
500             ast::ForeignItemKind::Ty => {
501                     gate_feature_post!(&self, extern_types, i.span,
502                                        "extern types are experimental");
503             }
504             ast::ForeignItemKind::Macro(..) => {}
505         }
506
507         visit::walk_foreign_item(self, i)
508     }
509
510     fn visit_ty(&mut self, ty: &'a ast::Ty) {
511         match ty.kind {
512             ast::TyKind::BareFn(ref bare_fn_ty) => {
513                 self.check_abi(bare_fn_ty.abi);
514             }
515             ast::TyKind::Never => {
516                 gate_feature_post!(&self, never_type, ty.span,
517                                    "The `!` type is experimental");
518             }
519             _ => {}
520         }
521         visit::walk_ty(self, ty)
522     }
523
524     fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
525         if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
526             if let ast::TyKind::Never = output_ty.kind {
527                 // Do nothing.
528             } else {
529                 self.visit_ty(output_ty)
530             }
531         }
532     }
533
534     fn visit_expr(&mut self, e: &'a ast::Expr) {
535         match e.kind {
536             ast::ExprKind::Box(_) => {
537                 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
538             }
539             ast::ExprKind::Type(..) => {
540                 // To avoid noise about type ascription in common syntax errors, only emit if it
541                 // is the *only* error.
542                 if self.parse_sess.span_diagnostic.err_count() == 0 {
543                     gate_feature_post!(&self, type_ascription, e.span,
544                                        "type ascription is experimental");
545                 }
546             }
547             ast::ExprKind::TryBlock(_) => {
548                 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
549             }
550             ast::ExprKind::Block(_, opt_label) => {
551                 if let Some(label) = opt_label {
552                     gate_feature_post!(&self, label_break_value, label.ident.span,
553                                     "labels on blocks are unstable");
554                 }
555             }
556             _ => {}
557         }
558         visit::walk_expr(self, e)
559     }
560
561     fn visit_arm(&mut self, arm: &'a ast::Arm) {
562         visit::walk_arm(self, arm)
563     }
564
565     fn visit_pat(&mut self, pattern: &'a ast::Pat) {
566         match &pattern.kind {
567             PatKind::Slice(pats) => {
568                 for pat in &*pats {
569                     let span = pat.span;
570                     let inner_pat = match &pat.kind {
571                         PatKind::Ident(.., Some(pat)) => pat,
572                         _ => pat,
573                     };
574                     if inner_pat.is_rest() {
575                         gate_feature_post!(
576                             &self,
577                             slice_patterns,
578                             span,
579                             "subslice patterns are unstable"
580                         );
581                     }
582                 }
583             }
584             PatKind::Box(..) => {
585                 gate_feature_post!(&self, box_patterns,
586                                   pattern.span,
587                                   "box pattern syntax is experimental");
588             }
589             PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
590                 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
591                                    "exclusive range pattern syntax is experimental");
592             }
593             _ => {}
594         }
595         visit::walk_pat(self, pattern)
596     }
597
598     fn visit_fn(&mut self,
599                 fn_kind: FnKind<'a>,
600                 fn_decl: &'a ast::FnDecl,
601                 span: Span,
602                 _node_id: NodeId) {
603         if let Some(header) = fn_kind.header() {
604             // Stability of const fn methods are covered in
605             // `visit_trait_item` and `visit_impl_item` below; this is
606             // because default methods don't pass through this point.
607             self.check_abi(header.abi);
608         }
609
610         if fn_decl.c_variadic() {
611             gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
612         }
613
614         visit::walk_fn(self, fn_kind, fn_decl, span)
615     }
616
617     fn visit_generic_param(&mut self, param: &'a GenericParam) {
618         match param.kind {
619             GenericParamKind::Const { .. } =>
620                 gate_feature_post!(&self, const_generics, param.ident.span,
621                     "const generics are unstable"),
622             _ => {}
623         }
624         visit::walk_generic_param(self, param)
625     }
626
627     fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
628         match constraint.kind {
629             AssocTyConstraintKind::Bound { .. } =>
630                 gate_feature_post!(&self, associated_type_bounds, constraint.span,
631                     "associated type bounds are unstable"),
632             _ => {}
633         }
634         visit::walk_assoc_ty_constraint(self, constraint)
635     }
636
637     fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
638         match ti.kind {
639             ast::TraitItemKind::Method(ref sig, ref block) => {
640                 if block.is_none() {
641                     self.check_abi(sig.header.abi);
642                 }
643                 if sig.decl.c_variadic() {
644                     gate_feature_post!(&self, c_variadic, ti.span,
645                                        "C-variadic functions are unstable");
646                 }
647                 if sig.header.constness.node == ast::Constness::Const {
648                     gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
649                 }
650             }
651             ast::TraitItemKind::Type(_, ref default) => {
652                 // We use three if statements instead of something like match guards so that all
653                 // of these errors can be emitted if all cases apply.
654                 if default.is_some() {
655                     gate_feature_post!(&self, associated_type_defaults, ti.span,
656                                        "associated type defaults are unstable");
657                 }
658                 self.check_gat(&ti.generics, ti.span);
659             }
660             _ => {}
661         }
662         visit::walk_trait_item(self, ti)
663     }
664
665     fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
666         if ii.defaultness == ast::Defaultness::Default {
667             gate_feature_post!(&self, specialization,
668                               ii.span,
669                               "specialization is unstable");
670         }
671
672         match ii.kind {
673             ast::ImplItemKind::Method(ref sig, _) => {
674                 if sig.decl.c_variadic() {
675                     gate_feature_post!(&self, c_variadic, ii.span,
676                                        "C-variadic functions are unstable");
677                 }
678             }
679             ast::ImplItemKind::OpaqueTy(..) => {
680                 gate_feature_post!(
681                     &self,
682                     type_alias_impl_trait,
683                     ii.span,
684                     "`impl Trait` in type aliases is unstable"
685                 );
686             }
687             ast::ImplItemKind::TyAlias(_) => {
688                 self.check_gat(&ii.generics, ii.span);
689             }
690             _ => {}
691         }
692         visit::walk_impl_item(self, ii)
693     }
694
695     fn visit_vis(&mut self, vis: &'a ast::Visibility) {
696         if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
697             gate_feature_post!(&self, crate_visibility_modifier, vis.span,
698                                "`crate` visibility modifier is experimental");
699         }
700         visit::walk_vis(self, vis)
701     }
702 }
703
704 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
705                     crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
706     fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
707         let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
708         if let Some(reason) = reason {
709             err.span_note(span, reason);
710         } else {
711             err.span_label(span, "feature has been removed");
712         }
713         err.emit();
714     }
715
716     let mut features = Features::new();
717     let mut edition_enabled_features = FxHashMap::default();
718
719     for &edition in ALL_EDITIONS {
720         if edition <= crate_edition {
721             // The `crate_edition` implies its respective umbrella feature-gate
722             // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
723             edition_enabled_features.insert(edition.feature_name(), edition);
724         }
725     }
726
727     for feature in active_features_up_to(crate_edition) {
728         feature.set(&mut features, DUMMY_SP);
729         edition_enabled_features.insert(feature.name, crate_edition);
730     }
731
732     // Process the edition umbrella feature-gates first, to ensure
733     // `edition_enabled_features` is completed before it's queried.
734     for attr in krate_attrs {
735         if !attr.check_name(sym::feature) {
736             continue
737         }
738
739         let list = match attr.meta_item_list() {
740             Some(list) => list,
741             None => continue,
742         };
743
744         for mi in list {
745             if !mi.is_word() {
746                 continue;
747             }
748
749             let name = mi.name_or_empty();
750
751             let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
752             if let Some(edition) = edition {
753                 if edition <= crate_edition {
754                     continue;
755                 }
756
757                 for feature in active_features_up_to(edition) {
758                     // FIXME(Manishearth) there is currently no way to set
759                     // lib features by edition
760                     feature.set(&mut features, DUMMY_SP);
761                     edition_enabled_features.insert(feature.name, edition);
762                 }
763             }
764         }
765     }
766
767     for attr in krate_attrs {
768         if !attr.check_name(sym::feature) {
769             continue
770         }
771
772         let list = match attr.meta_item_list() {
773             Some(list) => list,
774             None => continue,
775         };
776
777         let bad_input = |span| {
778             struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
779         };
780
781         for mi in list {
782             let name = match mi.ident() {
783                 Some(ident) if mi.is_word() => ident.name,
784                 Some(ident) => {
785                     bad_input(mi.span()).span_suggestion(
786                         mi.span(),
787                         "expected just one word",
788                         format!("{}", ident.name),
789                         Applicability::MaybeIncorrect,
790                     ).emit();
791                     continue
792                 }
793                 None => {
794                     bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
795                     continue
796                 }
797             };
798
799             if let Some(edition) = edition_enabled_features.get(&name) {
800                 struct_span_warn!(
801                     span_handler,
802                     mi.span(),
803                     E0705,
804                     "the feature `{}` is included in the Rust {} edition",
805                     name,
806                     edition,
807                 ).emit();
808                 continue;
809             }
810
811             if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
812                 // Handled in the separate loop above.
813                 continue;
814             }
815
816             let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
817             let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
818             if let Some(Feature { state, .. }) = removed.or(stable_removed) {
819                 if let FeatureState::Removed { reason }
820                 | FeatureState::Stabilized { reason } = state
821                 {
822                     feature_removed(span_handler, mi.span(), *reason);
823                     continue;
824                 }
825             }
826
827             if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
828                 let since = Some(Symbol::intern(since));
829                 features.declared_lang_features.push((name, mi.span(), since));
830                 continue;
831             }
832
833             if let Some(allowed) = allow_features.as_ref() {
834                 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
835                     span_err!(span_handler, mi.span(), E0725,
836                               "the feature `{}` is not in the list of allowed features",
837                               name);
838                     continue;
839                 }
840             }
841
842             if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
843                 f.set(&mut features, mi.span());
844                 features.declared_lang_features.push((name, mi.span(), None));
845                 continue;
846             }
847
848             features.declared_lib_features.push((name, mi.span()));
849         }
850     }
851
852     features
853 }
854
855 fn active_features_up_to(edition: Edition) -> impl Iterator<Item=&'static Feature> {
856     ACTIVE_FEATURES.iter()
857     .filter(move |feature| {
858         if let Some(feature_edition) = feature.edition {
859             feature_edition <= edition
860         } else {
861             false
862         }
863     })
864 }
865
866 pub fn check_crate(krate: &ast::Crate,
867                    parse_sess: &ParseSess,
868                    features: &Features,
869                    unstable: UnstableFeatures) {
870     maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
871     let mut visitor = PostExpansionVisitor { parse_sess, features };
872
873     let spans = parse_sess.gated_spans.spans.borrow();
874     macro_rules! gate_all {
875         ($gate:ident, $msg:literal) => {
876             for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
877                 gate_feature!(&visitor, $gate, *span, $msg);
878             }
879         }
880     }
881     gate_all!(let_chains, "`let` expressions in this position are experimental");
882     gate_all!(async_closure, "async closures are unstable");
883     gate_all!(generators, "yield syntax is experimental");
884     gate_all!(or_patterns, "or-patterns syntax is experimental");
885     gate_all!(const_extern_fn, "`const extern fn` definitions are unstable");
886
887     // All uses of `gate_all!` below this point were added in #65742,
888     // and subsequently disabled (with the non-early gating readded).
889     macro_rules! gate_all {
890         ($gate:ident, $msg:literal) => {
891             // FIXME(eddyb) do something more useful than always
892             // disabling these uses of early feature-gatings.
893             if false {
894                 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
895                     gate_feature!(&visitor, $gate, *span, $msg);
896                 }
897             }
898         }
899     }
900
901     gate_all!(trait_alias, "trait aliases are experimental");
902     gate_all!(associated_type_bounds, "associated type bounds are unstable");
903     gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
904     gate_all!(const_generics, "const generics are unstable");
905     gate_all!(decl_macro, "`macro` is experimental");
906     gate_all!(box_patterns, "box pattern syntax is experimental");
907     gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
908     gate_all!(try_blocks, "`try` blocks are unstable");
909     gate_all!(label_break_value, "labels on blocks are unstable");
910     gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
911     // To avoid noise about type ascription in common syntax errors,
912     // only emit if it is the *only* error. (Also check it last.)
913     if parse_sess.span_diagnostic.err_count() == 0 {
914         gate_all!(type_ascription, "type ascription is experimental");
915     }
916
917     visit::walk_crate(&mut visitor, krate);
918 }
919
920 #[derive(Clone, Copy, Hash)]
921 pub enum UnstableFeatures {
922     /// Hard errors for unstable features are active, as on beta/stable channels.
923     Disallow,
924     /// Allow features to be activated, as on nightly.
925     Allow,
926     /// Errors are bypassed for bootstrapping. This is required any time
927     /// during the build that feature-related lints are set to warn or above
928     /// because the build turns on warnings-as-errors and uses lots of unstable
929     /// features. As a result, this is always required for building Rust itself.
930     Cheat
931 }
932
933 impl UnstableFeatures {
934     pub fn from_environment() -> UnstableFeatures {
935         // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
936         let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
937         // `true` if we should enable unstable features for bootstrapping.
938         let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
939         match (disable_unstable_features, bootstrap) {
940             (_, true) => UnstableFeatures::Cheat,
941             (true, _) => UnstableFeatures::Disallow,
942             (false, _) => UnstableFeatures::Allow
943         }
944     }
945
946     pub fn is_nightly_build(&self) -> bool {
947         match *self {
948             UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
949             UnstableFeatures::Disallow => false,
950         }
951     }
952 }
953
954 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
955     if !unstable.is_nightly_build() {
956         for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
957             span_err!(
958                 span_handler, attr.span, E0554,
959                 "`#![feature]` may not be used on the {} release channel",
960                 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")
961             );
962         }
963     }
964 }