2 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
3 use rustc_ast::{AssocTyConstraint, AssocTyConstraintKind, NodeId};
4 use rustc_ast::{PatKind, RangeEnd, VariantData};
5 use rustc_errors::struct_span_err;
6 use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP};
7 use rustc_feature::{Features, GateIssue};
8 use rustc_session::parse::{feature_err, feature_err_issue};
9 use rustc_session::Session;
10 use rustc_span::source_map::Spanned;
11 use rustc_span::symbol::sym;
16 macro_rules! gate_feature_fn {
17 ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $help: expr) => {{
18 let (visitor, has_feature, span, name, explain, help) =
19 (&*$visitor, $has_feature, $span, $name, $explain, $help);
20 let has_feature: bool = has_feature(visitor.features);
21 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
22 if !has_feature && !span.allows_unstable($name) {
23 feature_err_issue(&visitor.sess.parse_sess, name, span, GateIssue::Language, explain)
28 ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{
29 let (visitor, has_feature, span, name, explain) =
30 (&*$visitor, $has_feature, $span, $name, $explain);
31 let has_feature: bool = has_feature(visitor.features);
32 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
33 if !has_feature && !span.allows_unstable($name) {
34 feature_err_issue(&visitor.sess.parse_sess, name, span, GateIssue::Language, explain)
40 macro_rules! gate_feature_post {
41 ($visitor: expr, $feature: ident, $span: expr, $explain: expr, $help: expr) => {
42 gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain, $help)
44 ($visitor: expr, $feature: ident, $span: expr, $explain: expr) => {
45 gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain)
49 pub fn check_attribute(attr: &ast::Attribute, sess: &Session, features: &Features) {
50 PostExpansionVisitor { sess, features }.visit_attribute(attr)
53 struct PostExpansionVisitor<'a> {
56 // `sess` contains a `Features`, but this might not be that one.
57 features: &'a Features,
60 impl<'a> PostExpansionVisitor<'a> {
61 fn check_abi(&self, abi: ast::StrLit) {
62 let ast::StrLit { symbol_unescaped, span, .. } = abi;
64 match &*symbol_unescaped.as_str() {
66 "Rust" | "C" | "cdecl" | "stdcall" | "fastcall" | "aapcs" | "win64" | "sysv64"
69 gate_feature_post!(&self, intrinsics, span, "intrinsics are subject to change");
71 "platform-intrinsic" => {
76 "platform intrinsics are experimental and possibly buggy"
84 "vectorcall is experimental and subject to change"
92 "thiscall is experimental and subject to change"
100 "rust-call ABI is subject to change"
108 "PTX ABIs are experimental and subject to change"
116 "unadjusted ABI is an implementation detail and perma-unstable"
119 "msp430-interrupt" => {
122 abi_msp430_interrupt,
124 "msp430-interrupt ABI is experimental and subject to change"
132 "x86-interrupt ABI is experimental and subject to change"
140 "amdgpu-kernel ABI is experimental and subject to change"
143 "avr-interrupt" | "avr-non-blocking-interrupt" => {
148 "avr-interrupt and avr-non-blocking-interrupt ABIs are experimental and subject to change"
156 "efiapi ABI is experimental and subject to change"
159 "C-cmse-nonsecure-call" => {
162 abi_c_cmse_nonsecure_call,
164 "C-cmse-nonsecure-call ABI is experimental and subject to change"
172 "C-unwind ABI is experimental and subject to change"
175 "stdcall-unwind" => {
180 "stdcall-unwind ABI is experimental and subject to change"
188 "system-unwind ABI is experimental and subject to change"
191 "thiscall-unwind" => {
196 "thiscall-unwind ABI is experimental and subject to change"
204 "wasm ABI is experimental and subject to change"
211 .delay_span_bug(span, &format!("unrecognized ABI not caught in lowering: {}", abi)),
215 fn check_extern(&self, ext: ast::Extern) {
216 if let ast::Extern::Explicit(abi) = ext {
221 fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
222 let has_fields = variants.iter().any(|variant| match variant.data {
223 VariantData::Tuple(..) | VariantData::Struct(..) => true,
224 VariantData::Unit(..) => false,
227 let discriminant_spans = variants
229 .filter(|variant| match variant.data {
230 VariantData::Tuple(..) | VariantData::Struct(..) => false,
231 VariantData::Unit(..) => true,
233 .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
234 .collect::<Vec<_>>();
236 if !discriminant_spans.is_empty() && has_fields {
237 let mut err = feature_err(
238 &self.sess.parse_sess,
239 sym::arbitrary_enum_discriminant,
240 discriminant_spans.clone(),
241 "custom discriminant values are not allowed in enums with tuple or struct variants",
243 for sp in discriminant_spans {
244 err.span_label(sp, "disallowed custom discriminant");
246 for variant in variants.iter() {
247 match &variant.data {
248 VariantData::Struct(..) => {
249 err.span_label(variant.span, "struct variant defined here");
251 VariantData::Tuple(..) => {
252 err.span_label(variant.span, "tuple variant defined here");
254 VariantData::Unit(..) => {}
261 fn check_gat(&self, generics: &ast::Generics, span: Span) {
262 if !generics.params.is_empty() {
265 generic_associated_types,
267 "generic associated types are unstable"
270 if !generics.where_clause.predicates.is_empty() {
273 generic_associated_types,
275 "where clauses on associated types are unstable"
280 /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
281 fn check_impl_trait(&self, ty: &ast::Ty) {
282 struct ImplTraitVisitor<'a> {
283 vis: &'a PostExpansionVisitor<'a>,
285 impl Visitor<'_> for ImplTraitVisitor<'_> {
286 fn visit_ty(&mut self, ty: &ast::Ty) {
287 if let ast::TyKind::ImplTrait(..) = ty.kind {
290 min_type_alias_impl_trait,
292 "`impl Trait` in type aliases is unstable"
295 visit::walk_ty(self, ty);
298 ImplTraitVisitor { vis: self }.visit_ty(ty);
302 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
303 fn visit_attribute(&mut self, attr: &ast::Attribute) {
305 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
306 // Check feature gates for built-in attributes.
307 if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
308 gate_feature_fn!(self, has_feature, attr.span, name, descr);
310 // Check unstable flavors of the `#[doc]` attribute.
311 if self.sess.check_name(attr, sym::doc) {
312 for nested_meta in attr.meta_item_list().unwrap_or_default() {
313 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
314 $(if nested_meta.has_name(sym::$name) {
315 let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
316 gate_feature_post!(self, $feature, attr.span, msg);
321 include => external_doc
324 notable_trait => doc_notable_trait
325 keyword => doc_keyword
330 // Check for unstable modifiers on `#[link(..)]` attribute
331 if self.sess.check_name(attr, sym::link) {
332 for nested_meta in attr.meta_item_list().unwrap_or_default() {
333 if nested_meta.has_name(sym::modifiers) {
336 native_link_modifiers,
338 "native link modifiers are experimental"
341 if let Some(modifiers) = nested_meta.value_str() {
342 for modifier in modifiers.as_str().split(',') {
343 if let Some(modifier) = modifier.strip_prefix(&['+', '-'][..]) {
344 macro_rules! gate_modifier { ($($name:literal => $feature:ident)*) => {
345 $(if modifier == $name {
346 let msg = concat!("`#[link(modifiers=\"", $name, "\")]` is unstable");
350 nested_meta.name_value_literal_span().unwrap(),
357 "bundle" => native_link_modifiers_bundle
358 "verbatim" => native_link_modifiers_verbatim
359 "whole-archive" => native_link_modifiers_whole_archive
360 "as-needed" => native_link_modifiers_as_needed
370 fn visit_item(&mut self, i: &'a ast::Item) {
372 ast::ItemKind::ForeignMod(ref foreign_module) => {
373 if let Some(abi) = foreign_module.abi {
378 ast::ItemKind::Fn(..) => {
379 if self.sess.contains_name(&i.attrs[..], sym::plugin_registrar) {
384 "compiler plugins are experimental and possibly buggy"
387 if self.sess.contains_name(&i.attrs[..], sym::start) {
392 "`#[start]` functions are experimental \
393 and their signature may change \
399 ast::ItemKind::Struct(..) => {
400 for attr in self.sess.filter_by_name(&i.attrs[..], sym::repr) {
401 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
402 if item.has_name(sym::simd) {
407 "SIMD types are experimental and possibly buggy"
414 ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => {
415 for variant in variants {
416 match (&variant.data, &variant.disr_expr) {
417 (ast::VariantData::Unit(..), _) => {}
418 (_, Some(disr_expr)) => gate_feature_post!(
420 arbitrary_enum_discriminant,
421 disr_expr.value.span,
422 "discriminants on non-unit variants are experimental"
428 let has_feature = self.features.arbitrary_enum_discriminant;
429 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
430 self.maybe_report_invalid_custom_discriminants(&variants);
434 ast::ItemKind::Impl(box ast::ImplKind {
435 polarity, defaultness, ref of_trait, ..
437 if let ast::ImplPolarity::Negative(span) = polarity {
441 span.to(of_trait.as_ref().map_or(span, |t| t.path.span)),
442 "negative trait bounds are not yet fully implemented; \
443 use marker types for now"
447 if let ast::Defaultness::Default(_) = defaultness {
448 gate_feature_post!(&self, specialization, i.span, "specialization is unstable");
452 ast::ItemKind::Trait(box ast::TraitKind(ast::IsAuto::Yes, ..)) => {
457 "auto traits are experimental and possibly buggy"
461 ast::ItemKind::TraitAlias(..) => {
462 gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental");
465 ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => {
466 let msg = "`macro` is experimental";
467 gate_feature_post!(&self, decl_macro, i.span, msg);
470 ast::ItemKind::TyAlias(box ast::TyAliasKind(_, _, _, Some(ref ty))) => {
471 self.check_impl_trait(&ty)
477 visit::walk_item(self, i);
480 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
482 ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
483 let link_name = self.sess.first_attr_value_str_by_name(&i.attrs, sym::link_name);
485 link_name.map_or(false, |val| val.as_str().starts_with("llvm."));
489 link_llvm_intrinsics,
491 "linking to LLVM intrinsics is experimental"
495 ast::ForeignItemKind::TyAlias(..) => {
496 gate_feature_post!(&self, extern_types, i.span, "extern types are experimental");
498 ast::ForeignItemKind::MacCall(..) => {}
501 visit::walk_foreign_item(self, i)
504 fn visit_ty(&mut self, ty: &'a ast::Ty) {
506 ast::TyKind::BareFn(ref bare_fn_ty) => {
507 self.check_extern(bare_fn_ty.ext);
509 ast::TyKind::Never => {
510 gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental");
514 visit::walk_ty(self, ty)
517 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
518 if let ast::FnRetTy::Ty(ref output_ty) = *ret_ty {
519 if let ast::TyKind::Never = output_ty.kind {
522 self.visit_ty(output_ty)
527 fn visit_expr(&mut self, e: &'a ast::Expr) {
529 ast::ExprKind::Box(_) => {
534 "box expression syntax is experimental; you can call `Box::new` instead"
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.sess.parse_sess.span_diagnostic.err_count() == 0 {
545 "type ascription is experimental"
549 ast::ExprKind::TryBlock(_) => {
550 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
552 ast::ExprKind::Block(_, opt_label) => {
553 if let Some(label) = opt_label {
558 "labels on blocks are unstable"
564 visit::walk_expr(self, e)
567 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
568 match &pattern.kind {
569 PatKind::Box(..) => {
574 "box pattern syntax is experimental"
577 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
580 exclusive_range_pattern,
582 "exclusive range pattern syntax is experimental"
587 visit::walk_pat(self, pattern)
590 fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
591 if let Some(header) = fn_kind.header() {
592 // Stability of const fn methods are covered in `visit_assoc_item` below.
593 self.check_extern(header.ext);
595 if let (ast::Const::Yes(_), ast::Extern::Implicit)
596 | (ast::Const::Yes(_), ast::Extern::Explicit(_)) = (header.constness, header.ext)
602 "`const extern fn` definitions are unstable"
607 if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
608 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
611 visit::walk_fn(self, fn_kind, span)
614 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
615 if let AssocTyConstraintKind::Bound { .. } = constraint.kind {
618 associated_type_bounds,
620 "associated type bounds are unstable"
623 visit::walk_assoc_ty_constraint(self, constraint)
626 fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
627 let is_fn = match i.kind {
628 ast::AssocItemKind::Fn(_) => true,
629 ast::AssocItemKind::TyAlias(box ast::TyAliasKind(_, ref generics, _, ref ty)) => {
630 if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
633 associated_type_defaults,
635 "associated type defaults are unstable"
638 if let Some(ty) = ty {
639 self.check_impl_trait(ty);
641 self.check_gat(generics, i.span);
646 if let ast::Defaultness::Default(_) = i.kind.defaultness() {
647 // Limit `min_specialization` to only specializing functions.
650 |x: &Features| x.specialization || (is_fn && x.min_specialization),
653 "specialization is unstable"
656 visit::walk_assoc_item(self, i, ctxt)
659 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
660 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.kind {
663 crate_visibility_modifier,
665 "`crate` visibility modifier is experimental"
668 visit::walk_vis(self, vis)
672 pub fn check_crate(krate: &ast::Crate, sess: &Session) {
673 maybe_stage_features(sess, krate);
674 check_incompatible_features(sess);
675 let mut visitor = PostExpansionVisitor { sess, features: &sess.features_untracked() };
677 let spans = sess.parse_sess.gated_spans.spans.borrow();
678 macro_rules! gate_all {
679 ($gate:ident, $msg:literal, $help:literal) => {
680 if let Some(spans) = spans.get(&sym::$gate) {
682 gate_feature_post!(&visitor, $gate, *span, $msg, $help);
686 ($gate:ident, $msg:literal) => {
687 if let Some(spans) = spans.get(&sym::$gate) {
689 gate_feature_post!(&visitor, $gate, *span, $msg);
696 "`if let` guards are experimental",
697 "you can write `if matches!(<expr>, <pattern>)` instead of `if let <pattern> = <expr>`"
701 "`let` expressions in this position are experimental",
702 "you can write `matches!(<expr>, <pattern>)` instead of `let <pattern> = <expr>`"
706 "async closures are unstable",
707 "to use an async block, remove the `||`: `async {`"
709 gate_all!(generators, "yield syntax is experimental");
710 gate_all!(raw_ref_op, "raw address of syntax is experimental");
711 gate_all!(const_trait_bound_opt_out, "`?const` on trait bounds is experimental");
712 gate_all!(const_trait_impl, "const trait impls are experimental");
713 gate_all!(half_open_range_patterns, "half-open range patterns are unstable");
714 gate_all!(inline_const, "inline-const is experimental");
716 const_generics_defaults,
717 "default values for const generic parameters are experimental"
719 if sess.parse_sess.span_diagnostic.err_count() == 0 {
720 // Errors for `destructuring_assignment` can get quite noisy, especially where `_` is
721 // involved, so we only emit errors where there are no other parsing errors.
722 gate_all!(destructuring_assignment, "destructuring assignments are unstable");
724 gate_all!(unnamed_fields, "unnamed fields are not yet fully implemented");
726 // All uses of `gate_all!` below this point were added in #65742,
727 // and subsequently disabled (with the non-early gating readded).
728 macro_rules! gate_all {
729 ($gate:ident, $msg:literal) => {
730 // FIXME(eddyb) do something more useful than always
731 // disabling these uses of early feature-gatings.
733 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
734 gate_feature_post!(&visitor, $gate, *span, $msg);
740 gate_all!(trait_alias, "trait aliases are experimental");
741 gate_all!(associated_type_bounds, "associated type bounds are unstable");
742 gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
743 gate_all!(const_generics, "const generics are unstable");
744 gate_all!(decl_macro, "`macro` is experimental");
745 gate_all!(box_patterns, "box pattern syntax is experimental");
746 gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
747 gate_all!(try_blocks, "`try` blocks are unstable");
748 gate_all!(label_break_value, "labels on blocks are unstable");
749 gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
750 // To avoid noise about type ascription in common syntax errors,
751 // only emit if it is the *only* error. (Also check it last.)
752 if sess.parse_sess.span_diagnostic.err_count() == 0 {
753 gate_all!(type_ascription, "type ascription is experimental");
756 visit::walk_crate(&mut visitor, krate);
759 fn maybe_stage_features(sess: &Session, krate: &ast::Crate) {
760 use rustc_errors::Applicability;
762 if !sess.opts.unstable_features.is_nightly_build() {
763 let lang_features = &sess.features_untracked().declared_lang_features;
764 for attr in krate.attrs.iter().filter(|attr| sess.check_name(attr, sym::feature)) {
765 let mut err = struct_span_err!(
766 sess.parse_sess.span_diagnostic,
769 "`#![feature]` may not be used on the {} release channel",
770 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")
772 let mut all_stable = true;
774 attr.meta_item_list().into_iter().flatten().map(|nested| nested.ident()).flatten()
776 let name = ident.name;
777 let stable_since = lang_features
779 .flat_map(|&(feature, _, since)| if feature == name { since } else { None })
781 if let Some(since) = stable_since {
783 "the feature `{}` has been stable since {} and no longer requires \
784 an attribute to enable",
794 "remove the attribute",
796 Applicability::MachineApplicable,
804 fn check_incompatible_features(sess: &Session) {
805 let features = sess.features_untracked();
807 let declared_features = features
808 .declared_lang_features
811 .map(|(name, span, _)| (name, span))
812 .chain(features.declared_lib_features.iter().copied());
814 for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES
816 .filter(|&&(f1, f2)| features.enabled(f1) && features.enabled(f2))
818 if let Some((f1_name, f1_span)) = declared_features.clone().find(|(name, _)| name == f1) {
819 if let Some((f2_name, f2_span)) = declared_features.clone().find(|(name, _)| name == f2)
821 let spans = vec![f1_span, f2_span];
822 sess.struct_span_err(
825 "features `{}` and `{}` are incompatible, using them at the same time \
830 .help("remove one of these features")