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};
21 use std::num::NonZeroU32;
23 #[derive(Copy, Clone, Debug)]
26 // First argument is tracking issue link; second argument is an optional
27 // help message, which defaults to "remove this attribute"
28 Deprecated(&'static str, Option<&'static str>),
31 macro_rules! gate_feature_fn {
32 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
33 let (cx, has_feature, span,
34 name, explain, level) = (&*$cx, $has_feature, $span, $name, $explain, $level);
35 let has_feature: bool = has_feature(&$cx.features);
36 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
37 if !has_feature && !span.allows_unstable($name) {
38 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
44 macro_rules! gate_feature {
45 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
46 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
47 sym::$feature, $explain, GateStrength::Hard)
49 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
50 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
51 sym::$feature, $explain, $level)
55 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
56 PostExpansionVisitor { parse_sess, features }.visit_attribute(attr)
59 fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
60 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.name == feature) {
61 // FIXME (#28244): enforce that active features have issue numbers
62 // assert!(info.issue().is_some())
65 // search in Accepted, Removed, or Stable Removed features
66 let found = ACCEPTED_FEATURES
68 .chain(REMOVED_FEATURES)
69 .chain(STABLE_REMOVED_FEATURES)
70 .find(|t| t.name == feature);
72 Some(found) => found.issue(),
73 None => panic!("feature `{}` is not declared anywhere", feature),
80 Library(Option<NonZeroU32>)
83 #[derive(Debug, Copy, Clone, PartialEq)]
84 pub enum GateStrength {
85 /// A hard error. (Most feature gates should use this.)
87 /// Only a warning. (Use this only as backwards-compatibility demands.)
91 pub fn emit_feature_err(
98 feature_err(sess, feature, span, issue, explain).emit();
101 pub fn feature_err<'a, S: Into<MultiSpan>>(
107 ) -> DiagnosticBuilder<'a> {
108 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
111 fn leveled_feature_err<'a, S: Into<MultiSpan>>(
118 ) -> DiagnosticBuilder<'a> {
119 let diag = &sess.span_diagnostic;
121 let issue = match issue {
122 GateIssue::Language => find_lang_feature_issue(feature),
123 GateIssue::Library(lib) => lib,
126 let mut err = match level {
127 GateStrength::Hard => {
128 diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
130 GateStrength::Soft => diag.struct_span_warn(span, explain),
133 if let Some(n) = issue {
135 "for more information, see https://github.com/rust-lang/rust/issues/{}",
140 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
141 if sess.unstable_features.is_nightly_build() {
142 err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
145 // If we're on stable and only emitting a "soft" warning, add a note to
146 // clarify that the feature isn't "on" (rather than being on but
148 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
149 err.help("a nightly build of the compiler is required to enable this feature");
156 const EXPLAIN_BOX_SYNTAX: &str =
157 "box expression syntax is experimental; you can call `Box::new` instead";
159 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
160 "attributes on expressions are experimental";
162 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
163 "allow_internal_unstable side-steps feature gating and stability checks";
164 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
165 "allow_internal_unsafe side-steps the unsafe_code lint";
167 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
168 "unsized tuple coercion is not stable enough for use and is subject to change";
170 struct PostExpansionVisitor<'a> {
171 parse_sess: &'a ParseSess,
172 features: &'a Features,
175 macro_rules! gate_feature_post {
176 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
177 let (cx, span) = ($cx, $span);
178 if !span.allows_unstable(sym::$feature) {
179 gate_feature!(cx, $feature, span, $explain)
182 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
183 let (cx, span) = ($cx, $span);
184 if !span.allows_unstable(sym::$feature) {
185 gate_feature!(cx, $feature, span, $explain, $level)
190 impl<'a> PostExpansionVisitor<'a> {
191 fn check_abi(&self, abi: ast::Abi) {
192 let ast::Abi { symbol, span } = abi;
194 match &*symbol.as_str() {
205 "rust-intrinsic" => {
206 gate_feature_post!(&self, intrinsics, span,
207 "intrinsics are subject to change");
209 "platform-intrinsic" => {
210 gate_feature_post!(&self, platform_intrinsics, span,
211 "platform intrinsics are experimental and possibly buggy");
214 gate_feature_post!(&self, abi_vectorcall, span,
215 "vectorcall is experimental and subject to change");
218 gate_feature_post!(&self, abi_thiscall, span,
219 "thiscall is experimental and subject to change");
222 gate_feature_post!(&self, unboxed_closures, span,
223 "rust-call ABI is subject to change");
226 gate_feature_post!(&self, abi_ptx, span,
227 "PTX ABIs are experimental and subject to change");
230 gate_feature_post!(&self, abi_unadjusted, span,
231 "unadjusted ABI is an implementation detail and perma-unstable");
233 "msp430-interrupt" => {
234 gate_feature_post!(&self, abi_msp430_interrupt, span,
235 "msp430-interrupt ABI is experimental and subject to change");
238 gate_feature_post!(&self, abi_x86_interrupt, span,
239 "x86-interrupt ABI is experimental and subject to change");
242 gate_feature_post!(&self, abi_amdgpu_kernel, span,
243 "amdgpu-kernel ABI is experimental and subject to change");
246 gate_feature_post!(&self, abi_efiapi, span,
247 "efiapi ABI is experimental and subject to change");
250 self.parse_sess.span_diagnostic.delay_span_bug(
252 &format!("unrecognized ABI not caught in lowering: {}", abi),
258 fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
259 let has_fields = variants.iter().any(|variant| match variant.data {
260 VariantData::Tuple(..) | VariantData::Struct(..) => true,
261 VariantData::Unit(..) => false,
264 let discriminant_spans = variants.iter().filter(|variant| match variant.data {
265 VariantData::Tuple(..) | VariantData::Struct(..) => false,
266 VariantData::Unit(..) => true,
268 .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
269 .collect::<Vec<_>>();
271 if !discriminant_spans.is_empty() && has_fields {
272 let mut err = feature_err(
274 sym::arbitrary_enum_discriminant,
275 discriminant_spans.clone(),
276 crate::feature_gate::GateIssue::Language,
277 "custom discriminant values are not allowed in enums with tuple or struct variants",
279 for sp in discriminant_spans {
280 err.span_label(sp, "disallowed custom discriminant");
282 for variant in variants.iter() {
283 match &variant.data {
284 VariantData::Struct(..) => {
287 "struct variant defined here",
290 VariantData::Tuple(..) => {
293 "tuple variant defined here",
296 VariantData::Unit(..) => {}
303 fn check_gat(&self, generics: &ast::Generics, span: Span) {
304 if !generics.params.is_empty() {
307 generic_associated_types,
309 "generic associated types are unstable"
312 if !generics.where_clause.predicates.is_empty() {
315 generic_associated_types,
317 "where clauses on associated types are unstable"
322 /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
323 fn check_impl_trait(&self, ty: &ast::Ty) {
324 struct ImplTraitVisitor<'a> {
325 vis: &'a PostExpansionVisitor<'a>,
327 impl Visitor<'_> for ImplTraitVisitor<'_> {
328 fn visit_ty(&mut self, ty: &ast::Ty) {
329 if let ast::TyKind::ImplTrait(..) = ty.kind {
332 type_alias_impl_trait,
334 "`impl Trait` in type aliases is unstable"
337 visit::walk_ty(self, ty);
340 ImplTraitVisitor { vis: self }.visit_ty(ty);
344 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
345 fn visit_attribute(&mut self, attr: &ast::Attribute) {
347 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
348 // Check feature gates for built-in attributes.
349 if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
350 gate_feature_fn!(self, has_feature, attr.span, name, descr, GateStrength::Hard);
352 // Check unstable flavors of the `#[doc]` attribute.
353 if attr.check_name(sym::doc) {
354 for nested_meta in attr.meta_item_list().unwrap_or_default() {
355 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
356 $(if nested_meta.check_name(sym::$name) {
357 let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
358 gate_feature!(self, $feature, attr.span, msg);
363 include => external_doc
366 spotlight => doc_spotlight
368 keyword => doc_keyword
374 fn visit_name(&mut self, sp: Span, name: ast::Name) {
375 if !name.as_str().is_ascii() {
379 self.parse_sess.source_map().def_span(sp),
380 "non-ascii idents are not fully supported"
385 fn visit_item(&mut self, i: &'a ast::Item) {
387 ast::ItemKind::ForeignMod(ref foreign_module) => {
388 self.check_abi(foreign_module.abi);
391 ast::ItemKind::Fn(..) => {
392 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
393 gate_feature_post!(&self, plugin_registrar, i.span,
394 "compiler plugins are experimental and possibly buggy");
396 if attr::contains_name(&i.attrs[..], sym::start) {
397 gate_feature_post!(&self, start, i.span,
398 "a `#[start]` function is an experimental \
399 feature whose signature may change \
402 if attr::contains_name(&i.attrs[..], sym::main) {
403 gate_feature_post!(&self, main, i.span,
404 "declaration of a non-standard `#[main]` \
405 function may change over time, for now \
406 a top-level `fn main()` is required");
410 ast::ItemKind::Struct(..) => {
411 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
412 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
413 if item.check_name(sym::simd) {
414 gate_feature_post!(&self, repr_simd, attr.span,
415 "SIMD types are experimental and possibly buggy");
421 ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
422 for variant in variants {
423 match (&variant.data, &variant.disr_expr) {
424 (ast::VariantData::Unit(..), _) => {},
425 (_, Some(disr_expr)) =>
428 arbitrary_enum_discriminant,
429 disr_expr.value.span,
430 "discriminants on non-unit variants are experimental"),
435 let has_feature = self.features.arbitrary_enum_discriminant;
436 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
437 self.maybe_report_invalid_custom_discriminants(&variants);
441 ast::ItemKind::Impl(_, polarity, defaultness, ..) => {
442 if polarity == ast::ImplPolarity::Negative {
443 gate_feature_post!(&self, optin_builtin_traits,
445 "negative trait bounds are not yet fully implemented; \
446 use marker types for now");
449 if let ast::Defaultness::Default = defaultness {
450 gate_feature_post!(&self, specialization,
452 "specialization is unstable");
456 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
457 gate_feature_post!(&self, optin_builtin_traits,
459 "auto traits are experimental and possibly buggy");
462 ast::ItemKind::TraitAlias(..) => {
467 "trait aliases are experimental"
471 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
472 let msg = "`macro` is experimental";
473 gate_feature_post!(&self, decl_macro, i.span, msg);
476 ast::ItemKind::TyAlias(ref ty, ..) => self.check_impl_trait(&ty),
481 visit::walk_item(self, i);
484 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
486 ast::ForeignItemKind::Fn(..) |
487 ast::ForeignItemKind::Static(..) => {
488 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
489 let links_to_llvm = match link_name {
490 Some(val) => val.as_str().starts_with("llvm."),
494 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
495 "linking to LLVM intrinsics is experimental");
498 ast::ForeignItemKind::Ty => {
499 gate_feature_post!(&self, extern_types, i.span,
500 "extern types are experimental");
502 ast::ForeignItemKind::Macro(..) => {}
505 visit::walk_foreign_item(self, i)
508 fn visit_ty(&mut self, ty: &'a ast::Ty) {
510 ast::TyKind::BareFn(ref bare_fn_ty) => {
511 self.check_abi(bare_fn_ty.abi);
513 ast::TyKind::Never => {
514 gate_feature_post!(&self, never_type, ty.span,
515 "The `!` type is experimental");
519 visit::walk_ty(self, ty)
522 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
523 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
524 if let ast::TyKind::Never = output_ty.kind {
527 self.visit_ty(output_ty)
532 fn visit_expr(&mut self, e: &'a ast::Expr) {
534 ast::ExprKind::Box(_) => {
535 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
537 ast::ExprKind::Type(..) => {
538 // To avoid noise about type ascription in common syntax errors, only emit if it
539 // is the *only* error.
540 if self.parse_sess.span_diagnostic.err_count() == 0 {
541 gate_feature_post!(&self, type_ascription, e.span,
542 "type ascription is experimental");
545 ast::ExprKind::TryBlock(_) => {
546 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
548 ast::ExprKind::Block(_, opt_label) => {
549 if let Some(label) = opt_label {
550 gate_feature_post!(&self, label_break_value, label.ident.span,
551 "labels on blocks are unstable");
556 visit::walk_expr(self, e)
559 fn visit_arm(&mut self, arm: &'a ast::Arm) {
560 visit::walk_arm(self, arm)
563 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
564 match &pattern.kind {
565 PatKind::Slice(pats) => {
568 let inner_pat = match &pat.kind {
569 PatKind::Ident(.., Some(pat)) => pat,
572 if inner_pat.is_rest() {
577 "subslice patterns are unstable"
582 PatKind::Box(..) => {
583 gate_feature_post!(&self, box_patterns,
585 "box pattern syntax is experimental");
587 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
588 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
589 "exclusive range pattern syntax is experimental");
593 visit::walk_pat(self, pattern)
596 fn visit_fn(&mut self,
598 fn_decl: &'a ast::FnDecl,
601 if let Some(header) = fn_kind.header() {
602 // Stability of const fn methods are covered in
603 // `visit_trait_item` and `visit_impl_item` below; this is
604 // because default methods don't pass through this point.
605 self.check_abi(header.abi);
608 if fn_decl.c_variadic() {
609 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
612 visit::walk_fn(self, fn_kind, fn_decl, span)
615 fn visit_generic_param(&mut self, param: &'a GenericParam) {
617 GenericParamKind::Const { .. } =>
618 gate_feature_post!(&self, const_generics, param.ident.span,
619 "const generics are unstable"),
622 visit::walk_generic_param(self, param)
625 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
626 match constraint.kind {
627 AssocTyConstraintKind::Bound { .. } =>
628 gate_feature_post!(&self, associated_type_bounds, constraint.span,
629 "associated type bounds are unstable"),
632 visit::walk_assoc_ty_constraint(self, constraint)
635 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
637 ast::TraitItemKind::Method(ref sig, ref block) => {
639 self.check_abi(sig.header.abi);
641 if sig.decl.c_variadic() {
642 gate_feature_post!(&self, c_variadic, ti.span,
643 "C-variadic functions are unstable");
645 if sig.header.constness.node == ast::Constness::Const {
646 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
649 ast::TraitItemKind::Type(_, ref default) => {
650 if let Some(ty) = default {
651 self.check_impl_trait(ty);
652 gate_feature_post!(&self, associated_type_defaults, ti.span,
653 "associated type defaults are unstable");
655 self.check_gat(&ti.generics, ti.span);
659 visit::walk_trait_item(self, ti)
662 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
663 if ii.defaultness == ast::Defaultness::Default {
664 gate_feature_post!(&self, specialization,
666 "specialization is unstable");
670 ast::ImplItemKind::Method(ref sig, _) => {
671 if sig.decl.c_variadic() {
672 gate_feature_post!(&self, c_variadic, ii.span,
673 "C-variadic functions are unstable");
676 ast::ImplItemKind::TyAlias(ref ty) => {
677 self.check_impl_trait(ty);
678 self.check_gat(&ii.generics, ii.span);
682 visit::walk_impl_item(self, ii)
685 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
686 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
687 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
688 "`crate` visibility modifier is experimental");
690 visit::walk_vis(self, vis)
694 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
695 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
696 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
697 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
698 if let Some(reason) = reason {
699 err.span_note(span, reason);
701 err.span_label(span, "feature has been removed");
706 let mut features = Features::new();
707 let mut edition_enabled_features = FxHashMap::default();
709 for &edition in ALL_EDITIONS {
710 if edition <= crate_edition {
711 // The `crate_edition` implies its respective umbrella feature-gate
712 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
713 edition_enabled_features.insert(edition.feature_name(), edition);
717 for feature in active_features_up_to(crate_edition) {
718 feature.set(&mut features, DUMMY_SP);
719 edition_enabled_features.insert(feature.name, crate_edition);
722 // Process the edition umbrella feature-gates first, to ensure
723 // `edition_enabled_features` is completed before it's queried.
724 for attr in krate_attrs {
725 if !attr.check_name(sym::feature) {
729 let list = match attr.meta_item_list() {
739 let name = mi.name_or_empty();
741 let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
742 if let Some(edition) = edition {
743 if edition <= crate_edition {
747 for feature in active_features_up_to(edition) {
748 // FIXME(Manishearth) there is currently no way to set
749 // lib features by edition
750 feature.set(&mut features, DUMMY_SP);
751 edition_enabled_features.insert(feature.name, edition);
757 for attr in krate_attrs {
758 if !attr.check_name(sym::feature) {
762 let list = match attr.meta_item_list() {
767 let bad_input = |span| {
768 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
772 let name = match mi.ident() {
773 Some(ident) if mi.is_word() => ident.name,
775 bad_input(mi.span()).span_suggestion(
777 "expected just one word",
778 format!("{}", ident.name),
779 Applicability::MaybeIncorrect,
784 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
789 if let Some(edition) = edition_enabled_features.get(&name) {
794 "the feature `{}` is included in the Rust {} edition",
801 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
802 // Handled in the separate loop above.
806 let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
807 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
808 if let Some(Feature { state, .. }) = removed.or(stable_removed) {
809 if let FeatureState::Removed { reason }
810 | FeatureState::Stabilized { reason } = state
812 feature_removed(span_handler, mi.span(), *reason);
817 if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
818 let since = Some(Symbol::intern(since));
819 features.declared_lang_features.push((name, mi.span(), since));
823 if let Some(allowed) = allow_features.as_ref() {
824 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
825 span_err!(span_handler, mi.span(), E0725,
826 "the feature `{}` is not in the list of allowed features",
832 if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
833 f.set(&mut features, mi.span());
834 features.declared_lang_features.push((name, mi.span(), None));
838 features.declared_lib_features.push((name, mi.span()));
845 fn active_features_up_to(edition: Edition) -> impl Iterator<Item=&'static Feature> {
846 ACTIVE_FEATURES.iter()
847 .filter(move |feature| {
848 if let Some(feature_edition) = feature.edition {
849 feature_edition <= edition
856 pub fn check_crate(krate: &ast::Crate,
857 parse_sess: &ParseSess,
859 unstable: UnstableFeatures) {
860 maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
861 let mut visitor = PostExpansionVisitor { parse_sess, features };
863 let spans = parse_sess.gated_spans.spans.borrow();
864 macro_rules! gate_all {
865 ($gate:ident, $msg:literal) => {
866 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
867 gate_feature!(&visitor, $gate, *span, $msg);
871 gate_all!(let_chains, "`let` expressions in this position are experimental");
872 gate_all!(async_closure, "async closures are unstable");
873 gate_all!(generators, "yield syntax is experimental");
874 gate_all!(or_patterns, "or-patterns syntax is experimental");
875 gate_all!(const_extern_fn, "`const extern fn` definitions are unstable");
877 // All uses of `gate_all!` below this point were added in #65742,
878 // and subsequently disabled (with the non-early gating readded).
879 macro_rules! gate_all {
880 ($gate:ident, $msg:literal) => {
881 // FIXME(eddyb) do something more useful than always
882 // disabling these uses of early feature-gatings.
884 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
885 gate_feature!(&visitor, $gate, *span, $msg);
891 gate_all!(trait_alias, "trait aliases are experimental");
892 gate_all!(associated_type_bounds, "associated type bounds are unstable");
893 gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
894 gate_all!(const_generics, "const generics are unstable");
895 gate_all!(decl_macro, "`macro` is experimental");
896 gate_all!(box_patterns, "box pattern syntax is experimental");
897 gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
898 gate_all!(try_blocks, "`try` blocks are unstable");
899 gate_all!(label_break_value, "labels on blocks are unstable");
900 gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
901 // To avoid noise about type ascription in common syntax errors,
902 // only emit if it is the *only* error. (Also check it last.)
903 if parse_sess.span_diagnostic.err_count() == 0 {
904 gate_all!(type_ascription, "type ascription is experimental");
907 visit::walk_crate(&mut visitor, krate);
910 #[derive(Clone, Copy, Hash)]
911 pub enum UnstableFeatures {
912 /// Hard errors for unstable features are active, as on beta/stable channels.
914 /// Allow features to be activated, as on nightly.
916 /// Errors are bypassed for bootstrapping. This is required any time
917 /// during the build that feature-related lints are set to warn or above
918 /// because the build turns on warnings-as-errors and uses lots of unstable
919 /// features. As a result, this is always required for building Rust itself.
923 impl UnstableFeatures {
924 pub fn from_environment() -> UnstableFeatures {
925 // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
926 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
927 // `true` if we should enable unstable features for bootstrapping.
928 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
929 match (disable_unstable_features, bootstrap) {
930 (_, true) => UnstableFeatures::Cheat,
931 (true, _) => UnstableFeatures::Disallow,
932 (false, _) => UnstableFeatures::Allow
936 pub fn is_nightly_build(&self) -> bool {
938 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
939 UnstableFeatures::Disallow => false,
944 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
945 if !unstable.is_nightly_build() {
946 for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
948 span_handler, attr.span, E0554,
949 "`#![feature]` may not be used on the {} release channel",
950 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")