2 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
3 use rustc_ast::{AssocConstraint, AssocConstraintKind, NodeId};
4 use rustc_ast::{PatKind, RangeEnd, VariantData};
5 use rustc_errors::{struct_span_err, Applicability, StashKey};
6 use rustc_feature::Features;
7 use rustc_feature::{AttributeGate, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
8 use rustc_session::parse::{feature_err, feature_warn};
9 use rustc_session::Session;
10 use rustc_span::source_map::Spanned;
11 use rustc_span::symbol::sym;
14 macro_rules! gate_feature_fn {
15 ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $help: expr) => {{
16 let (visitor, has_feature, span, name, explain, help) =
17 (&*$visitor, $has_feature, $span, $name, $explain, $help);
18 let has_feature: bool = has_feature(visitor.features);
19 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
20 if !has_feature && !span.allows_unstable($name) {
21 feature_err(&visitor.sess.parse_sess, name, span, explain).help(help).emit();
24 ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{
25 let (visitor, has_feature, span, name, explain) =
26 (&*$visitor, $has_feature, $span, $name, $explain);
27 let has_feature: bool = has_feature(visitor.features);
28 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
29 if !has_feature && !span.allows_unstable($name) {
30 feature_err(&visitor.sess.parse_sess, name, span, explain).emit();
33 (future_incompatible; $visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{
34 let (visitor, has_feature, span, name, explain) =
35 (&*$visitor, $has_feature, $span, $name, $explain);
36 let has_feature: bool = has_feature(visitor.features);
38 "gate_feature(feature = {:?}, span = {:?}); has? {} (future_incompatible)",
39 name, span, has_feature
41 if !has_feature && !span.allows_unstable($name) {
42 feature_warn(&visitor.sess.parse_sess, name, span, explain);
47 macro_rules! gate_feature_post {
48 ($visitor: expr, $feature: ident, $span: expr, $explain: expr, $help: expr) => {
49 gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain, $help)
51 ($visitor: expr, $feature: ident, $span: expr, $explain: expr) => {
52 gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain)
54 (future_incompatible; $visitor: expr, $feature: ident, $span: expr, $explain: expr) => {
55 gate_feature_fn!(future_incompatible; $visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain)
59 pub fn check_attribute(attr: &ast::Attribute, sess: &Session, features: &Features) {
60 PostExpansionVisitor { sess, features }.visit_attribute(attr)
63 struct PostExpansionVisitor<'a> {
66 // `sess` contains a `Features`, but this might not be that one.
67 features: &'a Features,
70 impl<'a> PostExpansionVisitor<'a> {
71 fn check_abi(&self, abi: ast::StrLit, constness: ast::Const) {
72 let ast::StrLit { symbol_unescaped, span, .. } = abi;
74 if let ast::Const::Yes(_) = constness {
75 match symbol_unescaped {
77 sym::Rust | sym::C => {}
78 abi => gate_feature_post!(
82 &format!("`{}` as a `const fn` ABI is unstable", abi)
87 match symbol_unescaped.as_str() {
89 "Rust" | "C" | "cdecl" | "stdcall" | "fastcall" | "aapcs" | "win64" | "sysv64"
92 gate_feature_post!(&self, intrinsics, span, "intrinsics are subject to change");
94 "platform-intrinsic" => {
99 "platform intrinsics are experimental and possibly buggy"
107 "vectorcall is experimental and subject to change"
115 "thiscall is experimental and subject to change"
123 "rust-call ABI is subject to change"
131 "rust-cold is experimental and subject to change"
139 "PTX ABIs are experimental and subject to change"
147 "unadjusted ABI is an implementation detail and perma-unstable"
150 "msp430-interrupt" => {
153 abi_msp430_interrupt,
155 "msp430-interrupt ABI is experimental and subject to change"
163 "x86-interrupt ABI is experimental and subject to change"
171 "amdgpu-kernel ABI is experimental and subject to change"
174 "avr-interrupt" | "avr-non-blocking-interrupt" => {
179 "avr-interrupt and avr-non-blocking-interrupt ABIs are experimental and subject to change"
187 "efiapi ABI is experimental and subject to change"
190 "C-cmse-nonsecure-call" => {
193 abi_c_cmse_nonsecure_call,
195 "C-cmse-nonsecure-call ABI is experimental and subject to change"
203 "C-unwind ABI is experimental and subject to change"
206 "stdcall-unwind" => {
211 "stdcall-unwind ABI is experimental and subject to change"
219 "system-unwind ABI is experimental and subject to change"
222 "thiscall-unwind" => {
227 "thiscall-unwind ABI is experimental and subject to change"
235 "cdecl-unwind ABI is experimental and subject to change"
238 "fastcall-unwind" => {
243 "fastcall-unwind ABI is experimental and subject to change"
246 "vectorcall-unwind" => {
251 "vectorcall-unwind ABI is experimental and subject to change"
259 "aapcs-unwind ABI is experimental and subject to change"
267 "win64-unwind ABI is experimental and subject to change"
275 "sysv64-unwind ABI is experimental and subject to change"
283 "wasm ABI is experimental and subject to change"
287 if self.sess.opts.pretty.map_or(true, |ppm| ppm.needs_hir()) {
288 self.sess.parse_sess.span_diagnostic.delay_span_bug(
290 &format!("unrecognized ABI not caught in lowering: {}", abi),
297 fn check_extern(&self, ext: ast::Extern, constness: ast::Const) {
298 if let ast::Extern::Explicit(abi, _) = ext {
299 self.check_abi(abi, constness);
303 fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
304 let has_fields = variants.iter().any(|variant| match variant.data {
305 VariantData::Tuple(..) | VariantData::Struct(..) => true,
306 VariantData::Unit(..) => false,
309 let discriminant_spans = variants
311 .filter(|variant| match variant.data {
312 VariantData::Tuple(..) | VariantData::Struct(..) => false,
313 VariantData::Unit(..) => true,
315 .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
316 .collect::<Vec<_>>();
318 if !discriminant_spans.is_empty() && has_fields {
319 let mut err = feature_err(
320 &self.sess.parse_sess,
321 sym::arbitrary_enum_discriminant,
322 discriminant_spans.clone(),
323 "custom discriminant values are not allowed in enums with tuple or struct variants",
325 for sp in discriminant_spans {
326 err.span_label(sp, "disallowed custom discriminant");
328 for variant in variants.iter() {
329 match &variant.data {
330 VariantData::Struct(..) => {
331 err.span_label(variant.span, "struct variant defined here");
333 VariantData::Tuple(..) => {
334 err.span_label(variant.span, "tuple variant defined here");
336 VariantData::Unit(..) => {}
343 /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
344 fn check_impl_trait(&self, ty: &ast::Ty) {
345 struct ImplTraitVisitor<'a> {
346 vis: &'a PostExpansionVisitor<'a>,
348 impl Visitor<'_> for ImplTraitVisitor<'_> {
349 fn visit_ty(&mut self, ty: &ast::Ty) {
350 if let ast::TyKind::ImplTrait(..) = ty.kind {
353 type_alias_impl_trait,
355 "`impl Trait` in type aliases is unstable"
358 visit::walk_ty(self, ty);
361 ImplTraitVisitor { vis: self }.visit_ty(ty);
365 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
366 fn visit_attribute(&mut self, attr: &ast::Attribute) {
367 let attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
368 // Check feature gates for built-in attributes.
369 if let Some(BuiltinAttribute {
370 gate: AttributeGate::Gated(_, name, descr, has_feature),
374 gate_feature_fn!(self, has_feature, attr.span, *name, descr);
376 // Check unstable flavors of the `#[doc]` attribute.
377 if attr.has_name(sym::doc) {
378 for nested_meta in attr.meta_item_list().unwrap_or_default() {
379 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
380 $(if nested_meta.has_name(sym::$name) {
381 let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
382 gate_feature_post!(self, $feature, attr.span, msg);
388 cfg_hide => doc_cfg_hide
390 notable_trait => doc_notable_trait
393 if nested_meta.has_name(sym::keyword) {
394 let msg = "`#[doc(keyword)]` is meant for internal use only";
395 gate_feature_post!(self, rustdoc_internals, attr.span, msg);
398 if nested_meta.has_name(sym::fake_variadic) {
399 let msg = "`#[doc(fake_variadic)]` is meant for internal use only";
400 gate_feature_post!(self, rustdoc_internals, attr.span, msg);
405 // Emit errors for non-staged-api crates.
406 if !self.features.staged_api {
407 if attr.has_name(sym::unstable)
408 || attr.has_name(sym::stable)
409 || attr.has_name(sym::rustc_const_unstable)
410 || attr.has_name(sym::rustc_const_stable)
411 || attr.has_name(sym::rustc_default_body_unstable)
417 "stability attributes may not be used outside of the standard library",
424 fn visit_item(&mut self, i: &'a ast::Item) {
426 ast::ItemKind::ForeignMod(ref foreign_module) => {
427 if let Some(abi) = foreign_module.abi {
428 self.check_abi(abi, ast::Const::No);
432 ast::ItemKind::Fn(..) => {
433 if self.sess.contains_name(&i.attrs, sym::start) {
438 "`#[start]` functions are experimental \
439 and their signature may change \
445 ast::ItemKind::Struct(..) => {
446 for attr in self.sess.filter_by_name(&i.attrs, sym::repr) {
447 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
448 if item.has_name(sym::simd) {
453 "SIMD types are experimental and possibly buggy"
460 ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => {
461 for variant in variants {
462 match (&variant.data, &variant.disr_expr) {
463 (ast::VariantData::Unit(..), _) => {}
464 (_, Some(disr_expr)) => gate_feature_post!(
466 arbitrary_enum_discriminant,
467 disr_expr.value.span,
468 "discriminants on non-unit variants are experimental"
474 let has_feature = self.features.arbitrary_enum_discriminant;
475 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
476 self.maybe_report_invalid_custom_discriminants(&variants);
480 ast::ItemKind::Impl(box ast::Impl { polarity, defaultness, ref of_trait, .. }) => {
481 if let ast::ImplPolarity::Negative(span) = polarity {
485 span.to(of_trait.as_ref().map_or(span, |t| t.path.span)),
486 "negative trait bounds are not yet fully implemented; \
487 use marker types for now"
491 if let ast::Defaultness::Default(_) = defaultness {
492 gate_feature_post!(&self, specialization, i.span, "specialization is unstable");
496 ast::ItemKind::Trait(box ast::Trait { is_auto: ast::IsAuto::Yes, .. }) => {
501 "auto traits are experimental and possibly buggy"
505 ast::ItemKind::TraitAlias(..) => {
506 gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental");
509 ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => {
510 let msg = "`macro` is experimental";
511 gate_feature_post!(&self, decl_macro, i.span, msg);
514 ast::ItemKind::TyAlias(box ast::TyAlias { ty: Some(ref ty), .. }) => {
515 self.check_impl_trait(&ty)
521 visit::walk_item(self, i);
524 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
526 ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
527 let link_name = self.sess.first_attr_value_str_by_name(&i.attrs, sym::link_name);
529 link_name.map_or(false, |val| val.as_str().starts_with("llvm."));
533 link_llvm_intrinsics,
535 "linking to LLVM intrinsics is experimental"
539 ast::ForeignItemKind::TyAlias(..) => {
540 gate_feature_post!(&self, extern_types, i.span, "extern types are experimental");
542 ast::ForeignItemKind::MacCall(..) => {}
545 visit::walk_foreign_item(self, i)
548 fn visit_ty(&mut self, ty: &'a ast::Ty) {
550 ast::TyKind::BareFn(ref bare_fn_ty) => {
551 // Function pointers cannot be `const`
552 self.check_extern(bare_fn_ty.ext, ast::Const::No);
554 ast::TyKind::Never => {
555 gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental");
557 ast::TyKind::TraitObject(_, ast::TraitObjectSyntax::DynStar, ..) => {
558 gate_feature_post!(&self, dyn_star, ty.span, "dyn* trait objects are unstable");
562 visit::walk_ty(self, ty)
565 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
566 if let ast::FnRetTy::Ty(ref output_ty) = *ret_ty {
567 if let ast::TyKind::Never = output_ty.kind {
570 self.visit_ty(output_ty)
575 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
576 if let ast::StmtKind::Semi(expr) = &stmt.kind
577 && let ast::ExprKind::Assign(lhs, _, _) = &expr.kind
578 && let ast::ExprKind::Type(..) = lhs.kind
579 && self.sess.parse_sess.span_diagnostic.err_count() == 0
580 && !self.features.type_ascription
581 && !lhs.span.allows_unstable(sym::type_ascription)
583 // When we encounter a statement of the form `foo: Ty = val;`, this will emit a type
584 // ascription error, but the likely intention was to write a `let` statement. (#78907).
586 &self.sess.parse_sess,
587 sym::type_ascription,
589 "type ascription is experimental",
590 ).span_suggestion_verbose(
591 lhs.span.shrink_to_lo(),
592 "you might have meant to introduce a new binding",
594 Applicability::MachineApplicable,
597 visit::walk_stmt(self, stmt);
600 fn visit_expr(&mut self, e: &'a ast::Expr) {
602 ast::ExprKind::Box(_) => {
607 "box expression syntax is experimental; you can call `Box::new` instead"
610 ast::ExprKind::Type(..) => {
611 if self.sess.parse_sess.span_diagnostic.err_count() == 0 {
612 // To avoid noise about type ascription in common syntax errors,
613 // only emit if it is the *only* error.
618 "type ascription is experimental"
621 // And if it isn't, cancel the early-pass warning.
625 .steal_diagnostic(e.span, StashKey::EarlySyntaxWarning)
626 .map(|err| err.cancel());
629 ast::ExprKind::TryBlock(_) => {
630 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
634 visit::walk_expr(self, e)
637 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
638 match &pattern.kind {
639 PatKind::Slice(pats) => {
641 let inner_pat = match &pat.kind {
642 PatKind::Ident(.., Some(pat)) => pat,
645 if let PatKind::Range(Some(_), None, Spanned { .. }) = inner_pat.kind {
648 half_open_range_patterns,
650 "`X..` patterns in slices are experimental"
655 PatKind::Box(..) => {
660 "box pattern syntax is experimental"
663 PatKind::Range(_, Some(_), Spanned { node: RangeEnd::Excluded, .. }) => {
666 exclusive_range_pattern,
668 "exclusive range pattern syntax is experimental"
673 visit::walk_pat(self, pattern)
676 fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
677 if let Some(header) = fn_kind.header() {
678 // Stability of const fn methods are covered in `visit_assoc_item` below.
679 self.check_extern(header.ext, header.constness);
682 if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
683 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
686 visit::walk_fn(self, fn_kind)
689 fn visit_assoc_constraint(&mut self, constraint: &'a AssocConstraint) {
690 if let AssocConstraintKind::Bound { .. } = constraint.kind {
693 associated_type_bounds,
695 "associated type bounds are unstable"
698 visit::walk_assoc_constraint(self, constraint)
701 fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
702 let is_fn = match i.kind {
703 ast::AssocItemKind::Fn(_) => true,
704 ast::AssocItemKind::TyAlias(box ast::TyAlias { ref ty, .. }) => {
705 if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
708 associated_type_defaults,
710 "associated type defaults are unstable"
713 if let Some(ty) = ty {
714 self.check_impl_trait(ty);
720 if let ast::Defaultness::Default(_) = i.kind.defaultness() {
721 // Limit `min_specialization` to only specializing functions.
724 |x: &Features| x.specialization || (is_fn && x.min_specialization),
727 "specialization is unstable"
730 visit::walk_assoc_item(self, i, ctxt)
734 pub fn check_crate(krate: &ast::Crate, sess: &Session) {
735 maybe_stage_features(sess, krate);
736 check_incompatible_features(sess);
737 let mut visitor = PostExpansionVisitor { sess, features: &sess.features_untracked() };
739 let spans = sess.parse_sess.gated_spans.spans.borrow();
740 macro_rules! gate_all {
741 ($gate:ident, $msg:literal, $help:literal) => {
742 if let Some(spans) = spans.get(&sym::$gate) {
744 gate_feature_post!(&visitor, $gate, *span, $msg, $help);
748 ($gate:ident, $msg:literal) => {
749 if let Some(spans) = spans.get(&sym::$gate) {
751 gate_feature_post!(&visitor, $gate, *span, $msg);
758 "`if let` guards are experimental",
759 "you can write `if matches!(<expr>, <pattern>)` instead of `if let <pattern> = <expr>`"
761 gate_all!(let_chains, "`let` expressions in this position are unstable");
764 "async closures are unstable",
765 "to use an async block, remove the `||`: `async {`"
768 closure_lifetime_binder,
769 "`for<...>` binders for closures are experimental",
770 "consider removing `for<...>`"
772 gate_all!(more_qualified_paths, "usage of qualified paths in this context is experimental");
773 gate_all!(generators, "yield syntax is experimental");
774 gate_all!(raw_ref_op, "raw address of syntax is experimental");
775 gate_all!(const_trait_impl, "const trait impls are experimental");
776 gate_all!(half_open_range_patterns, "half-open range patterns are unstable");
777 gate_all!(inline_const, "inline-const is experimental");
778 gate_all!(inline_const_pat, "inline-const in pattern position is experimental");
779 gate_all!(associated_const_equality, "associated const equality is incomplete");
780 gate_all!(yeet_expr, "`do yeet` expression is experimental");
782 // All uses of `gate_all!` below this point were added in #65742,
783 // and subsequently disabled (with the non-early gating readded).
784 // We emit an early future-incompatible warning for these.
785 // New syntax gates should go above here to get a hard error gate.
786 macro_rules! gate_all {
787 ($gate:ident, $msg:literal) => {
788 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
789 gate_feature_post!(future_incompatible; &visitor, $gate, *span, $msg);
794 gate_all!(trait_alias, "trait aliases are experimental");
795 gate_all!(associated_type_bounds, "associated type bounds are unstable");
796 gate_all!(decl_macro, "`macro` is experimental");
797 gate_all!(box_patterns, "box pattern syntax is experimental");
798 gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
799 gate_all!(try_blocks, "`try` blocks are unstable");
800 gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
801 gate_all!(type_ascription, "type ascription is experimental");
803 visit::walk_crate(&mut visitor, krate);
806 fn maybe_stage_features(sess: &Session, krate: &ast::Crate) {
807 // checks if `#![feature]` has been used to enable any lang feature
808 // does not check the same for lib features unless there's at least one
809 // declared lang feature
810 if !sess.opts.unstable_features.is_nightly_build() {
811 let lang_features = &sess.features_untracked().declared_lang_features;
812 if lang_features.len() == 0 {
815 for attr in krate.attrs.iter().filter(|attr| attr.has_name(sym::feature)) {
816 let mut err = struct_span_err!(
817 sess.parse_sess.span_diagnostic,
820 "`#![feature]` may not be used on the {} release channel",
821 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")
823 let mut all_stable = true;
825 attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident())
827 let name = ident.name;
828 let stable_since = lang_features
830 .flat_map(|&(feature, _, since)| if feature == name { since } else { None })
832 if let Some(since) = stable_since {
834 "the feature `{}` has been stable since {} and no longer requires \
835 an attribute to enable",
845 "remove the attribute",
847 Applicability::MachineApplicable,
855 fn check_incompatible_features(sess: &Session) {
856 let features = sess.features_untracked();
858 let declared_features = features
859 .declared_lang_features
862 .map(|(name, span, _)| (name, span))
863 .chain(features.declared_lib_features.iter().copied());
865 for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES
867 .filter(|&&(f1, f2)| features.enabled(f1) && features.enabled(f2))
869 if let Some((f1_name, f1_span)) = declared_features.clone().find(|(name, _)| name == f1) {
870 if let Some((f2_name, f2_span)) = declared_features.clone().find(|(name, _)| name == f2)
872 let spans = vec![f1_span, f2_span];
873 sess.struct_span_err(
876 "features `{}` and `{}` are incompatible, using them at the same time \
881 .help("remove one of these features")