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};
6 use crate::ast::{self, AssocTyConstraint, AssocTyConstraintKind, NodeId};
7 use crate::ast::{GenericParam, GenericParamKind, PatKind, RangeEnd, VariantData};
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};
15 use errors::{Applicability, DiagnosticBuilder, Handler};
16 use rustc_data_structures::fx::FxHashMap;
17 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
20 use rustc_error_codes::*;
24 use std::num::NonZeroU32;
26 #[derive(Copy, Clone, Debug)]
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>),
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)
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)
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)
58 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
59 PostExpansionVisitor { parse_sess, features }.visit_attribute(attr)
62 fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
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())
68 // search in Accepted, Removed, or Stable Removed features
69 let found = ACCEPTED_FEATURES
71 .chain(REMOVED_FEATURES)
72 .chain(STABLE_REMOVED_FEATURES)
73 .find(|t| t.name == feature);
75 Some(found) => found.issue(),
76 None => panic!("feature `{}` is not declared anywhere", feature),
83 Library(Option<NonZeroU32>)
86 #[derive(Debug, Copy, Clone, PartialEq)]
87 pub enum GateStrength {
88 /// A hard error. (Most feature gates should use this.)
90 /// Only a warning. (Use this only as backwards-compatibility demands.)
94 pub fn emit_feature_err(
101 feature_err(sess, feature, span, issue, explain).emit();
104 pub fn feature_err<'a, S: Into<MultiSpan>>(
110 ) -> DiagnosticBuilder<'a> {
111 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
114 fn leveled_feature_err<'a, S: Into<MultiSpan>>(
121 ) -> DiagnosticBuilder<'a> {
122 let diag = &sess.span_diagnostic;
124 let issue = match issue {
125 GateIssue::Language => find_lang_feature_issue(feature),
126 GateIssue::Library(lib) => lib,
129 let mut err = match level {
130 GateStrength::Hard => {
131 diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
133 GateStrength::Soft => diag.struct_span_warn(span, explain),
136 if let Some(n) = issue {
138 "for more information, see https://github.com/rust-lang/rust/issues/{}",
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));
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
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");
159 const EXPLAIN_BOX_SYNTAX: &str =
160 "box expression syntax is experimental; you can call `Box::new` instead";
162 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
163 "attributes on expressions are experimental";
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";
170 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
171 "unsized tuple coercion is not stable enough for use and is subject to change";
173 struct PostExpansionVisitor<'a> {
174 parse_sess: &'a ParseSess,
175 features: &'a Features,
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)
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)
193 impl<'a> PostExpansionVisitor<'a> {
194 fn check_abi(&self, abi: ast::Abi) {
195 let ast::Abi { symbol, span } = abi;
197 match &*symbol.as_str() {
208 "rust-intrinsic" => {
209 gate_feature_post!(&self, intrinsics, span,
210 "intrinsics are subject to change");
212 "platform-intrinsic" => {
213 gate_feature_post!(&self, platform_intrinsics, span,
214 "platform intrinsics are experimental and possibly buggy");
217 gate_feature_post!(&self, abi_vectorcall, span,
218 "vectorcall is experimental and subject to change");
221 gate_feature_post!(&self, abi_thiscall, span,
222 "thiscall is experimental and subject to change");
225 gate_feature_post!(&self, unboxed_closures, span,
226 "rust-call ABI is subject to change");
229 gate_feature_post!(&self, abi_ptx, span,
230 "PTX ABIs are experimental and subject to change");
233 gate_feature_post!(&self, abi_unadjusted, span,
234 "unadjusted ABI is an implementation detail and perma-unstable");
236 "msp430-interrupt" => {
237 gate_feature_post!(&self, abi_msp430_interrupt, span,
238 "msp430-interrupt ABI is experimental and subject to change");
241 gate_feature_post!(&self, abi_x86_interrupt, span,
242 "x86-interrupt ABI is experimental and subject to change");
245 gate_feature_post!(&self, abi_amdgpu_kernel, span,
246 "amdgpu-kernel ABI is experimental and subject to change");
249 gate_feature_post!(&self, abi_efiapi, span,
250 "efiapi ABI is experimental and subject to change");
253 self.parse_sess.span_diagnostic.delay_span_bug(
255 &format!("unrecognized ABI not caught in lowering: {}", abi),
261 fn check_extern(&self, ext: ast::Extern) {
262 if let ast::Extern::Explicit(abi) = ext {
267 fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
268 let has_fields = variants.iter().any(|variant| match variant.data {
269 VariantData::Tuple(..) | VariantData::Struct(..) => true,
270 VariantData::Unit(..) => false,
273 let discriminant_spans = variants.iter().filter(|variant| match variant.data {
274 VariantData::Tuple(..) | VariantData::Struct(..) => false,
275 VariantData::Unit(..) => true,
277 .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
278 .collect::<Vec<_>>();
280 if !discriminant_spans.is_empty() && has_fields {
281 let mut err = feature_err(
283 sym::arbitrary_enum_discriminant,
284 discriminant_spans.clone(),
285 crate::feature_gate::GateIssue::Language,
286 "custom discriminant values are not allowed in enums with tuple or struct variants",
288 for sp in discriminant_spans {
289 err.span_label(sp, "disallowed custom discriminant");
291 for variant in variants.iter() {
292 match &variant.data {
293 VariantData::Struct(..) => {
296 "struct variant defined here",
299 VariantData::Tuple(..) => {
302 "tuple variant defined here",
305 VariantData::Unit(..) => {}
312 fn check_gat(&self, generics: &ast::Generics, span: Span) {
313 if !generics.params.is_empty() {
316 generic_associated_types,
318 "generic associated types are unstable"
321 if !generics.where_clause.predicates.is_empty() {
324 generic_associated_types,
326 "where clauses on associated types are unstable"
331 /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
332 fn check_impl_trait(&self, ty: &ast::Ty) {
333 struct ImplTraitVisitor<'a> {
334 vis: &'a PostExpansionVisitor<'a>,
336 impl Visitor<'_> for ImplTraitVisitor<'_> {
337 fn visit_ty(&mut self, ty: &ast::Ty) {
338 if let ast::TyKind::ImplTrait(..) = ty.kind {
341 type_alias_impl_trait,
343 "`impl Trait` in type aliases is unstable"
346 visit::walk_ty(self, ty);
349 ImplTraitVisitor { vis: self }.visit_ty(ty);
353 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
354 fn visit_attribute(&mut self, attr: &ast::Attribute) {
356 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
357 // Check feature gates for built-in attributes.
358 if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
359 gate_feature_fn!(self, has_feature, attr.span, name, descr, GateStrength::Hard);
361 // Check unstable flavors of the `#[doc]` attribute.
362 if attr.check_name(sym::doc) {
363 for nested_meta in attr.meta_item_list().unwrap_or_default() {
364 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
365 $(if nested_meta.check_name(sym::$name) {
366 let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
367 gate_feature!(self, $feature, attr.span, msg);
372 include => external_doc
375 spotlight => doc_spotlight
377 keyword => doc_keyword
383 fn visit_name(&mut self, sp: Span, name: ast::Name) {
384 if !name.as_str().is_ascii() {
388 self.parse_sess.source_map().def_span(sp),
389 "non-ascii idents are not fully supported"
394 fn visit_item(&mut self, i: &'a ast::Item) {
396 ast::ItemKind::ForeignMod(ref foreign_module) => {
397 if let Some(abi) = foreign_module.abi {
402 ast::ItemKind::Fn(..) => {
403 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
404 gate_feature_post!(&self, plugin_registrar, i.span,
405 "compiler plugins are experimental and possibly buggy");
407 if attr::contains_name(&i.attrs[..], sym::start) {
408 gate_feature_post!(&self, start, i.span,
409 "a `#[start]` function is an experimental \
410 feature whose signature may change \
413 if attr::contains_name(&i.attrs[..], sym::main) {
414 gate_feature_post!(&self, main, i.span,
415 "declaration of a non-standard `#[main]` \
416 function may change over time, for now \
417 a top-level `fn main()` is required");
421 ast::ItemKind::Struct(..) => {
422 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
423 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
424 if item.check_name(sym::simd) {
425 gate_feature_post!(&self, repr_simd, attr.span,
426 "SIMD types are experimental and possibly buggy");
432 ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
433 for variant in variants {
434 match (&variant.data, &variant.disr_expr) {
435 (ast::VariantData::Unit(..), _) => {},
436 (_, Some(disr_expr)) =>
439 arbitrary_enum_discriminant,
440 disr_expr.value.span,
441 "discriminants on non-unit variants are experimental"),
446 let has_feature = self.features.arbitrary_enum_discriminant;
447 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
448 self.maybe_report_invalid_custom_discriminants(&variants);
452 ast::ItemKind::Impl(_, polarity, defaultness, ..) => {
453 if polarity == ast::ImplPolarity::Negative {
454 gate_feature_post!(&self, optin_builtin_traits,
456 "negative trait bounds are not yet fully implemented; \
457 use marker types for now");
460 if let ast::Defaultness::Default = defaultness {
461 gate_feature_post!(&self, specialization,
463 "specialization is unstable");
467 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
468 gate_feature_post!(&self, optin_builtin_traits,
470 "auto traits are experimental and possibly buggy");
473 ast::ItemKind::TraitAlias(..) => {
478 "trait aliases are experimental"
482 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
483 let msg = "`macro` is experimental";
484 gate_feature_post!(&self, decl_macro, i.span, msg);
487 ast::ItemKind::TyAlias(ref ty, ..) => self.check_impl_trait(&ty),
492 visit::walk_item(self, i);
495 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
497 ast::ForeignItemKind::Fn(..) |
498 ast::ForeignItemKind::Static(..) => {
499 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
500 let links_to_llvm = match link_name {
501 Some(val) => val.as_str().starts_with("llvm."),
505 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
506 "linking to LLVM intrinsics is experimental");
509 ast::ForeignItemKind::Ty => {
510 gate_feature_post!(&self, extern_types, i.span,
511 "extern types are experimental");
513 ast::ForeignItemKind::Macro(..) => {}
516 visit::walk_foreign_item(self, i)
519 fn visit_ty(&mut self, ty: &'a ast::Ty) {
521 ast::TyKind::BareFn(ref bare_fn_ty) => {
522 self.check_extern(bare_fn_ty.ext);
524 ast::TyKind::Never => {
525 gate_feature_post!(&self, never_type, ty.span,
526 "The `!` type is experimental");
530 visit::walk_ty(self, ty)
533 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
534 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
535 if let ast::TyKind::Never = output_ty.kind {
538 self.visit_ty(output_ty)
543 fn visit_expr(&mut self, e: &'a ast::Expr) {
545 ast::ExprKind::Box(_) => {
546 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
548 ast::ExprKind::Type(..) => {
549 // To avoid noise about type ascription in common syntax errors, only emit if it
550 // is the *only* error.
551 if self.parse_sess.span_diagnostic.err_count() == 0 {
552 gate_feature_post!(&self, type_ascription, e.span,
553 "type ascription is experimental");
556 ast::ExprKind::TryBlock(_) => {
557 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
559 ast::ExprKind::Block(_, opt_label) => {
560 if let Some(label) = opt_label {
561 gate_feature_post!(&self, label_break_value, label.ident.span,
562 "labels on blocks are unstable");
567 visit::walk_expr(self, e)
570 fn visit_arm(&mut self, arm: &'a ast::Arm) {
571 visit::walk_arm(self, arm)
574 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
575 match &pattern.kind {
576 PatKind::Slice(pats) => {
579 let inner_pat = match &pat.kind {
580 PatKind::Ident(.., Some(pat)) => pat,
583 if inner_pat.is_rest() {
588 "subslice patterns are unstable"
593 PatKind::Box(..) => {
594 gate_feature_post!(&self, box_patterns,
596 "box pattern syntax is experimental");
598 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
599 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
600 "exclusive range pattern syntax is experimental");
604 visit::walk_pat(self, pattern)
607 fn visit_fn(&mut self,
609 fn_decl: &'a ast::FnDecl,
612 if let Some(header) = fn_kind.header() {
613 // Stability of const fn methods are covered in
614 // `visit_trait_item` and `visit_impl_item` below; this is
615 // because default methods don't pass through this point.
616 self.check_extern(header.ext);
619 if fn_decl.c_variadic() {
620 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
623 visit::walk_fn(self, fn_kind, fn_decl, span)
626 fn visit_generic_param(&mut self, param: &'a GenericParam) {
628 GenericParamKind::Const { .. } =>
629 gate_feature_post!(&self, const_generics, param.ident.span,
630 "const generics are unstable"),
633 visit::walk_generic_param(self, param)
636 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
637 match constraint.kind {
638 AssocTyConstraintKind::Bound { .. } =>
639 gate_feature_post!(&self, associated_type_bounds, constraint.span,
640 "associated type bounds are unstable"),
643 visit::walk_assoc_ty_constraint(self, constraint)
646 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
648 ast::TraitItemKind::Method(ref sig, ref block) => {
650 self.check_extern(sig.header.ext);
652 if sig.decl.c_variadic() {
653 gate_feature_post!(&self, c_variadic, ti.span,
654 "C-variadic functions are unstable");
656 if sig.header.constness.node == ast::Constness::Const {
657 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
660 ast::TraitItemKind::Type(_, ref default) => {
661 if let Some(ty) = default {
662 self.check_impl_trait(ty);
663 gate_feature_post!(&self, associated_type_defaults, ti.span,
664 "associated type defaults are unstable");
666 self.check_gat(&ti.generics, ti.span);
670 visit::walk_trait_item(self, ti)
673 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
674 if ii.defaultness == ast::Defaultness::Default {
675 gate_feature_post!(&self, specialization,
677 "specialization is unstable");
681 ast::ImplItemKind::Method(ref sig, _) => {
682 if sig.decl.c_variadic() {
683 gate_feature_post!(&self, c_variadic, ii.span,
684 "C-variadic functions are unstable");
687 ast::ImplItemKind::TyAlias(ref ty) => {
688 self.check_impl_trait(ty);
689 self.check_gat(&ii.generics, ii.span);
693 visit::walk_impl_item(self, ii)
696 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
697 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
698 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
699 "`crate` visibility modifier is experimental");
701 visit::walk_vis(self, vis)
705 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
706 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
707 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
708 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
709 if let Some(reason) = reason {
710 err.span_note(span, reason);
712 err.span_label(span, "feature has been removed");
717 let mut features = Features::new();
718 let mut edition_enabled_features = FxHashMap::default();
720 for &edition in ALL_EDITIONS {
721 if edition <= crate_edition {
722 // The `crate_edition` implies its respective umbrella feature-gate
723 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
724 edition_enabled_features.insert(edition.feature_name(), edition);
728 for feature in active_features_up_to(crate_edition) {
729 feature.set(&mut features, DUMMY_SP);
730 edition_enabled_features.insert(feature.name, crate_edition);
733 // Process the edition umbrella feature-gates first, to ensure
734 // `edition_enabled_features` is completed before it's queried.
735 for attr in krate_attrs {
736 if !attr.check_name(sym::feature) {
740 let list = match attr.meta_item_list() {
750 let name = mi.name_or_empty();
752 let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
753 if let Some(edition) = edition {
754 if edition <= crate_edition {
758 for feature in active_features_up_to(edition) {
759 // FIXME(Manishearth) there is currently no way to set
760 // lib features by edition
761 feature.set(&mut features, DUMMY_SP);
762 edition_enabled_features.insert(feature.name, edition);
768 for attr in krate_attrs {
769 if !attr.check_name(sym::feature) {
773 let list = match attr.meta_item_list() {
778 let bad_input = |span| {
779 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
783 let name = match mi.ident() {
784 Some(ident) if mi.is_word() => ident.name,
786 bad_input(mi.span()).span_suggestion(
788 "expected just one word",
789 format!("{}", ident.name),
790 Applicability::MaybeIncorrect,
795 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
800 if let Some(edition) = edition_enabled_features.get(&name) {
805 "the feature `{}` is included in the Rust {} edition",
812 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
813 // Handled in the separate loop above.
817 let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
818 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
819 if let Some(Feature { state, .. }) = removed.or(stable_removed) {
820 if let FeatureState::Removed { reason }
821 | FeatureState::Stabilized { reason } = state
823 feature_removed(span_handler, mi.span(), *reason);
828 if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
829 let since = Some(Symbol::intern(since));
830 features.declared_lang_features.push((name, mi.span(), since));
834 if let Some(allowed) = allow_features.as_ref() {
835 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
836 span_err!(span_handler, mi.span(), E0725,
837 "the feature `{}` is not in the list of allowed features",
843 if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
844 f.set(&mut features, mi.span());
845 features.declared_lang_features.push((name, mi.span(), None));
849 features.declared_lib_features.push((name, mi.span()));
856 fn active_features_up_to(edition: Edition) -> impl Iterator<Item=&'static Feature> {
857 ACTIVE_FEATURES.iter()
858 .filter(move |feature| {
859 if let Some(feature_edition) = feature.edition {
860 feature_edition <= edition
867 pub fn check_crate(krate: &ast::Crate,
868 parse_sess: &ParseSess,
870 unstable: UnstableFeatures) {
871 maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
872 let mut visitor = PostExpansionVisitor { parse_sess, features };
874 let spans = parse_sess.gated_spans.spans.borrow();
875 macro_rules! gate_all {
876 ($gate:ident, $msg:literal) => {
877 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
878 gate_feature!(&visitor, $gate, *span, $msg);
882 gate_all!(let_chains, "`let` expressions in this position are experimental");
883 gate_all!(async_closure, "async closures are unstable");
884 gate_all!(generators, "yield syntax is experimental");
885 gate_all!(or_patterns, "or-patterns syntax is experimental");
886 gate_all!(const_extern_fn, "`const extern fn` definitions are unstable");
888 // All uses of `gate_all!` below this point were added in #65742,
889 // and subsequently disabled (with the non-early gating readded).
890 macro_rules! gate_all {
891 ($gate:ident, $msg:literal) => {
892 // FIXME(eddyb) do something more useful than always
893 // disabling these uses of early feature-gatings.
895 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
896 gate_feature!(&visitor, $gate, *span, $msg);
902 gate_all!(trait_alias, "trait aliases are experimental");
903 gate_all!(associated_type_bounds, "associated type bounds are unstable");
904 gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
905 gate_all!(const_generics, "const generics are unstable");
906 gate_all!(decl_macro, "`macro` is experimental");
907 gate_all!(box_patterns, "box pattern syntax is experimental");
908 gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
909 gate_all!(try_blocks, "`try` blocks are unstable");
910 gate_all!(label_break_value, "labels on blocks are unstable");
911 gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
912 // To avoid noise about type ascription in common syntax errors,
913 // only emit if it is the *only* error. (Also check it last.)
914 if parse_sess.span_diagnostic.err_count() == 0 {
915 gate_all!(type_ascription, "type ascription is experimental");
918 visit::walk_crate(&mut visitor, krate);
921 #[derive(Clone, Copy, Hash)]
922 pub enum UnstableFeatures {
923 /// Hard errors for unstable features are active, as on beta/stable channels.
925 /// Allow features to be activated, as on nightly.
927 /// Errors are bypassed for bootstrapping. This is required any time
928 /// during the build that feature-related lints are set to warn or above
929 /// because the build turns on warnings-as-errors and uses lots of unstable
930 /// features. As a result, this is always required for building Rust itself.
934 impl UnstableFeatures {
935 pub fn from_environment() -> UnstableFeatures {
936 // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
937 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
938 // `true` if we should enable unstable features for bootstrapping.
939 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
940 match (disable_unstable_features, bootstrap) {
941 (_, true) => UnstableFeatures::Cheat,
942 (true, _) => UnstableFeatures::Disallow,
943 (false, _) => UnstableFeatures::Allow
947 pub fn is_nightly_build(&self) -> bool {
949 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
950 UnstableFeatures::Disallow => false,
955 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
956 if !unstable.is_nightly_build() {
957 for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
959 span_handler, attr.span, E0554,
960 "`#![feature]` may not be used on the {} release channel",
961 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")