1 use rustc_feature::{ACCEPTED_FEATURES, ACTIVE_FEATURES, Features, Feature, State as FeatureState};
2 use rustc_feature::{REMOVED_FEATURES, STABLE_REMOVED_FEATURES};
3 use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP};
5 use crate::ast::{self, AssocTyConstraint, AssocTyConstraintKind, NodeId};
6 use crate::ast::{GenericParam, GenericParamKind, PatKind, RangeEnd, VariantData};
8 use crate::source_map::Spanned;
9 use crate::edition::{ALL_EDITIONS, Edition};
10 use crate::visit::{self, FnKind, Visitor};
11 use crate::sess::ParseSess;
12 use crate::symbol::{Symbol, sym};
14 use errors::{Applicability, DiagnosticBuilder, Handler};
15 use rustc_data_structures::fx::FxHashMap;
16 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
19 use rustc_error_codes::*;
23 use std::num::NonZeroU32;
25 macro_rules! gate_feature_fn {
26 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
27 let (cx, has_feature, span,
28 name, explain, level) = (&*$cx, $has_feature, $span, $name, $explain, $level);
29 let has_feature: bool = has_feature(&$cx.features);
30 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
31 if !has_feature && !span.allows_unstable($name) {
32 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
38 macro_rules! gate_feature {
39 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
40 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
41 sym::$feature, $explain, GateStrength::Hard)
43 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
44 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
45 sym::$feature, $explain, $level)
49 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
50 PostExpansionVisitor { parse_sess, features }.visit_attribute(attr)
53 fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
54 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.name == feature) {
55 // FIXME (#28244): enforce that active features have issue numbers
56 // assert!(info.issue().is_some())
59 // search in Accepted, Removed, or Stable Removed features
60 let found = ACCEPTED_FEATURES
62 .chain(REMOVED_FEATURES)
63 .chain(STABLE_REMOVED_FEATURES)
64 .find(|t| t.name == feature);
66 Some(found) => found.issue(),
67 None => panic!("feature `{}` is not declared anywhere", feature),
74 Library(Option<NonZeroU32>)
77 #[derive(Debug, Copy, Clone, PartialEq)]
78 pub enum GateStrength {
79 /// A hard error. (Most feature gates should use this.)
81 /// Only a warning. (Use this only as backwards-compatibility demands.)
85 pub fn emit_feature_err(
92 feature_err(sess, feature, span, issue, explain).emit();
95 pub fn feature_err<'a, S: Into<MultiSpan>>(
101 ) -> DiagnosticBuilder<'a> {
102 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
105 fn leveled_feature_err<'a, S: Into<MultiSpan>>(
112 ) -> DiagnosticBuilder<'a> {
113 let diag = &sess.span_diagnostic;
115 let issue = match issue {
116 GateIssue::Language => find_lang_feature_issue(feature),
117 GateIssue::Library(lib) => lib,
120 let mut err = match level {
121 GateStrength::Hard => {
122 diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
124 GateStrength::Soft => diag.struct_span_warn(span, explain),
127 if let Some(n) = issue {
129 "for more information, see https://github.com/rust-lang/rust/issues/{}",
134 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
135 if sess.unstable_features.is_nightly_build() {
136 err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
139 // If we're on stable and only emitting a "soft" warning, add a note to
140 // clarify that the feature isn't "on" (rather than being on but
142 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
143 err.help("a nightly build of the compiler is required to enable this feature");
150 const EXPLAIN_BOX_SYNTAX: &str =
151 "box expression syntax is experimental; you can call `Box::new` instead";
153 struct PostExpansionVisitor<'a> {
154 parse_sess: &'a ParseSess,
155 features: &'a Features,
158 macro_rules! gate_feature_post {
159 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
160 let (cx, span) = ($cx, $span);
161 if !span.allows_unstable(sym::$feature) {
162 gate_feature!(cx, $feature, span, $explain)
165 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
166 let (cx, span) = ($cx, $span);
167 if !span.allows_unstable(sym::$feature) {
168 gate_feature!(cx, $feature, span, $explain, $level)
173 impl<'a> PostExpansionVisitor<'a> {
174 fn check_abi(&self, abi: ast::StrLit) {
175 let ast::StrLit { symbol_unescaped, span, .. } = abi;
177 match &*symbol_unescaped.as_str() {
188 "rust-intrinsic" => {
189 gate_feature_post!(&self, intrinsics, span,
190 "intrinsics are subject to change");
192 "platform-intrinsic" => {
193 gate_feature_post!(&self, platform_intrinsics, span,
194 "platform intrinsics are experimental and possibly buggy");
197 gate_feature_post!(&self, abi_vectorcall, span,
198 "vectorcall is experimental and subject to change");
201 gate_feature_post!(&self, abi_thiscall, span,
202 "thiscall is experimental and subject to change");
205 gate_feature_post!(&self, unboxed_closures, span,
206 "rust-call ABI is subject to change");
209 gate_feature_post!(&self, abi_ptx, span,
210 "PTX ABIs are experimental and subject to change");
213 gate_feature_post!(&self, abi_unadjusted, span,
214 "unadjusted ABI is an implementation detail and perma-unstable");
216 "msp430-interrupt" => {
217 gate_feature_post!(&self, abi_msp430_interrupt, span,
218 "msp430-interrupt ABI is experimental and subject to change");
221 gate_feature_post!(&self, abi_x86_interrupt, span,
222 "x86-interrupt ABI is experimental and subject to change");
225 gate_feature_post!(&self, abi_amdgpu_kernel, span,
226 "amdgpu-kernel ABI is experimental and subject to change");
229 gate_feature_post!(&self, abi_efiapi, span,
230 "efiapi ABI is experimental and subject to change");
233 self.parse_sess.span_diagnostic.delay_span_bug(
235 &format!("unrecognized ABI not caught in lowering: {}", abi),
241 fn check_extern(&self, ext: ast::Extern) {
242 if let ast::Extern::Explicit(abi) = ext {
247 fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
248 let has_fields = variants.iter().any(|variant| match variant.data {
249 VariantData::Tuple(..) | VariantData::Struct(..) => true,
250 VariantData::Unit(..) => false,
253 let discriminant_spans = variants.iter().filter(|variant| match variant.data {
254 VariantData::Tuple(..) | VariantData::Struct(..) => false,
255 VariantData::Unit(..) => true,
257 .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
258 .collect::<Vec<_>>();
260 if !discriminant_spans.is_empty() && has_fields {
261 let mut err = feature_err(
263 sym::arbitrary_enum_discriminant,
264 discriminant_spans.clone(),
265 crate::feature_gate::GateIssue::Language,
266 "custom discriminant values are not allowed in enums with tuple or struct variants",
268 for sp in discriminant_spans {
269 err.span_label(sp, "disallowed custom discriminant");
271 for variant in variants.iter() {
272 match &variant.data {
273 VariantData::Struct(..) => {
276 "struct variant defined here",
279 VariantData::Tuple(..) => {
282 "tuple variant defined here",
285 VariantData::Unit(..) => {}
292 fn check_gat(&self, generics: &ast::Generics, span: Span) {
293 if !generics.params.is_empty() {
296 generic_associated_types,
298 "generic associated types are unstable"
301 if !generics.where_clause.predicates.is_empty() {
304 generic_associated_types,
306 "where clauses on associated types are unstable"
311 /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
312 fn check_impl_trait(&self, ty: &ast::Ty) {
313 struct ImplTraitVisitor<'a> {
314 vis: &'a PostExpansionVisitor<'a>,
316 impl Visitor<'_> for ImplTraitVisitor<'_> {
317 fn visit_ty(&mut self, ty: &ast::Ty) {
318 if let ast::TyKind::ImplTrait(..) = ty.kind {
321 type_alias_impl_trait,
323 "`impl Trait` in type aliases is unstable"
326 visit::walk_ty(self, ty);
329 ImplTraitVisitor { vis: self }.visit_ty(ty);
333 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
334 fn visit_attribute(&mut self, attr: &ast::Attribute) {
336 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
337 // Check feature gates for built-in attributes.
338 if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
339 gate_feature_fn!(self, has_feature, attr.span, name, descr, GateStrength::Hard);
341 // Check unstable flavors of the `#[doc]` attribute.
342 if attr.check_name(sym::doc) {
343 for nested_meta in attr.meta_item_list().unwrap_or_default() {
344 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
345 $(if nested_meta.check_name(sym::$name) {
346 let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
347 gate_feature!(self, $feature, attr.span, msg);
352 include => external_doc
355 spotlight => doc_spotlight
357 keyword => doc_keyword
363 fn visit_name(&mut self, sp: Span, name: ast::Name) {
364 if !name.as_str().is_ascii() {
368 self.parse_sess.source_map().def_span(sp),
369 "non-ascii idents are not fully supported"
374 fn visit_item(&mut self, i: &'a ast::Item) {
376 ast::ItemKind::ForeignMod(ref foreign_module) => {
377 if let Some(abi) = foreign_module.abi {
382 ast::ItemKind::Fn(..) => {
383 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
384 gate_feature_post!(&self, plugin_registrar, i.span,
385 "compiler plugins are experimental and possibly buggy");
387 if attr::contains_name(&i.attrs[..], sym::start) {
388 gate_feature_post!(&self, start, i.span,
389 "a `#[start]` function is an experimental \
390 feature whose signature may change \
393 if attr::contains_name(&i.attrs[..], sym::main) {
394 gate_feature_post!(&self, main, i.span,
395 "declaration of a non-standard `#[main]` \
396 function may change over time, for now \
397 a top-level `fn main()` is required");
401 ast::ItemKind::Struct(..) => {
402 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
403 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
404 if item.check_name(sym::simd) {
405 gate_feature_post!(&self, repr_simd, attr.span,
406 "SIMD types are experimental and possibly buggy");
412 ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
413 for variant in variants {
414 match (&variant.data, &variant.disr_expr) {
415 (ast::VariantData::Unit(..), _) => {},
416 (_, Some(disr_expr)) =>
419 arbitrary_enum_discriminant,
420 disr_expr.value.span,
421 "discriminants on non-unit variants are experimental"),
426 let has_feature = self.features.arbitrary_enum_discriminant;
427 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
428 self.maybe_report_invalid_custom_discriminants(&variants);
432 ast::ItemKind::Impl(_, polarity, defaultness, ..) => {
433 if polarity == ast::ImplPolarity::Negative {
434 gate_feature_post!(&self, optin_builtin_traits,
436 "negative trait bounds are not yet fully implemented; \
437 use marker types for now");
440 if let ast::Defaultness::Default = defaultness {
441 gate_feature_post!(&self, specialization,
443 "specialization is unstable");
447 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
448 gate_feature_post!(&self, optin_builtin_traits,
450 "auto traits are experimental and possibly buggy");
453 ast::ItemKind::TraitAlias(..) => {
458 "trait aliases are experimental"
462 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
463 let msg = "`macro` is experimental";
464 gate_feature_post!(&self, decl_macro, i.span, msg);
467 ast::ItemKind::TyAlias(ref ty, ..) => self.check_impl_trait(&ty),
472 visit::walk_item(self, i);
475 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
477 ast::ForeignItemKind::Fn(..) |
478 ast::ForeignItemKind::Static(..) => {
479 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
480 let links_to_llvm = match link_name {
481 Some(val) => val.as_str().starts_with("llvm."),
485 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
486 "linking to LLVM intrinsics is experimental");
489 ast::ForeignItemKind::Ty => {
490 gate_feature_post!(&self, extern_types, i.span,
491 "extern types are experimental");
493 ast::ForeignItemKind::Macro(..) => {}
496 visit::walk_foreign_item(self, i)
499 fn visit_ty(&mut self, ty: &'a ast::Ty) {
501 ast::TyKind::BareFn(ref bare_fn_ty) => {
502 self.check_extern(bare_fn_ty.ext);
506 visit::walk_ty(self, ty)
509 fn visit_expr(&mut self, e: &'a ast::Expr) {
511 ast::ExprKind::Box(_) => {
512 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
514 ast::ExprKind::Type(..) => {
515 // To avoid noise about type ascription in common syntax errors, only emit if it
516 // is the *only* error.
517 if self.parse_sess.span_diagnostic.err_count() == 0 {
518 gate_feature_post!(&self, type_ascription, e.span,
519 "type ascription is experimental");
522 ast::ExprKind::TryBlock(_) => {
523 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
525 ast::ExprKind::Block(_, opt_label) => {
526 if let Some(label) = opt_label {
527 gate_feature_post!(&self, label_break_value, label.ident.span,
528 "labels on blocks are unstable");
533 visit::walk_expr(self, e)
536 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
537 match &pattern.kind {
538 PatKind::Slice(pats) => {
541 let inner_pat = match &pat.kind {
542 PatKind::Ident(.., Some(pat)) => pat,
545 if inner_pat.is_rest() {
550 "subslice patterns are unstable"
555 PatKind::Box(..) => {
556 gate_feature_post!(&self, box_patterns,
558 "box pattern syntax is experimental");
560 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
561 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
562 "exclusive range pattern syntax is experimental");
566 visit::walk_pat(self, pattern)
569 fn visit_fn(&mut self,
571 fn_decl: &'a ast::FnDecl,
574 if let Some(header) = fn_kind.header() {
575 // Stability of const fn methods are covered in
576 // `visit_trait_item` and `visit_impl_item` below; this is
577 // because default methods don't pass through this point.
578 self.check_extern(header.ext);
581 if fn_decl.c_variadic() {
582 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
585 visit::walk_fn(self, fn_kind, fn_decl, span)
588 fn visit_generic_param(&mut self, param: &'a GenericParam) {
590 GenericParamKind::Const { .. } =>
591 gate_feature_post!(&self, const_generics, param.ident.span,
592 "const generics are unstable"),
595 visit::walk_generic_param(self, param)
598 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
599 match constraint.kind {
600 AssocTyConstraintKind::Bound { .. } =>
601 gate_feature_post!(&self, associated_type_bounds, constraint.span,
602 "associated type bounds are unstable"),
605 visit::walk_assoc_ty_constraint(self, constraint)
608 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
610 ast::TraitItemKind::Method(ref sig, ref block) => {
612 self.check_extern(sig.header.ext);
614 if sig.decl.c_variadic() {
615 gate_feature_post!(&self, c_variadic, ti.span,
616 "C-variadic functions are unstable");
618 if sig.header.constness.node == ast::Constness::Const {
619 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
622 ast::TraitItemKind::Type(_, ref default) => {
623 if let Some(ty) = default {
624 self.check_impl_trait(ty);
625 gate_feature_post!(&self, associated_type_defaults, ti.span,
626 "associated type defaults are unstable");
628 self.check_gat(&ti.generics, ti.span);
632 visit::walk_trait_item(self, ti)
635 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
636 if ii.defaultness == ast::Defaultness::Default {
637 gate_feature_post!(&self, specialization,
639 "specialization is unstable");
643 ast::ImplItemKind::Method(ref sig, _) => {
644 if sig.decl.c_variadic() {
645 gate_feature_post!(&self, c_variadic, ii.span,
646 "C-variadic functions are unstable");
649 ast::ImplItemKind::TyAlias(ref ty) => {
650 self.check_impl_trait(ty);
651 self.check_gat(&ii.generics, ii.span);
655 visit::walk_impl_item(self, ii)
658 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
659 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
660 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
661 "`crate` visibility modifier is experimental");
663 visit::walk_vis(self, vis)
667 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
668 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
669 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
670 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
671 err.span_label(span, "feature has been removed");
672 if let Some(reason) = reason {
678 let mut features = Features::new();
679 let mut edition_enabled_features = FxHashMap::default();
681 for &edition in ALL_EDITIONS {
682 if edition <= crate_edition {
683 // The `crate_edition` implies its respective umbrella feature-gate
684 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
685 edition_enabled_features.insert(edition.feature_name(), edition);
689 for feature in active_features_up_to(crate_edition) {
690 feature.set(&mut features, DUMMY_SP);
691 edition_enabled_features.insert(feature.name, crate_edition);
694 // Process the edition umbrella feature-gates first, to ensure
695 // `edition_enabled_features` is completed before it's queried.
696 for attr in krate_attrs {
697 if !attr.check_name(sym::feature) {
701 let list = match attr.meta_item_list() {
711 let name = mi.name_or_empty();
713 let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
714 if let Some(edition) = edition {
715 if edition <= crate_edition {
719 for feature in active_features_up_to(edition) {
720 // FIXME(Manishearth) there is currently no way to set
721 // lib features by edition
722 feature.set(&mut features, DUMMY_SP);
723 edition_enabled_features.insert(feature.name, edition);
729 for attr in krate_attrs {
730 if !attr.check_name(sym::feature) {
734 let list = match attr.meta_item_list() {
739 let bad_input = |span| {
740 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
744 let name = match mi.ident() {
745 Some(ident) if mi.is_word() => ident.name,
747 bad_input(mi.span()).span_suggestion(
749 "expected just one word",
750 format!("{}", ident.name),
751 Applicability::MaybeIncorrect,
756 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
761 if let Some(edition) = edition_enabled_features.get(&name) {
766 "the feature `{}` is included in the Rust {} edition",
773 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
774 // Handled in the separate loop above.
778 let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
779 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
780 if let Some(Feature { state, .. }) = removed.or(stable_removed) {
781 if let FeatureState::Removed { reason }
782 | FeatureState::Stabilized { reason } = state
784 feature_removed(span_handler, mi.span(), *reason);
789 if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
790 let since = Some(Symbol::intern(since));
791 features.declared_lang_features.push((name, mi.span(), since));
795 if let Some(allowed) = allow_features.as_ref() {
796 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
797 span_err!(span_handler, mi.span(), E0725,
798 "the feature `{}` is not in the list of allowed features",
804 if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
805 f.set(&mut features, mi.span());
806 features.declared_lang_features.push((name, mi.span(), None));
810 features.declared_lib_features.push((name, mi.span()));
817 fn active_features_up_to(edition: Edition) -> impl Iterator<Item=&'static Feature> {
818 ACTIVE_FEATURES.iter()
819 .filter(move |feature| {
820 if let Some(feature_edition) = feature.edition {
821 feature_edition <= edition
828 pub fn check_crate(krate: &ast::Crate,
829 parse_sess: &ParseSess,
831 unstable: UnstableFeatures) {
832 maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
833 let mut visitor = PostExpansionVisitor { parse_sess, features };
835 let spans = parse_sess.gated_spans.spans.borrow();
836 macro_rules! gate_all {
837 ($gate:ident, $msg:literal) => {
838 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
839 gate_feature!(&visitor, $gate, *span, $msg);
843 gate_all!(let_chains, "`let` expressions in this position are experimental");
844 gate_all!(async_closure, "async closures are unstable");
845 gate_all!(generators, "yield syntax is experimental");
846 gate_all!(or_patterns, "or-patterns syntax is experimental");
847 gate_all!(const_extern_fn, "`const extern fn` definitions are unstable");
848 gate_all!(raw_ref_op, "raw address of syntax is experimental");
850 // All uses of `gate_all!` below this point were added in #65742,
851 // and subsequently disabled (with the non-early gating readded).
852 macro_rules! gate_all {
853 ($gate:ident, $msg:literal) => {
854 // FIXME(eddyb) do something more useful than always
855 // disabling these uses of early feature-gatings.
857 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
858 gate_feature!(&visitor, $gate, *span, $msg);
864 gate_all!(trait_alias, "trait aliases are experimental");
865 gate_all!(associated_type_bounds, "associated type bounds are unstable");
866 gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
867 gate_all!(const_generics, "const generics are unstable");
868 gate_all!(decl_macro, "`macro` is experimental");
869 gate_all!(box_patterns, "box pattern syntax is experimental");
870 gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
871 gate_all!(try_blocks, "`try` blocks are unstable");
872 gate_all!(label_break_value, "labels on blocks are unstable");
873 gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
874 // To avoid noise about type ascription in common syntax errors,
875 // only emit if it is the *only* error. (Also check it last.)
876 if parse_sess.span_diagnostic.err_count() == 0 {
877 gate_all!(type_ascription, "type ascription is experimental");
880 visit::walk_crate(&mut visitor, krate);
883 #[derive(Clone, Copy, Hash)]
884 pub enum UnstableFeatures {
885 /// Hard errors for unstable features are active, as on beta/stable channels.
887 /// Allow features to be activated, as on nightly.
889 /// Errors are bypassed for bootstrapping. This is required any time
890 /// during the build that feature-related lints are set to warn or above
891 /// because the build turns on warnings-as-errors and uses lots of unstable
892 /// features. As a result, this is always required for building Rust itself.
896 impl UnstableFeatures {
897 pub fn from_environment() -> UnstableFeatures {
898 // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
899 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
900 // `true` if we should enable unstable features for bootstrapping.
901 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
902 match (disable_unstable_features, bootstrap) {
903 (_, true) => UnstableFeatures::Cheat,
904 (true, _) => UnstableFeatures::Disallow,
905 (false, _) => UnstableFeatures::Allow
909 pub fn is_nightly_build(&self) -> bool {
911 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
912 UnstableFeatures::Disallow => false,
917 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
918 if !unstable.is_nightly_build() {
919 for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
921 span_handler, attr.span, E0554,
922 "`#![feature]` may not be used on the {} release channel",
923 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")