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