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;
6 use rustc_feature::{AttributeGate, BuiltinAttribute, 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 "cdecl-unwind ABI is experimental and subject to change"
207 "fastcall-unwind" => {
212 "fastcall-unwind ABI is experimental and subject to change"
215 "vectorcall-unwind" => {
220 "vectorcall-unwind ABI is experimental and subject to change"
228 "aapcs-unwind ABI is experimental and subject to change"
236 "win64-unwind ABI is experimental and subject to change"
244 "sysv64-unwind ABI is experimental and subject to change"
252 "wasm ABI is experimental and subject to change"
259 .delay_span_bug(span, &format!("unrecognized ABI not caught in lowering: {}", abi)),
263 fn check_extern(&self, ext: ast::Extern) {
264 if let ast::Extern::Explicit(abi) = ext {
269 fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
270 let has_fields = variants.iter().any(|variant| match variant.data {
271 VariantData::Tuple(..) | VariantData::Struct(..) => true,
272 VariantData::Unit(..) => false,
275 let discriminant_spans = variants
277 .filter(|variant| match variant.data {
278 VariantData::Tuple(..) | VariantData::Struct(..) => false,
279 VariantData::Unit(..) => true,
281 .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
282 .collect::<Vec<_>>();
284 if !discriminant_spans.is_empty() && has_fields {
285 let mut err = feature_err(
286 &self.sess.parse_sess,
287 sym::arbitrary_enum_discriminant,
288 discriminant_spans.clone(),
289 "custom discriminant values are not allowed in enums with tuple or struct variants",
291 for sp in discriminant_spans {
292 err.span_label(sp, "disallowed custom discriminant");
294 for variant in variants.iter() {
295 match &variant.data {
296 VariantData::Struct(..) => {
297 err.span_label(variant.span, "struct variant defined here");
299 VariantData::Tuple(..) => {
300 err.span_label(variant.span, "tuple variant defined here");
302 VariantData::Unit(..) => {}
309 fn check_gat(&self, generics: &ast::Generics, span: Span) {
310 if !generics.params.is_empty() {
313 generic_associated_types,
315 "generic associated types are unstable"
318 if !generics.where_clause.predicates.is_empty() {
321 generic_associated_types,
323 "where clauses on associated types are unstable"
328 /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
329 fn check_impl_trait(&self, ty: &ast::Ty) {
330 struct ImplTraitVisitor<'a> {
331 vis: &'a PostExpansionVisitor<'a>,
333 impl Visitor<'_> for ImplTraitVisitor<'_> {
334 fn visit_ty(&mut self, ty: &ast::Ty) {
335 if let ast::TyKind::ImplTrait(..) = ty.kind {
338 type_alias_impl_trait,
340 "`impl Trait` in type aliases is unstable"
343 visit::walk_ty(self, ty);
346 ImplTraitVisitor { vis: self }.visit_ty(ty);
350 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
351 fn visit_attribute(&mut self, attr: &ast::Attribute) {
352 let attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
353 // Check feature gates for built-in attributes.
354 if let Some(BuiltinAttribute {
355 gate: AttributeGate::Gated(_, name, descr, has_feature),
359 gate_feature_fn!(self, has_feature, attr.span, *name, descr);
361 // Check unstable flavors of the `#[doc]` attribute.
362 if attr.has_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.has_name(sym::$name) {
366 let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
367 gate_feature_post!(self, $feature, attr.span, msg);
373 cfg_hide => doc_cfg_hide
375 notable_trait => doc_notable_trait
378 if nested_meta.has_name(sym::keyword) {
379 let msg = "`#[doc(keyword)]` is meant for internal use only";
380 gate_feature_post!(self, rustdoc_internals, attr.span, msg);
385 // Check for unstable modifiers on `#[link(..)]` attribute
386 if attr.has_name(sym::link) {
387 for nested_meta in attr.meta_item_list().unwrap_or_default() {
388 if nested_meta.has_name(sym::modifiers) {
391 native_link_modifiers,
393 "native link modifiers are experimental"
396 if let Some(modifiers) = nested_meta.value_str() {
397 for modifier in modifiers.as_str().split(',') {
398 if let Some(modifier) = modifier.strip_prefix(&['+', '-']) {
399 macro_rules! gate_modifier { ($($name:literal => $feature:ident)*) => {
400 $(if modifier == $name {
401 let msg = concat!("`#[link(modifiers=\"", $name, "\")]` is unstable");
405 nested_meta.name_value_literal_span().unwrap(),
412 "bundle" => native_link_modifiers_bundle
413 "verbatim" => native_link_modifiers_verbatim
414 "whole-archive" => native_link_modifiers_whole_archive
415 "as-needed" => native_link_modifiers_as_needed
424 // Emit errors for non-staged-api crates.
425 if !self.features.staged_api {
426 if attr.has_name(sym::rustc_deprecated)
427 || attr.has_name(sym::unstable)
428 || attr.has_name(sym::stable)
429 || attr.has_name(sym::rustc_const_unstable)
430 || attr.has_name(sym::rustc_const_stable)
436 "stability attributes may not be used outside of the standard library",
441 if attr.has_name(sym::deprecated) {
443 .struct_span_err(attr.span, "`#[deprecated]` cannot be used in staged API")
444 .span_label(attr.span, "use `#[rustc_deprecated]` instead")
450 fn visit_item(&mut self, i: &'a ast::Item) {
452 ast::ItemKind::ForeignMod(ref foreign_module) => {
453 if let Some(abi) = foreign_module.abi {
458 ast::ItemKind::Fn(..) => {
459 if self.sess.contains_name(&i.attrs, sym::start) {
464 "`#[start]` functions are experimental \
465 and their signature may change \
471 ast::ItemKind::Struct(..) => {
472 for attr in self.sess.filter_by_name(&i.attrs, sym::repr) {
473 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
474 if item.has_name(sym::simd) {
479 "SIMD types are experimental and possibly buggy"
486 ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => {
487 for variant in variants {
488 match (&variant.data, &variant.disr_expr) {
489 (ast::VariantData::Unit(..), _) => {}
490 (_, Some(disr_expr)) => gate_feature_post!(
492 arbitrary_enum_discriminant,
493 disr_expr.value.span,
494 "discriminants on non-unit variants are experimental"
500 let has_feature = self.features.arbitrary_enum_discriminant;
501 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
502 self.maybe_report_invalid_custom_discriminants(&variants);
506 ast::ItemKind::Impl(box ast::Impl { polarity, defaultness, ref of_trait, .. }) => {
507 if let ast::ImplPolarity::Negative(span) = polarity {
511 span.to(of_trait.as_ref().map_or(span, |t| t.path.span)),
512 "negative trait bounds are not yet fully implemented; \
513 use marker types for now"
517 if let ast::Defaultness::Default(_) = defaultness {
518 gate_feature_post!(&self, specialization, i.span, "specialization is unstable");
522 ast::ItemKind::Trait(box ast::Trait { is_auto: ast::IsAuto::Yes, .. }) => {
527 "auto traits are experimental and possibly buggy"
531 ast::ItemKind::TraitAlias(..) => {
532 gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental");
535 ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => {
536 let msg = "`macro` is experimental";
537 gate_feature_post!(&self, decl_macro, i.span, msg);
540 ast::ItemKind::TyAlias(box ast::TyAlias { ty: Some(ref ty), .. }) => {
541 self.check_impl_trait(&ty)
547 visit::walk_item(self, i);
550 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
552 ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
553 let link_name = self.sess.first_attr_value_str_by_name(&i.attrs, sym::link_name);
555 link_name.map_or(false, |val| val.as_str().starts_with("llvm."));
559 link_llvm_intrinsics,
561 "linking to LLVM intrinsics is experimental"
565 ast::ForeignItemKind::TyAlias(..) => {
566 gate_feature_post!(&self, extern_types, i.span, "extern types are experimental");
568 ast::ForeignItemKind::MacCall(..) => {}
571 visit::walk_foreign_item(self, i)
574 fn visit_ty(&mut self, ty: &'a ast::Ty) {
576 ast::TyKind::BareFn(ref bare_fn_ty) => {
577 self.check_extern(bare_fn_ty.ext);
579 ast::TyKind::Never => {
580 gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental");
584 visit::walk_ty(self, ty)
587 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
588 if let ast::FnRetTy::Ty(ref output_ty) = *ret_ty {
589 if let ast::TyKind::Never = output_ty.kind {
592 self.visit_ty(output_ty)
597 fn visit_expr(&mut self, e: &'a ast::Expr) {
599 ast::ExprKind::Box(_) => {
604 "box expression syntax is experimental; you can call `Box::new` instead"
607 ast::ExprKind::Type(..) => {
608 // To avoid noise about type ascription in common syntax errors, only emit if it
609 // is the *only* error.
610 if self.sess.parse_sess.span_diagnostic.err_count() == 0 {
615 "type ascription is experimental"
619 ast::ExprKind::TryBlock(_) => {
620 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
622 ast::ExprKind::Block(_, Some(label)) => {
627 "labels on blocks are unstable"
632 visit::walk_expr(self, e)
635 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
636 match &pattern.kind {
637 PatKind::Slice(pats) => {
639 let inner_pat = match &pat.kind {
640 PatKind::Ident(.., Some(pat)) => pat,
643 if let PatKind::Range(Some(_), None, Spanned { .. }) = inner_pat.kind {
646 half_open_range_patterns,
648 "`X..` patterns in slices are experimental"
653 PatKind::Box(..) => {
658 "box pattern syntax is experimental"
661 PatKind::Range(_, Some(_), Spanned { node: RangeEnd::Excluded, .. }) => {
664 exclusive_range_pattern,
666 "exclusive range pattern syntax is experimental"
671 visit::walk_pat(self, pattern)
674 fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
675 if let Some(header) = fn_kind.header() {
676 // Stability of const fn methods are covered in `visit_assoc_item` below.
677 self.check_extern(header.ext);
679 if let (ast::Const::Yes(_), ast::Extern::Implicit)
680 | (ast::Const::Yes(_), ast::Extern::Explicit(_)) = (header.constness, header.ext)
686 "`const extern fn` definitions are unstable"
691 if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
692 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
695 visit::walk_fn(self, fn_kind, span)
698 fn visit_assoc_constraint(&mut self, constraint: &'a AssocConstraint) {
699 if let AssocConstraintKind::Bound { .. } = constraint.kind {
702 associated_type_bounds,
704 "associated type bounds are unstable"
707 visit::walk_assoc_constraint(self, constraint)
710 fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
711 let is_fn = match i.kind {
712 ast::AssocItemKind::Fn(_) => true,
713 ast::AssocItemKind::TyAlias(box ast::TyAlias { ref generics, ref ty, .. }) => {
714 if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
717 associated_type_defaults,
719 "associated type defaults are unstable"
722 if let Some(ty) = ty {
723 self.check_impl_trait(ty);
725 self.check_gat(generics, i.span);
730 if let ast::Defaultness::Default(_) = i.kind.defaultness() {
731 // Limit `min_specialization` to only specializing functions.
734 |x: &Features| x.specialization || (is_fn && x.min_specialization),
737 "specialization is unstable"
740 visit::walk_assoc_item(self, i, ctxt)
743 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
744 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.kind {
747 crate_visibility_modifier,
749 "`crate` visibility modifier is experimental"
752 visit::walk_vis(self, vis)
756 pub fn check_crate(krate: &ast::Crate, sess: &Session) {
757 maybe_stage_features(sess, krate);
758 check_incompatible_features(sess);
759 let mut visitor = PostExpansionVisitor { sess, features: &sess.features_untracked() };
761 let spans = sess.parse_sess.gated_spans.spans.borrow();
762 macro_rules! gate_all {
763 ($gate:ident, $msg:literal, $help:literal) => {
764 if let Some(spans) = spans.get(&sym::$gate) {
766 gate_feature_post!(&visitor, $gate, *span, $msg, $help);
770 ($gate:ident, $msg:literal) => {
771 if let Some(spans) = spans.get(&sym::$gate) {
773 gate_feature_post!(&visitor, $gate, *span, $msg);
780 "`if let` guards are experimental",
781 "you can write `if matches!(<expr>, <pattern>)` instead of `if let <pattern> = <expr>`"
783 gate_all!(let_chains, "`let` expressions in this position are unstable");
786 "async closures are unstable",
787 "to use an async block, remove the `||`: `async {`"
789 gate_all!(more_qualified_paths, "usage of qualified paths in this context is experimental");
790 gate_all!(generators, "yield syntax is experimental");
791 gate_all!(raw_ref_op, "raw address of syntax is experimental");
792 gate_all!(const_trait_impl, "const trait impls are experimental");
793 gate_all!(half_open_range_patterns, "half-open range patterns are unstable");
794 gate_all!(inline_const, "inline-const is experimental");
795 gate_all!(inline_const_pat, "inline-const in pattern position is experimental");
796 gate_all!(associated_const_equality, "associated const equality is incomplete");
798 // All uses of `gate_all!` below this point were added in #65742,
799 // and subsequently disabled (with the non-early gating readded).
800 macro_rules! gate_all {
801 ($gate:ident, $msg:literal) => {
802 // FIXME(eddyb) do something more useful than always
803 // disabling these uses of early feature-gatings.
805 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
806 gate_feature_post!(&visitor, $gate, *span, $msg);
812 gate_all!(trait_alias, "trait aliases are experimental");
813 gate_all!(associated_type_bounds, "associated type bounds are unstable");
814 gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
815 gate_all!(decl_macro, "`macro` is experimental");
816 gate_all!(box_patterns, "box pattern syntax is experimental");
817 gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
818 gate_all!(try_blocks, "`try` blocks are unstable");
819 gate_all!(label_break_value, "labels on blocks are unstable");
820 gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
821 // To avoid noise about type ascription in common syntax errors,
822 // only emit if it is the *only* error. (Also check it last.)
823 if sess.parse_sess.span_diagnostic.err_count() == 0 {
824 gate_all!(type_ascription, "type ascription is experimental");
827 visit::walk_crate(&mut visitor, krate);
830 fn maybe_stage_features(sess: &Session, krate: &ast::Crate) {
831 // checks if `#![feature]` has been used to enable any lang feature
832 // does not check the same for lib features unless there's at least one
833 // declared lang feature
834 use rustc_errors::Applicability;
836 if !sess.opts.unstable_features.is_nightly_build() {
837 let lang_features = &sess.features_untracked().declared_lang_features;
838 if lang_features.len() == 0 {
841 for attr in krate.attrs.iter().filter(|attr| attr.has_name(sym::feature)) {
842 let mut err = struct_span_err!(
843 sess.parse_sess.span_diagnostic,
846 "`#![feature]` may not be used on the {} release channel",
847 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")
849 let mut all_stable = true;
851 attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident())
853 let name = ident.name;
854 let stable_since = lang_features
856 .flat_map(|&(feature, _, since)| if feature == name { since } else { None })
858 if let Some(since) = stable_since {
860 "the feature `{}` has been stable since {} and no longer requires \
861 an attribute to enable",
871 "remove the attribute",
873 Applicability::MachineApplicable,
881 fn check_incompatible_features(sess: &Session) {
882 let features = sess.features_untracked();
884 let declared_features = features
885 .declared_lang_features
888 .map(|(name, span, _)| (name, span))
889 .chain(features.declared_lib_features.iter().copied());
891 for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES
893 .filter(|&&(f1, f2)| features.enabled(f1) && features.enabled(f2))
895 if let Some((f1_name, f1_span)) = declared_features.clone().find(|(name, _)| name == f1) {
896 if let Some((f2_name, f2_span)) = declared_features.clone().find(|(name, _)| name == f2)
898 let spans = vec![f1_span, f2_span];
899 sess.struct_span_err(
902 "features `{}` and `{}` are incompatible, using them at the same time \
907 .help("remove one of these features")