1 use rustc_ast::ast::{self, AssocTyConstraint, AssocTyConstraintKind, NodeId};
2 use rustc_ast::ast::{GenericParam, GenericParamKind, PatKind, RangeEnd, VariantData};
4 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
5 use rustc_errors::{struct_span_err, Handler};
6 use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP};
7 use rustc_feature::{Features, GateIssue, UnstableFeatures};
8 use rustc_session::parse::{feature_err, feature_err_issue, ParseSess};
9 use rustc_span::source_map::Spanned;
10 use rustc_span::symbol::{sym, Symbol};
15 macro_rules! gate_feature_fn {
16 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{
17 let (cx, has_feature, span, name, explain) = (&*$cx, $has_feature, $span, $name, $explain);
18 let has_feature: bool = has_feature(&$cx.features);
19 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
20 if !has_feature && !span.allows_unstable($name) {
21 feature_err_issue(cx.parse_sess, name, span, GateIssue::Language, explain).emit();
26 macro_rules! gate_feature_post {
27 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
28 gate_feature_fn!($cx, |x: &Features| x.$feature, $span, sym::$feature, $explain)
32 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
33 PostExpansionVisitor { parse_sess, features }.visit_attribute(attr)
36 struct PostExpansionVisitor<'a> {
37 parse_sess: &'a ParseSess,
38 features: &'a Features,
41 impl<'a> PostExpansionVisitor<'a> {
42 fn check_abi(&self, abi: ast::StrLit) {
43 let ast::StrLit { symbol_unescaped, span, .. } = abi;
45 match &*symbol_unescaped.as_str() {
47 "Rust" | "C" | "cdecl" | "stdcall" | "fastcall" | "aapcs" | "win64" | "sysv64"
50 gate_feature_post!(&self, intrinsics, span, "intrinsics are subject to change");
52 "platform-intrinsic" => {
57 "platform intrinsics are experimental and possibly buggy"
65 "vectorcall is experimental and subject to change"
73 "thiscall is experimental and subject to change"
81 "rust-call ABI is subject to change"
89 "PTX ABIs are experimental and subject to change"
97 "unadjusted ABI is an implementation detail and perma-unstable"
100 "msp430-interrupt" => {
103 abi_msp430_interrupt,
105 "msp430-interrupt ABI is experimental and subject to change"
113 "x86-interrupt ABI is experimental and subject to change"
121 "amdgpu-kernel ABI is experimental and subject to change"
124 "avr-interrupt" | "avr-non-blocking-interrupt" => {
129 "avr-interrupt and avr-non-blocking-interrupt ABIs are experimental and subject to change"
137 "efiapi ABI is experimental and subject to change"
143 .delay_span_bug(span, &format!("unrecognized ABI not caught in lowering: {}", abi)),
147 fn check_extern(&self, ext: ast::Extern) {
148 if let ast::Extern::Explicit(abi) = ext {
153 fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
154 let has_fields = variants.iter().any(|variant| match variant.data {
155 VariantData::Tuple(..) | VariantData::Struct(..) => true,
156 VariantData::Unit(..) => false,
159 let discriminant_spans = variants
161 .filter(|variant| match variant.data {
162 VariantData::Tuple(..) | VariantData::Struct(..) => false,
163 VariantData::Unit(..) => true,
165 .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
166 .collect::<Vec<_>>();
168 if !discriminant_spans.is_empty() && has_fields {
169 let mut err = feature_err(
171 sym::arbitrary_enum_discriminant,
172 discriminant_spans.clone(),
173 "custom discriminant values are not allowed in enums with tuple or struct variants",
175 for sp in discriminant_spans {
176 err.span_label(sp, "disallowed custom discriminant");
178 for variant in variants.iter() {
179 match &variant.data {
180 VariantData::Struct(..) => {
181 err.span_label(variant.span, "struct variant defined here");
183 VariantData::Tuple(..) => {
184 err.span_label(variant.span, "tuple variant defined here");
186 VariantData::Unit(..) => {}
193 fn check_gat(&self, generics: &ast::Generics, span: Span) {
194 if !generics.params.is_empty() {
197 generic_associated_types,
199 "generic associated types are unstable"
202 if !generics.where_clause.predicates.is_empty() {
205 generic_associated_types,
207 "where clauses on associated types are unstable"
212 /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
213 fn check_impl_trait(&self, ty: &ast::Ty) {
214 struct ImplTraitVisitor<'a> {
215 vis: &'a PostExpansionVisitor<'a>,
217 impl Visitor<'_> for ImplTraitVisitor<'_> {
218 fn visit_ty(&mut self, ty: &ast::Ty) {
219 if let ast::TyKind::ImplTrait(..) = ty.kind {
222 type_alias_impl_trait,
224 "`impl Trait` in type aliases is unstable"
227 visit::walk_ty(self, ty);
230 ImplTraitVisitor { vis: self }.visit_ty(ty);
234 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
235 fn visit_attribute(&mut self, attr: &ast::Attribute) {
237 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
238 // Check feature gates for built-in attributes.
239 if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
240 gate_feature_fn!(self, has_feature, attr.span, name, descr);
242 // Check unstable flavors of the `#[doc]` attribute.
243 if attr.check_name(sym::doc) {
244 for nested_meta in attr.meta_item_list().unwrap_or_default() {
245 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
246 $(if nested_meta.has_name(sym::$name) {
247 let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
248 gate_feature_post!(self, $feature, attr.span, msg);
253 include => external_doc
256 spotlight => doc_spotlight
258 keyword => doc_keyword
264 fn visit_name(&mut self, sp: Span, name: Symbol) {
265 if !name.as_str().is_ascii() {
269 self.parse_sess.source_map().guess_head_span(sp),
270 "non-ascii idents are not fully supported"
275 fn visit_item(&mut self, i: &'a ast::Item) {
277 ast::ItemKind::ForeignMod(ref foreign_module) => {
278 if let Some(abi) = foreign_module.abi {
283 ast::ItemKind::Fn(..) => {
284 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
289 "compiler plugins are experimental and possibly buggy"
292 if attr::contains_name(&i.attrs[..], sym::start) {
297 "`#[start]` functions are experimental \
298 and their signature may change \
302 if attr::contains_name(&i.attrs[..], sym::main) {
307 "declaration of a non-standard `#[main]` \
308 function may change over time, for now \
309 a top-level `fn main()` is required"
314 ast::ItemKind::Struct(..) => {
315 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
316 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
317 if item.has_name(sym::simd) {
322 "SIMD types are experimental and possibly buggy"
329 ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => {
330 for variant in variants {
331 match (&variant.data, &variant.disr_expr) {
332 (ast::VariantData::Unit(..), _) => {}
333 (_, Some(disr_expr)) => gate_feature_post!(
335 arbitrary_enum_discriminant,
336 disr_expr.value.span,
337 "discriminants on non-unit variants are experimental"
343 let has_feature = self.features.arbitrary_enum_discriminant;
344 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
345 self.maybe_report_invalid_custom_discriminants(&variants);
349 ast::ItemKind::Impl { polarity, defaultness, ref of_trait, .. } => {
350 if let ast::ImplPolarity::Negative(span) = polarity {
354 span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(span)),
355 "negative trait bounds are not yet fully implemented; \
356 use marker types for now"
360 if let ast::Defaultness::Default(_) = defaultness {
361 gate_feature_post!(&self, specialization, i.span, "specialization is unstable");
365 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
368 optin_builtin_traits,
370 "auto traits are experimental and possibly buggy"
374 ast::ItemKind::TraitAlias(..) => {
375 gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental");
378 ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => {
379 let msg = "`macro` is experimental";
380 gate_feature_post!(&self, decl_macro, i.span, msg);
383 ast::ItemKind::TyAlias(_, _, _, Some(ref ty)) => self.check_impl_trait(&ty),
388 visit::walk_item(self, i);
391 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
393 ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
394 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
395 let links_to_llvm = match link_name {
396 Some(val) => val.as_str().starts_with("llvm."),
402 link_llvm_intrinsics,
404 "linking to LLVM intrinsics is experimental"
408 ast::ForeignItemKind::TyAlias(..) => {
409 gate_feature_post!(&self, extern_types, i.span, "extern types are experimental");
411 ast::ForeignItemKind::MacCall(..) => {}
414 visit::walk_foreign_item(self, i)
417 fn visit_ty(&mut self, ty: &'a ast::Ty) {
419 ast::TyKind::BareFn(ref bare_fn_ty) => {
420 self.check_extern(bare_fn_ty.ext);
422 ast::TyKind::Never => {
423 gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental");
427 visit::walk_ty(self, ty)
430 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
431 if let ast::FnRetTy::Ty(ref output_ty) = *ret_ty {
432 if let ast::TyKind::Never = output_ty.kind {
435 self.visit_ty(output_ty)
440 fn visit_expr(&mut self, e: &'a ast::Expr) {
442 ast::ExprKind::Box(_) => {
447 "box expression syntax is experimental; you can call `Box::new` instead"
450 ast::ExprKind::Type(..) => {
451 // To avoid noise about type ascription in common syntax errors, only emit if it
452 // is the *only* error.
453 if self.parse_sess.span_diagnostic.err_count() == 0 {
458 "type ascription is experimental"
462 ast::ExprKind::TryBlock(_) => {
463 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
465 ast::ExprKind::Block(_, opt_label) => {
466 if let Some(label) = opt_label {
471 "labels on blocks are unstable"
477 visit::walk_expr(self, e)
480 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
481 match &pattern.kind {
482 PatKind::Box(..) => {
487 "box pattern syntax is experimental"
490 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
493 exclusive_range_pattern,
495 "exclusive range pattern syntax is experimental"
500 visit::walk_pat(self, pattern)
503 fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
504 if let Some(header) = fn_kind.header() {
505 // Stability of const fn methods are covered in `visit_assoc_item` below.
506 self.check_extern(header.ext);
508 if let (ast::Const::Yes(_), ast::Extern::Implicit)
509 | (ast::Const::Yes(_), ast::Extern::Explicit(_)) = (header.constness, header.ext)
515 "`const extern fn` definitions are unstable"
520 if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
521 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
524 visit::walk_fn(self, fn_kind, span)
527 fn visit_generic_param(&mut self, param: &'a GenericParam) {
528 if let GenericParamKind::Const { .. } = param.kind {
533 "const generics are unstable"
536 visit::walk_generic_param(self, param)
539 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
540 if let AssocTyConstraintKind::Bound { .. } = constraint.kind {
543 associated_type_bounds,
545 "associated type bounds are unstable"
548 visit::walk_assoc_ty_constraint(self, constraint)
551 fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
552 let is_fn = match i.kind {
553 ast::AssocItemKind::Fn(_, ref sig, _, _) => {
554 if let (ast::Const::Yes(_), AssocCtxt::Trait) = (sig.header.constness, ctxt) {
555 gate_feature_post!(&self, const_fn, i.span, "const fn is unstable");
559 ast::AssocItemKind::TyAlias(_, ref generics, _, ref ty) => {
560 if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
563 associated_type_defaults,
565 "associated type defaults are unstable"
568 if let Some(ty) = ty {
569 self.check_impl_trait(ty);
571 self.check_gat(generics, i.span);
576 if let ast::Defaultness::Default(_) = i.kind.defaultness() {
577 // Limit `min_specialization` to only specializing functions.
580 |x: &Features| x.specialization || (is_fn && x.min_specialization),
583 "specialization is unstable"
586 visit::walk_assoc_item(self, i, ctxt)
589 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
590 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
593 crate_visibility_modifier,
595 "`crate` visibility modifier is experimental"
598 visit::walk_vis(self, vis)
604 parse_sess: &ParseSess,
606 unstable: UnstableFeatures,
608 maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
609 let mut visitor = PostExpansionVisitor { parse_sess, features };
611 let spans = parse_sess.gated_spans.spans.borrow();
612 macro_rules! gate_all {
613 ($gate:ident, $msg:literal) => {
614 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
615 gate_feature_post!(&visitor, $gate, *span, $msg);
619 gate_all!(let_chains, "`let` expressions in this position are experimental");
620 gate_all!(async_closure, "async closures are unstable");
621 gate_all!(generators, "yield syntax is experimental");
622 gate_all!(or_patterns, "or-patterns syntax is experimental");
623 gate_all!(raw_ref_op, "raw address of syntax is experimental");
624 gate_all!(const_trait_bound_opt_out, "`?const` on trait bounds is experimental");
625 gate_all!(const_trait_impl, "const trait impls are experimental");
626 gate_all!(half_open_range_patterns, "half-open range patterns are unstable");
628 // All uses of `gate_all!` below this point were added in #65742,
629 // and subsequently disabled (with the non-early gating readded).
630 macro_rules! gate_all {
631 ($gate:ident, $msg:literal) => {
632 // FIXME(eddyb) do something more useful than always
633 // disabling these uses of early feature-gatings.
635 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
636 gate_feature_post!(&visitor, $gate, *span, $msg);
642 gate_all!(trait_alias, "trait aliases are experimental");
643 gate_all!(associated_type_bounds, "associated type bounds are unstable");
644 gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
645 gate_all!(const_generics, "const generics are unstable");
646 gate_all!(decl_macro, "`macro` is experimental");
647 gate_all!(box_patterns, "box pattern syntax is experimental");
648 gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
649 gate_all!(try_blocks, "`try` blocks are unstable");
650 gate_all!(label_break_value, "labels on blocks are unstable");
651 gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
652 // To avoid noise about type ascription in common syntax errors,
653 // only emit if it is the *only* error. (Also check it last.)
654 if parse_sess.span_diagnostic.err_count() == 0 {
655 gate_all!(type_ascription, "type ascription is experimental");
658 visit::walk_crate(&mut visitor, krate);
661 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
662 if !unstable.is_nightly_build() {
663 for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
668 "`#![feature]` may not be used on the {} release channel",
669 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")