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 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
154 "attributes on expressions are experimental";
156 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
157 "unsized tuple coercion is not stable enough for use and is subject to change";
159 struct PostExpansionVisitor<'a> {
160 parse_sess: &'a ParseSess,
161 features: &'a Features,
164 macro_rules! gate_feature_post {
165 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
166 let (cx, span) = ($cx, $span);
167 if !span.allows_unstable(sym::$feature) {
168 gate_feature!(cx, $feature, span, $explain)
171 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
172 let (cx, span) = ($cx, $span);
173 if !span.allows_unstable(sym::$feature) {
174 gate_feature!(cx, $feature, span, $explain, $level)
179 impl<'a> PostExpansionVisitor<'a> {
180 fn check_abi(&self, abi: ast::StrLit) {
181 let ast::StrLit { symbol_unescaped, span, .. } = abi;
183 match &*symbol_unescaped.as_str() {
194 "rust-intrinsic" => {
195 gate_feature_post!(&self, intrinsics, span,
196 "intrinsics are subject to change");
198 "platform-intrinsic" => {
199 gate_feature_post!(&self, platform_intrinsics, span,
200 "platform intrinsics are experimental and possibly buggy");
203 gate_feature_post!(&self, abi_vectorcall, span,
204 "vectorcall is experimental and subject to change");
207 gate_feature_post!(&self, abi_thiscall, span,
208 "thiscall is experimental and subject to change");
211 gate_feature_post!(&self, unboxed_closures, span,
212 "rust-call ABI is subject to change");
215 gate_feature_post!(&self, abi_ptx, span,
216 "PTX ABIs are experimental and subject to change");
219 gate_feature_post!(&self, abi_unadjusted, span,
220 "unadjusted ABI is an implementation detail and perma-unstable");
222 "msp430-interrupt" => {
223 gate_feature_post!(&self, abi_msp430_interrupt, span,
224 "msp430-interrupt ABI is experimental and subject to change");
227 gate_feature_post!(&self, abi_x86_interrupt, span,
228 "x86-interrupt ABI is experimental and subject to change");
231 gate_feature_post!(&self, abi_amdgpu_kernel, span,
232 "amdgpu-kernel ABI is experimental and subject to change");
235 gate_feature_post!(&self, abi_efiapi, span,
236 "efiapi ABI is experimental and subject to change");
239 self.parse_sess.span_diagnostic.delay_span_bug(
241 &format!("unrecognized ABI not caught in lowering: {}", abi),
247 fn check_extern(&self, ext: ast::Extern) {
248 if let ast::Extern::Explicit(abi) = ext {
253 fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
254 let has_fields = variants.iter().any(|variant| match variant.data {
255 VariantData::Tuple(..) | VariantData::Struct(..) => true,
256 VariantData::Unit(..) => false,
259 let discriminant_spans = variants.iter().filter(|variant| match variant.data {
260 VariantData::Tuple(..) | VariantData::Struct(..) => false,
261 VariantData::Unit(..) => true,
263 .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
264 .collect::<Vec<_>>();
266 if !discriminant_spans.is_empty() && has_fields {
267 let mut err = feature_err(
269 sym::arbitrary_enum_discriminant,
270 discriminant_spans.clone(),
271 crate::feature_gate::GateIssue::Language,
272 "custom discriminant values are not allowed in enums with tuple or struct variants",
274 for sp in discriminant_spans {
275 err.span_label(sp, "disallowed custom discriminant");
277 for variant in variants.iter() {
278 match &variant.data {
279 VariantData::Struct(..) => {
282 "struct variant defined here",
285 VariantData::Tuple(..) => {
288 "tuple variant defined here",
291 VariantData::Unit(..) => {}
298 fn check_gat(&self, generics: &ast::Generics, span: Span) {
299 if !generics.params.is_empty() {
302 generic_associated_types,
304 "generic associated types are unstable"
307 if !generics.where_clause.predicates.is_empty() {
310 generic_associated_types,
312 "where clauses on associated types are unstable"
317 /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
318 fn check_impl_trait(&self, ty: &ast::Ty) {
319 struct ImplTraitVisitor<'a> {
320 vis: &'a PostExpansionVisitor<'a>,
322 impl Visitor<'_> for ImplTraitVisitor<'_> {
323 fn visit_ty(&mut self, ty: &ast::Ty) {
324 if let ast::TyKind::ImplTrait(..) = ty.kind {
327 type_alias_impl_trait,
329 "`impl Trait` in type aliases is unstable"
332 visit::walk_ty(self, ty);
335 ImplTraitVisitor { vis: self }.visit_ty(ty);
339 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
340 fn visit_attribute(&mut self, attr: &ast::Attribute) {
342 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
343 // Check feature gates for built-in attributes.
344 if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
345 gate_feature_fn!(self, has_feature, attr.span, name, descr, GateStrength::Hard);
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);
358 include => external_doc
361 spotlight => doc_spotlight
363 keyword => doc_keyword
369 fn visit_name(&mut self, sp: Span, name: ast::Name) {
370 if !name.as_str().is_ascii() {
374 self.parse_sess.source_map().def_span(sp),
375 "non-ascii idents are not fully supported"
380 fn visit_item(&mut self, i: &'a ast::Item) {
382 ast::ItemKind::ForeignMod(ref foreign_module) => {
383 if let Some(abi) = foreign_module.abi {
388 ast::ItemKind::Fn(..) => {
389 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
390 gate_feature_post!(&self, plugin_registrar, i.span,
391 "compiler plugins are experimental and possibly buggy");
393 if attr::contains_name(&i.attrs[..], sym::start) {
394 gate_feature_post!(&self, start, i.span,
395 "a `#[start]` function is an experimental \
396 feature whose signature may change \
399 if attr::contains_name(&i.attrs[..], sym::main) {
400 gate_feature_post!(&self, main, i.span,
401 "declaration of a non-standard `#[main]` \
402 function may change over time, for now \
403 a top-level `fn main()` is required");
407 ast::ItemKind::Struct(..) => {
408 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
409 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
410 if item.check_name(sym::simd) {
411 gate_feature_post!(&self, repr_simd, attr.span,
412 "SIMD types are experimental and possibly buggy");
418 ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
419 for variant in variants {
420 match (&variant.data, &variant.disr_expr) {
421 (ast::VariantData::Unit(..), _) => {},
422 (_, Some(disr_expr)) =>
425 arbitrary_enum_discriminant,
426 disr_expr.value.span,
427 "discriminants on non-unit variants are experimental"),
432 let has_feature = self.features.arbitrary_enum_discriminant;
433 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
434 self.maybe_report_invalid_custom_discriminants(&variants);
438 ast::ItemKind::Impl(_, polarity, defaultness, ..) => {
439 if polarity == ast::ImplPolarity::Negative {
440 gate_feature_post!(&self, optin_builtin_traits,
442 "negative trait bounds are not yet fully implemented; \
443 use marker types for now");
446 if let ast::Defaultness::Default = defaultness {
447 gate_feature_post!(&self, specialization,
449 "specialization is unstable");
453 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
454 gate_feature_post!(&self, optin_builtin_traits,
456 "auto traits are experimental and possibly buggy");
459 ast::ItemKind::TraitAlias(..) => {
464 "trait aliases are experimental"
468 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
469 let msg = "`macro` is experimental";
470 gate_feature_post!(&self, decl_macro, i.span, msg);
473 ast::ItemKind::TyAlias(ref ty, ..) => self.check_impl_trait(&ty),
478 visit::walk_item(self, i);
481 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
483 ast::ForeignItemKind::Fn(..) |
484 ast::ForeignItemKind::Static(..) => {
485 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
486 let links_to_llvm = match link_name {
487 Some(val) => val.as_str().starts_with("llvm."),
491 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
492 "linking to LLVM intrinsics is experimental");
495 ast::ForeignItemKind::Ty => {
496 gate_feature_post!(&self, extern_types, i.span,
497 "extern types are experimental");
499 ast::ForeignItemKind::Macro(..) => {}
502 visit::walk_foreign_item(self, i)
505 fn visit_ty(&mut self, ty: &'a ast::Ty) {
507 ast::TyKind::BareFn(ref bare_fn_ty) => {
508 self.check_extern(bare_fn_ty.ext);
512 visit::walk_ty(self, ty)
515 fn visit_expr(&mut self, e: &'a ast::Expr) {
517 ast::ExprKind::Box(_) => {
518 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
520 ast::ExprKind::Type(..) => {
521 // To avoid noise about type ascription in common syntax errors, only emit if it
522 // is the *only* error.
523 if self.parse_sess.span_diagnostic.err_count() == 0 {
524 gate_feature_post!(&self, type_ascription, e.span,
525 "type ascription is experimental");
528 ast::ExprKind::TryBlock(_) => {
529 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
531 ast::ExprKind::Block(_, opt_label) => {
532 if let Some(label) = opt_label {
533 gate_feature_post!(&self, label_break_value, label.ident.span,
534 "labels on blocks are unstable");
539 visit::walk_expr(self, e)
542 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
543 match &pattern.kind {
544 PatKind::Slice(pats) => {
547 let inner_pat = match &pat.kind {
548 PatKind::Ident(.., Some(pat)) => pat,
551 if inner_pat.is_rest() {
556 "subslice patterns are unstable"
561 PatKind::Box(..) => {
562 gate_feature_post!(&self, box_patterns,
564 "box pattern syntax is experimental");
566 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
567 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
568 "exclusive range pattern syntax is experimental");
572 visit::walk_pat(self, pattern)
575 fn visit_fn(&mut self,
577 fn_decl: &'a ast::FnDecl,
580 if let Some(header) = fn_kind.header() {
581 // Stability of const fn methods are covered in
582 // `visit_trait_item` and `visit_impl_item` below; this is
583 // because default methods don't pass through this point.
584 self.check_extern(header.ext);
587 if fn_decl.c_variadic() {
588 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
591 visit::walk_fn(self, fn_kind, fn_decl, span)
594 fn visit_generic_param(&mut self, param: &'a GenericParam) {
596 GenericParamKind::Const { .. } =>
597 gate_feature_post!(&self, const_generics, param.ident.span,
598 "const generics are unstable"),
601 visit::walk_generic_param(self, param)
604 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
605 match constraint.kind {
606 AssocTyConstraintKind::Bound { .. } =>
607 gate_feature_post!(&self, associated_type_bounds, constraint.span,
608 "associated type bounds are unstable"),
611 visit::walk_assoc_ty_constraint(self, constraint)
614 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
616 ast::TraitItemKind::Method(ref sig, ref block) => {
618 self.check_extern(sig.header.ext);
620 if sig.decl.c_variadic() {
621 gate_feature_post!(&self, c_variadic, ti.span,
622 "C-variadic functions are unstable");
624 if sig.header.constness.node == ast::Constness::Const {
625 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
628 ast::TraitItemKind::Type(_, ref default) => {
629 if let Some(ty) = default {
630 self.check_impl_trait(ty);
631 gate_feature_post!(&self, associated_type_defaults, ti.span,
632 "associated type defaults are unstable");
634 self.check_gat(&ti.generics, ti.span);
638 visit::walk_trait_item(self, ti)
641 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
642 if ii.defaultness == ast::Defaultness::Default {
643 gate_feature_post!(&self, specialization,
645 "specialization is unstable");
649 ast::ImplItemKind::Method(ref sig, _) => {
650 if sig.decl.c_variadic() {
651 gate_feature_post!(&self, c_variadic, ii.span,
652 "C-variadic functions are unstable");
655 ast::ImplItemKind::TyAlias(ref ty) => {
656 self.check_impl_trait(ty);
657 self.check_gat(&ii.generics, ii.span);
661 visit::walk_impl_item(self, ii)
664 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
665 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
666 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
667 "`crate` visibility modifier is experimental");
669 visit::walk_vis(self, vis)
673 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
674 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
675 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
676 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
677 err.span_label(span, "feature has been removed");
678 if let Some(reason) = reason {
684 let mut features = Features::new();
685 let mut edition_enabled_features = FxHashMap::default();
687 for &edition in ALL_EDITIONS {
688 if edition <= crate_edition {
689 // The `crate_edition` implies its respective umbrella feature-gate
690 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
691 edition_enabled_features.insert(edition.feature_name(), edition);
695 for feature in active_features_up_to(crate_edition) {
696 feature.set(&mut features, DUMMY_SP);
697 edition_enabled_features.insert(feature.name, crate_edition);
700 // Process the edition umbrella feature-gates first, to ensure
701 // `edition_enabled_features` is completed before it's queried.
702 for attr in krate_attrs {
703 if !attr.check_name(sym::feature) {
707 let list = match attr.meta_item_list() {
717 let name = mi.name_or_empty();
719 let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
720 if let Some(edition) = edition {
721 if edition <= crate_edition {
725 for feature in active_features_up_to(edition) {
726 // FIXME(Manishearth) there is currently no way to set
727 // lib features by edition
728 feature.set(&mut features, DUMMY_SP);
729 edition_enabled_features.insert(feature.name, edition);
735 for attr in krate_attrs {
736 if !attr.check_name(sym::feature) {
740 let list = match attr.meta_item_list() {
745 let bad_input = |span| {
746 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
750 let name = match mi.ident() {
751 Some(ident) if mi.is_word() => ident.name,
753 bad_input(mi.span()).span_suggestion(
755 "expected just one word",
756 format!("{}", ident.name),
757 Applicability::MaybeIncorrect,
762 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
767 if let Some(edition) = edition_enabled_features.get(&name) {
772 "the feature `{}` is included in the Rust {} edition",
779 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
780 // Handled in the separate loop above.
784 let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
785 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
786 if let Some(Feature { state, .. }) = removed.or(stable_removed) {
787 if let FeatureState::Removed { reason }
788 | FeatureState::Stabilized { reason } = state
790 feature_removed(span_handler, mi.span(), *reason);
795 if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
796 let since = Some(Symbol::intern(since));
797 features.declared_lang_features.push((name, mi.span(), since));
801 if let Some(allowed) = allow_features.as_ref() {
802 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
803 span_err!(span_handler, mi.span(), E0725,
804 "the feature `{}` is not in the list of allowed features",
810 if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
811 f.set(&mut features, mi.span());
812 features.declared_lang_features.push((name, mi.span(), None));
816 features.declared_lib_features.push((name, mi.span()));
823 fn active_features_up_to(edition: Edition) -> impl Iterator<Item=&'static Feature> {
824 ACTIVE_FEATURES.iter()
825 .filter(move |feature| {
826 if let Some(feature_edition) = feature.edition {
827 feature_edition <= edition
834 pub fn check_crate(krate: &ast::Crate,
835 parse_sess: &ParseSess,
837 unstable: UnstableFeatures) {
838 maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
839 let mut visitor = PostExpansionVisitor { parse_sess, features };
841 let spans = parse_sess.gated_spans.spans.borrow();
842 macro_rules! gate_all {
843 ($gate:ident, $msg:literal) => {
844 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
845 gate_feature!(&visitor, $gate, *span, $msg);
849 gate_all!(let_chains, "`let` expressions in this position are experimental");
850 gate_all!(async_closure, "async closures are unstable");
851 gate_all!(generators, "yield syntax is experimental");
852 gate_all!(or_patterns, "or-patterns syntax is experimental");
853 gate_all!(const_extern_fn, "`const extern fn` definitions are unstable");
854 gate_all!(raw_ref_op, "raw address of syntax is experimental");
856 // All uses of `gate_all!` below this point were added in #65742,
857 // and subsequently disabled (with the non-early gating readded).
858 macro_rules! gate_all {
859 ($gate:ident, $msg:literal) => {
860 // FIXME(eddyb) do something more useful than always
861 // disabling these uses of early feature-gatings.
863 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
864 gate_feature!(&visitor, $gate, *span, $msg);
870 gate_all!(trait_alias, "trait aliases are experimental");
871 gate_all!(associated_type_bounds, "associated type bounds are unstable");
872 gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
873 gate_all!(const_generics, "const generics are unstable");
874 gate_all!(decl_macro, "`macro` is experimental");
875 gate_all!(box_patterns, "box pattern syntax is experimental");
876 gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
877 gate_all!(try_blocks, "`try` blocks are unstable");
878 gate_all!(label_break_value, "labels on blocks are unstable");
879 gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
880 // To avoid noise about type ascription in common syntax errors,
881 // only emit if it is the *only* error. (Also check it last.)
882 if parse_sess.span_diagnostic.err_count() == 0 {
883 gate_all!(type_ascription, "type ascription is experimental");
886 visit::walk_crate(&mut visitor, krate);
889 #[derive(Clone, Copy, Hash)]
890 pub enum UnstableFeatures {
891 /// Hard errors for unstable features are active, as on beta/stable channels.
893 /// Allow features to be activated, as on nightly.
895 /// Errors are bypassed for bootstrapping. This is required any time
896 /// during the build that feature-related lints are set to warn or above
897 /// because the build turns on warnings-as-errors and uses lots of unstable
898 /// features. As a result, this is always required for building Rust itself.
902 impl UnstableFeatures {
903 pub fn from_environment() -> UnstableFeatures {
904 // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
905 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
906 // `true` if we should enable unstable features for bootstrapping.
907 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
908 match (disable_unstable_features, bootstrap) {
909 (_, true) => UnstableFeatures::Cheat,
910 (true, _) => UnstableFeatures::Disallow,
911 (false, _) => UnstableFeatures::Allow
915 pub fn is_nightly_build(&self) -> bool {
917 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
918 UnstableFeatures::Disallow => false,
923 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
924 if !unstable.is_nightly_build() {
925 for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
927 span_handler, attr.span, E0554,
928 "`#![feature]` may not be used on the {} release channel",
929 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")