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};
22 #[derive(Copy, Clone, Debug)]
25 // First argument is tracking issue link; second argument is an optional
26 // help message, which defaults to "remove this attribute"
27 Deprecated(&'static str, Option<&'static str>),
30 macro_rules! gate_feature_fn {
31 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
32 let (cx, has_feature, span,
33 name, explain, level) = (&*$cx, $has_feature, $span, $name, $explain, $level);
34 let has_feature: bool = has_feature(&$cx.features);
35 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
36 if !has_feature && !span.allows_unstable($name) {
37 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
43 macro_rules! gate_feature {
44 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
45 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
46 sym::$feature, $explain, GateStrength::Hard)
48 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
49 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
50 sym::$feature, $explain, $level)
54 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
55 PostExpansionVisitor { parse_sess, features }.visit_attribute(attr)
58 fn find_lang_feature_issue(feature: Symbol) -> Option<u32> {
59 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.name == feature) {
60 // FIXME (#28244): enforce that active features have issue numbers
61 // assert!(info.issue.is_some())
64 // search in Accepted, Removed, or Stable Removed features
65 let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
66 .find(|t| t.name == feature);
68 Some(&Feature { issue, .. }) => issue,
69 None => panic!("Feature `{}` is not declared anywhere", feature),
79 #[derive(Debug, Copy, Clone, PartialEq)]
80 pub enum GateStrength {
81 /// A hard error. (Most feature gates should use this.)
83 /// Only a warning. (Use this only as backwards-compatibility demands.)
87 pub fn emit_feature_err(
94 feature_err(sess, feature, span, issue, explain).emit();
97 pub fn feature_err<'a, S: Into<MultiSpan>>(
103 ) -> DiagnosticBuilder<'a> {
104 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
107 fn leveled_feature_err<'a, S: Into<MultiSpan>>(
114 ) -> DiagnosticBuilder<'a> {
115 let diag = &sess.span_diagnostic;
117 let issue = match issue {
118 GateIssue::Language => find_lang_feature_issue(feature),
119 GateIssue::Library(lib) => lib,
122 let mut err = match level {
123 GateStrength::Hard => {
124 diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
126 GateStrength::Soft => diag.struct_span_warn(span, explain),
130 None | Some(0) => {} // We still accept `0` as a stand-in for backwards compatibility
133 "for more information, see https://github.com/rust-lang/rust/issues/{}",
139 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
140 if sess.unstable_features.is_nightly_build() {
141 err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
144 // If we're on stable and only emitting a "soft" warning, add a note to
145 // clarify that the feature isn't "on" (rather than being on but
147 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
148 err.help("a nightly build of the compiler is required to enable this feature");
155 const EXPLAIN_BOX_SYNTAX: &str =
156 "box expression syntax is experimental; you can call `Box::new` instead";
158 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
159 "attributes on expressions are experimental";
161 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
162 "allow_internal_unstable side-steps feature gating and stability checks";
163 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
164 "allow_internal_unsafe side-steps the unsafe_code lint";
166 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
167 "unsized tuple coercion is not stable enough for use and is subject to change";
169 struct PostExpansionVisitor<'a> {
170 parse_sess: &'a ParseSess,
171 features: &'a Features,
174 macro_rules! gate_feature_post {
175 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
176 let (cx, span) = ($cx, $span);
177 if !span.allows_unstable(sym::$feature) {
178 gate_feature!(cx, $feature, span, $explain)
181 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
182 let (cx, span) = ($cx, $span);
183 if !span.allows_unstable(sym::$feature) {
184 gate_feature!(cx, $feature, span, $explain, $level)
189 impl<'a> PostExpansionVisitor<'a> {
190 fn check_abi(&self, abi: ast::Abi) {
191 let ast::Abi { symbol, span } = abi;
193 match &*symbol.as_str() {
204 "rust-intrinsic" => {
205 gate_feature_post!(&self, intrinsics, span,
206 "intrinsics are subject to change");
208 "platform-intrinsic" => {
209 gate_feature_post!(&self, platform_intrinsics, span,
210 "platform intrinsics are experimental and possibly buggy");
213 gate_feature_post!(&self, abi_vectorcall, span,
214 "vectorcall is experimental and subject to change");
217 gate_feature_post!(&self, abi_thiscall, span,
218 "thiscall is experimental and subject to change");
221 gate_feature_post!(&self, unboxed_closures, span,
222 "rust-call ABI is subject to change");
225 gate_feature_post!(&self, abi_ptx, span,
226 "PTX ABIs are experimental and subject to change");
229 gate_feature_post!(&self, abi_unadjusted, span,
230 "unadjusted ABI is an implementation detail and perma-unstable");
232 "msp430-interrupt" => {
233 gate_feature_post!(&self, abi_msp430_interrupt, span,
234 "msp430-interrupt ABI is experimental and subject to change");
237 gate_feature_post!(&self, abi_x86_interrupt, span,
238 "x86-interrupt ABI is experimental and subject to change");
241 gate_feature_post!(&self, abi_amdgpu_kernel, span,
242 "amdgpu-kernel ABI is experimental and subject to change");
245 gate_feature_post!(&self, abi_efiapi, span,
246 "efiapi ABI is experimental and subject to change");
249 self.parse_sess.span_diagnostic.delay_span_bug(
251 &format!("unrecognized ABI not caught in lowering: {}", abi),
257 fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
258 let has_fields = variants.iter().any(|variant| match variant.data {
259 VariantData::Tuple(..) | VariantData::Struct(..) => true,
260 VariantData::Unit(..) => false,
263 let discriminant_spans = variants.iter().filter(|variant| match variant.data {
264 VariantData::Tuple(..) | VariantData::Struct(..) => false,
265 VariantData::Unit(..) => true,
267 .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
268 .collect::<Vec<_>>();
270 if !discriminant_spans.is_empty() && has_fields {
271 let mut err = feature_err(
273 sym::arbitrary_enum_discriminant,
274 discriminant_spans.clone(),
275 crate::feature_gate::GateIssue::Language,
276 "custom discriminant values are not allowed in enums with tuple or struct variants",
278 for sp in discriminant_spans {
279 err.span_label(sp, "disallowed custom discriminant");
281 for variant in variants.iter() {
282 match &variant.data {
283 VariantData::Struct(..) => {
286 "struct variant defined here",
289 VariantData::Tuple(..) => {
292 "tuple variant defined here",
295 VariantData::Unit(..) => {}
302 fn check_gat(&self, generics: &ast::Generics, span: Span) {
303 if !generics.params.is_empty() {
306 generic_associated_types,
308 "generic associated types are unstable"
311 if !generics.where_clause.predicates.is_empty() {
314 generic_associated_types,
316 "where clauses on associated types are unstable"
322 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
323 fn visit_attribute(&mut self, attr: &ast::Attribute) {
325 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
326 // Check feature gates for built-in attributes.
327 if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
328 gate_feature_fn!(self, has_feature, attr.span, name, descr, GateStrength::Hard);
330 // Check unstable flavors of the `#[doc]` attribute.
331 if attr.check_name(sym::doc) {
332 for nested_meta in attr.meta_item_list().unwrap_or_default() {
333 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
334 $(if nested_meta.check_name(sym::$name) {
335 let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
336 gate_feature!(self, $feature, attr.span, msg);
341 include => external_doc
344 spotlight => doc_spotlight
346 keyword => doc_keyword
352 fn visit_name(&mut self, sp: Span, name: ast::Name) {
353 if !name.as_str().is_ascii() {
357 self.parse_sess.source_map().def_span(sp),
358 "non-ascii idents are not fully supported"
363 fn visit_item(&mut self, i: &'a ast::Item) {
365 ast::ItemKind::ForeignMod(ref foreign_module) => {
366 self.check_abi(foreign_module.abi);
369 ast::ItemKind::Fn(..) => {
370 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
371 gate_feature_post!(&self, plugin_registrar, i.span,
372 "compiler plugins are experimental and possibly buggy");
374 if attr::contains_name(&i.attrs[..], sym::start) {
375 gate_feature_post!(&self, start, i.span,
376 "a `#[start]` function is an experimental \
377 feature whose signature may change \
380 if attr::contains_name(&i.attrs[..], sym::main) {
381 gate_feature_post!(&self, main, i.span,
382 "declaration of a non-standard `#[main]` \
383 function may change over time, for now \
384 a top-level `fn main()` is required");
388 ast::ItemKind::Struct(..) => {
389 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
390 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
391 if item.check_name(sym::simd) {
392 gate_feature_post!(&self, repr_simd, attr.span,
393 "SIMD types are experimental and possibly buggy");
399 ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
400 for variant in variants {
401 match (&variant.data, &variant.disr_expr) {
402 (ast::VariantData::Unit(..), _) => {},
403 (_, Some(disr_expr)) =>
406 arbitrary_enum_discriminant,
407 disr_expr.value.span,
408 "discriminants on non-unit variants are experimental"),
413 let has_feature = self.features.arbitrary_enum_discriminant;
414 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
415 self.maybe_report_invalid_custom_discriminants(&variants);
419 ast::ItemKind::Impl(_, polarity, defaultness, ..) => {
420 if polarity == ast::ImplPolarity::Negative {
421 gate_feature_post!(&self, optin_builtin_traits,
423 "negative trait bounds are not yet fully implemented; \
424 use marker types for now");
427 if let ast::Defaultness::Default = defaultness {
428 gate_feature_post!(&self, specialization,
430 "specialization is unstable");
434 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
435 gate_feature_post!(&self, optin_builtin_traits,
437 "auto traits are experimental and possibly buggy");
440 ast::ItemKind::TraitAlias(..) => {
445 "trait aliases are experimental"
449 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
450 let msg = "`macro` is experimental";
451 gate_feature_post!(&self, decl_macro, i.span, msg);
454 ast::ItemKind::OpaqueTy(..) => {
457 type_alias_impl_trait,
459 "`impl Trait` in type aliases is unstable"
466 visit::walk_item(self, i);
469 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
471 ast::ForeignItemKind::Fn(..) |
472 ast::ForeignItemKind::Static(..) => {
473 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
474 let links_to_llvm = match link_name {
475 Some(val) => val.as_str().starts_with("llvm."),
479 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
480 "linking to LLVM intrinsics is experimental");
483 ast::ForeignItemKind::Ty => {
484 gate_feature_post!(&self, extern_types, i.span,
485 "extern types are experimental");
487 ast::ForeignItemKind::Macro(..) => {}
490 visit::walk_foreign_item(self, i)
493 fn visit_ty(&mut self, ty: &'a ast::Ty) {
495 ast::TyKind::BareFn(ref bare_fn_ty) => {
496 self.check_abi(bare_fn_ty.abi);
498 ast::TyKind::Never => {
499 gate_feature_post!(&self, never_type, ty.span,
500 "The `!` type is experimental");
504 visit::walk_ty(self, ty)
507 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
508 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
509 if let ast::TyKind::Never = output_ty.kind {
512 self.visit_ty(output_ty)
517 fn visit_expr(&mut self, e: &'a ast::Expr) {
519 ast::ExprKind::Box(_) => {
520 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
522 ast::ExprKind::Type(..) => {
523 // To avoid noise about type ascription in common syntax errors, only emit if it
524 // is the *only* error.
525 if self.parse_sess.span_diagnostic.err_count() == 0 {
526 gate_feature_post!(&self, type_ascription, e.span,
527 "type ascription is experimental");
530 ast::ExprKind::TryBlock(_) => {
531 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
533 ast::ExprKind::Block(_, opt_label) => {
534 if let Some(label) = opt_label {
535 gate_feature_post!(&self, label_break_value, label.ident.span,
536 "labels on blocks are unstable");
541 visit::walk_expr(self, e)
544 fn visit_arm(&mut self, arm: &'a ast::Arm) {
545 visit::walk_arm(self, arm)
548 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
549 match &pattern.kind {
550 PatKind::Slice(pats) => {
553 let inner_pat = match &pat.kind {
554 PatKind::Ident(.., Some(pat)) => pat,
557 if inner_pat.is_rest() {
562 "subslice patterns are unstable"
567 PatKind::Box(..) => {
568 gate_feature_post!(&self, box_patterns,
570 "box pattern syntax is experimental");
572 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
573 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
574 "exclusive range pattern syntax is experimental");
578 visit::walk_pat(self, pattern)
581 fn visit_fn(&mut self,
583 fn_decl: &'a ast::FnDecl,
586 if let Some(header) = fn_kind.header() {
587 // Stability of const fn methods are covered in
588 // `visit_trait_item` and `visit_impl_item` below; this is
589 // because default methods don't pass through this point.
590 self.check_abi(header.abi);
593 if fn_decl.c_variadic() {
594 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
597 visit::walk_fn(self, fn_kind, fn_decl, span)
600 fn visit_generic_param(&mut self, param: &'a GenericParam) {
602 GenericParamKind::Const { .. } =>
603 gate_feature_post!(&self, const_generics, param.ident.span,
604 "const generics are unstable"),
607 visit::walk_generic_param(self, param)
610 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
611 match constraint.kind {
612 AssocTyConstraintKind::Bound { .. } =>
613 gate_feature_post!(&self, associated_type_bounds, constraint.span,
614 "associated type bounds are unstable"),
617 visit::walk_assoc_ty_constraint(self, constraint)
620 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
622 ast::TraitItemKind::Method(ref sig, ref block) => {
624 self.check_abi(sig.header.abi);
626 if sig.decl.c_variadic() {
627 gate_feature_post!(&self, c_variadic, ti.span,
628 "C-variadic functions are unstable");
630 if sig.header.constness.node == ast::Constness::Const {
631 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
634 ast::TraitItemKind::Type(_, ref default) => {
635 // We use three if statements instead of something like match guards so that all
636 // of these errors can be emitted if all cases apply.
637 if default.is_some() {
638 gate_feature_post!(&self, associated_type_defaults, ti.span,
639 "associated type defaults are unstable");
641 self.check_gat(&ti.generics, ti.span);
645 visit::walk_trait_item(self, ti)
648 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
649 if ii.defaultness == ast::Defaultness::Default {
650 gate_feature_post!(&self, specialization,
652 "specialization is unstable");
656 ast::ImplItemKind::Method(ref sig, _) => {
657 if sig.decl.c_variadic() {
658 gate_feature_post!(&self, c_variadic, ii.span,
659 "C-variadic functions are unstable");
662 ast::ImplItemKind::OpaqueTy(..) => {
665 type_alias_impl_trait,
667 "`impl Trait` in type aliases is unstable"
670 ast::ImplItemKind::TyAlias(_) => {
671 self.check_gat(&ii.generics, ii.span);
675 visit::walk_impl_item(self, ii)
678 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
679 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
680 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
681 "`crate` visibility modifier is experimental");
683 visit::walk_vis(self, vis)
687 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
688 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
689 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
690 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
691 if let Some(reason) = reason {
692 err.span_note(span, reason);
694 err.span_label(span, "feature has been removed");
699 let mut features = Features::new();
700 let mut edition_enabled_features = FxHashMap::default();
702 for &edition in ALL_EDITIONS {
703 if edition <= crate_edition {
704 // The `crate_edition` implies its respective umbrella feature-gate
705 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
706 edition_enabled_features.insert(edition.feature_name(), edition);
710 for feature in active_features_up_to(crate_edition) {
711 feature.set(&mut features, DUMMY_SP);
712 edition_enabled_features.insert(feature.name, crate_edition);
715 // Process the edition umbrella feature-gates first, to ensure
716 // `edition_enabled_features` is completed before it's queried.
717 for attr in krate_attrs {
718 if !attr.check_name(sym::feature) {
722 let list = match attr.meta_item_list() {
732 let name = mi.name_or_empty();
734 let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
735 if let Some(edition) = edition {
736 if edition <= crate_edition {
740 for feature in active_features_up_to(edition) {
741 // FIXME(Manishearth) there is currently no way to set
742 // lib features by edition
743 feature.set(&mut features, DUMMY_SP);
744 edition_enabled_features.insert(feature.name, edition);
750 for attr in krate_attrs {
751 if !attr.check_name(sym::feature) {
755 let list = match attr.meta_item_list() {
760 let bad_input = |span| {
761 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
765 let name = match mi.ident() {
766 Some(ident) if mi.is_word() => ident.name,
768 bad_input(mi.span()).span_suggestion(
770 "expected just one word",
771 format!("{}", ident.name),
772 Applicability::MaybeIncorrect,
777 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
782 if let Some(edition) = edition_enabled_features.get(&name) {
787 "the feature `{}` is included in the Rust {} edition",
794 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
795 // Handled in the separate loop above.
799 let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
800 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
801 if let Some(Feature { state, .. }) = removed.or(stable_removed) {
802 if let FeatureState::Removed { reason }
803 | FeatureState::Stabilized { reason } = state
805 feature_removed(span_handler, mi.span(), *reason);
810 if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
811 let since = Some(Symbol::intern(since));
812 features.declared_lang_features.push((name, mi.span(), since));
816 if let Some(allowed) = allow_features.as_ref() {
817 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
818 span_err!(span_handler, mi.span(), E0725,
819 "the feature `{}` is not in the list of allowed features",
825 if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
826 f.set(&mut features, mi.span());
827 features.declared_lang_features.push((name, mi.span(), None));
831 features.declared_lib_features.push((name, mi.span()));
838 fn active_features_up_to(edition: Edition) -> impl Iterator<Item=&'static Feature> {
839 ACTIVE_FEATURES.iter()
840 .filter(move |feature| {
841 if let Some(feature_edition) = feature.edition {
842 feature_edition <= edition
849 pub fn check_crate(krate: &ast::Crate,
850 parse_sess: &ParseSess,
852 unstable: UnstableFeatures) {
853 maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
854 let mut visitor = PostExpansionVisitor { parse_sess, features };
856 let spans = parse_sess.gated_spans.spans.borrow();
857 macro_rules! gate_all {
858 ($gate:ident, $msg:literal) => {
859 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
860 gate_feature!(&visitor, $gate, *span, $msg);
864 gate_all!(let_chains, "`let` expressions in this position are experimental");
865 gate_all!(async_closure, "async closures are unstable");
866 gate_all!(generators, "yield syntax is experimental");
867 gate_all!(or_patterns, "or-patterns syntax is experimental");
868 gate_all!(const_extern_fn, "`const extern fn` definitions are unstable");
870 // All uses of `gate_all!` below this point were added in #65742,
871 // and subsequently disabled (with the non-early gating readded).
872 macro_rules! gate_all {
873 ($gate:ident, $msg:literal) => {
874 // FIXME(eddyb) do something more useful than always
875 // disabling these uses of early feature-gatings.
877 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
878 gate_feature!(&visitor, $gate, *span, $msg);
884 gate_all!(trait_alias, "trait aliases are experimental");
885 gate_all!(associated_type_bounds, "associated type bounds are unstable");
886 gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
887 gate_all!(const_generics, "const generics are unstable");
888 gate_all!(decl_macro, "`macro` is experimental");
889 gate_all!(box_patterns, "box pattern syntax is experimental");
890 gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
891 gate_all!(try_blocks, "`try` blocks are unstable");
892 gate_all!(label_break_value, "labels on blocks are unstable");
893 gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
894 // To avoid noise about type ascription in common syntax errors,
895 // only emit if it is the *only* error. (Also check it last.)
896 if parse_sess.span_diagnostic.err_count() == 0 {
897 gate_all!(type_ascription, "type ascription is experimental");
900 visit::walk_crate(&mut visitor, krate);
903 #[derive(Clone, Copy, Hash)]
904 pub enum UnstableFeatures {
905 /// Hard errors for unstable features are active, as on beta/stable channels.
907 /// Allow features to be activated, as on nightly.
909 /// Errors are bypassed for bootstrapping. This is required any time
910 /// during the build that feature-related lints are set to warn or above
911 /// because the build turns on warnings-as-errors and uses lots of unstable
912 /// features. As a result, this is always required for building Rust itself.
916 impl UnstableFeatures {
917 pub fn from_environment() -> UnstableFeatures {
918 // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
919 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
920 // `true` if we should enable unstable features for bootstrapping.
921 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
922 match (disable_unstable_features, bootstrap) {
923 (_, true) => UnstableFeatures::Cheat,
924 (true, _) => UnstableFeatures::Disallow,
925 (false, _) => UnstableFeatures::Allow
929 pub fn is_nightly_build(&self) -> bool {
931 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
932 UnstableFeatures::Disallow => false,
937 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
938 if !unstable.is_nightly_build() {
939 for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
941 span_handler, attr.span, E0554,
942 "`#![feature]` may not be used on the {} release channel",
943 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")