1 use rustc_error_codes::*;
2 use rustc_errors::{struct_span_err, Handler};
3 use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP};
4 use rustc_feature::{Features, GateIssue, UnstableFeatures};
5 use rustc_span::source_map::Spanned;
6 use rustc_span::symbol::sym;
8 use syntax::ast::{self, AssocTyConstraint, AssocTyConstraintKind, NodeId};
9 use syntax::ast::{GenericParam, GenericParamKind, PatKind, RangeEnd, VariantData};
11 use syntax::sess::{feature_err, feature_err_issue, ParseSess};
12 use syntax::visit::{self, FnKind, Visitor};
16 macro_rules! gate_feature_fn {
17 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{
18 let (cx, has_feature, span, name, explain) = (&*$cx, $has_feature, $span, $name, $explain);
19 let has_feature: bool = has_feature(&$cx.features);
20 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
21 if !has_feature && !span.allows_unstable($name) {
22 feature_err_issue(cx.parse_sess, name, span, GateIssue::Language, explain).emit();
27 macro_rules! gate_feature_post {
28 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
29 gate_feature_fn!($cx, |x: &Features| x.$feature, $span, sym::$feature, $explain)
33 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
34 PostExpansionVisitor { parse_sess, features }.visit_attribute(attr)
37 struct PostExpansionVisitor<'a> {
38 parse_sess: &'a ParseSess,
39 features: &'a Features,
42 impl<'a> PostExpansionVisitor<'a> {
43 fn check_abi(&self, abi: ast::StrLit) {
44 let ast::StrLit { symbol_unescaped, span, .. } = abi;
46 match &*symbol_unescaped.as_str() {
48 "Rust" | "C" | "cdecl" | "stdcall" | "fastcall" | "aapcs" | "win64" | "sysv64"
51 gate_feature_post!(&self, intrinsics, span, "intrinsics are subject to change");
53 "platform-intrinsic" => {
58 "platform intrinsics are experimental and possibly buggy"
66 "vectorcall is experimental and subject to change"
74 "thiscall is experimental and subject to change"
82 "rust-call ABI is subject to change"
90 "PTX ABIs are experimental and subject to change"
98 "unadjusted ABI is an implementation detail and perma-unstable"
101 "msp430-interrupt" => {
104 abi_msp430_interrupt,
106 "msp430-interrupt ABI is experimental and subject to change"
114 "x86-interrupt ABI is experimental and subject to change"
122 "amdgpu-kernel ABI is experimental and subject to change"
130 "efiapi ABI is experimental and subject to change"
136 .delay_span_bug(span, &format!("unrecognized ABI not caught in lowering: {}", abi)),
140 fn check_extern(&self, ext: ast::Extern) {
141 if let ast::Extern::Explicit(abi) = ext {
146 fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
147 let has_fields = variants.iter().any(|variant| match variant.data {
148 VariantData::Tuple(..) | VariantData::Struct(..) => true,
149 VariantData::Unit(..) => false,
152 let discriminant_spans = variants
154 .filter(|variant| match variant.data {
155 VariantData::Tuple(..) | VariantData::Struct(..) => false,
156 VariantData::Unit(..) => true,
158 .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
159 .collect::<Vec<_>>();
161 if !discriminant_spans.is_empty() && has_fields {
162 let mut err = feature_err(
164 sym::arbitrary_enum_discriminant,
165 discriminant_spans.clone(),
166 "custom discriminant values are not allowed in enums with tuple or struct variants",
168 for sp in discriminant_spans {
169 err.span_label(sp, "disallowed custom discriminant");
171 for variant in variants.iter() {
172 match &variant.data {
173 VariantData::Struct(..) => {
174 err.span_label(variant.span, "struct variant defined here");
176 VariantData::Tuple(..) => {
177 err.span_label(variant.span, "tuple variant defined here");
179 VariantData::Unit(..) => {}
186 fn check_gat(&self, generics: &ast::Generics, span: Span) {
187 if !generics.params.is_empty() {
190 generic_associated_types,
192 "generic associated types are unstable"
195 if !generics.where_clause.predicates.is_empty() {
198 generic_associated_types,
200 "where clauses on associated types are unstable"
205 /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
206 fn check_impl_trait(&self, ty: &ast::Ty) {
207 struct ImplTraitVisitor<'a> {
208 vis: &'a PostExpansionVisitor<'a>,
210 impl Visitor<'_> for ImplTraitVisitor<'_> {
211 fn visit_ty(&mut self, ty: &ast::Ty) {
212 if let ast::TyKind::ImplTrait(..) = ty.kind {
215 type_alias_impl_trait,
217 "`impl Trait` in type aliases is unstable"
220 visit::walk_ty(self, ty);
223 ImplTraitVisitor { vis: self }.visit_ty(ty);
227 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
228 fn visit_attribute(&mut self, attr: &ast::Attribute) {
230 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
231 // Check feature gates for built-in attributes.
232 if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
233 gate_feature_fn!(self, has_feature, attr.span, name, descr);
235 // Check unstable flavors of the `#[doc]` attribute.
236 if attr.check_name(sym::doc) {
237 for nested_meta in attr.meta_item_list().unwrap_or_default() {
238 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
239 $(if nested_meta.check_name(sym::$name) {
240 let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
241 gate_feature_post!(self, $feature, attr.span, msg);
246 include => external_doc
249 spotlight => doc_spotlight
251 keyword => doc_keyword
257 fn visit_name(&mut self, sp: Span, name: ast::Name) {
258 if !name.as_str().is_ascii() {
262 self.parse_sess.source_map().def_span(sp),
263 "non-ascii idents are not fully supported"
268 fn visit_item(&mut self, i: &'a ast::Item) {
270 ast::ItemKind::ForeignMod(ref foreign_module) => {
271 if let Some(abi) = foreign_module.abi {
276 ast::ItemKind::Fn(..) => {
277 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
282 "compiler plugins are experimental and possibly buggy"
285 if attr::contains_name(&i.attrs[..], sym::start) {
290 "`#[start]` functions are experimental \
291 and their signature may change \
295 if attr::contains_name(&i.attrs[..], sym::main) {
300 "declaration of a non-standard `#[main]` \
301 function may change over time, for now \
302 a top-level `fn main()` is required"
307 ast::ItemKind::Struct(..) => {
308 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
309 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
310 if item.check_name(sym::simd) {
315 "SIMD types are experimental and possibly buggy"
322 ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => {
323 for variant in variants {
324 match (&variant.data, &variant.disr_expr) {
325 (ast::VariantData::Unit(..), _) => {}
326 (_, Some(disr_expr)) => gate_feature_post!(
328 arbitrary_enum_discriminant,
329 disr_expr.value.span,
330 "discriminants on non-unit variants are experimental"
336 let has_feature = self.features.arbitrary_enum_discriminant;
337 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
338 self.maybe_report_invalid_custom_discriminants(&variants);
342 ast::ItemKind::Impl(_, polarity, defaultness, ..) => {
343 if polarity == ast::ImplPolarity::Negative {
346 optin_builtin_traits,
348 "negative trait bounds are not yet fully implemented; \
349 use marker types for now"
353 if let ast::Defaultness::Default = defaultness {
354 gate_feature_post!(&self, specialization, i.span, "specialization is unstable");
358 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
361 optin_builtin_traits,
363 "auto traits are experimental and possibly buggy"
367 ast::ItemKind::TraitAlias(..) => {
368 gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental");
371 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
372 let msg = "`macro` is experimental";
373 gate_feature_post!(&self, decl_macro, i.span, msg);
376 ast::ItemKind::TyAlias(ref ty, ..) => self.check_impl_trait(&ty),
381 visit::walk_item(self, i);
384 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
386 ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
387 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
388 let links_to_llvm = match link_name {
389 Some(val) => val.as_str().starts_with("llvm."),
395 link_llvm_intrinsics,
397 "linking to LLVM intrinsics is experimental"
401 ast::ForeignItemKind::Ty => {
402 gate_feature_post!(&self, extern_types, i.span, "extern types are experimental");
404 ast::ForeignItemKind::Macro(..) => {}
407 visit::walk_foreign_item(self, i)
410 fn visit_ty(&mut self, ty: &'a ast::Ty) {
412 ast::TyKind::BareFn(ref bare_fn_ty) => {
413 self.check_extern(bare_fn_ty.ext);
415 ast::TyKind::Never => {
416 gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental");
420 visit::walk_ty(self, ty)
423 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
424 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
425 if let ast::TyKind::Never = output_ty.kind {
428 self.visit_ty(output_ty)
433 fn visit_expr(&mut self, e: &'a ast::Expr) {
435 ast::ExprKind::Box(_) => {
440 "box expression syntax is experimental; you can call `Box::new` instead"
443 ast::ExprKind::Type(..) => {
444 // To avoid noise about type ascription in common syntax errors, only emit if it
445 // is the *only* error.
446 if self.parse_sess.span_diagnostic.err_count() == 0 {
451 "type ascription is experimental"
455 ast::ExprKind::TryBlock(_) => {
456 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
458 ast::ExprKind::Block(_, opt_label) => {
459 if let Some(label) = opt_label {
464 "labels on blocks are unstable"
470 visit::walk_expr(self, e)
473 fn visit_arm(&mut self, arm: &'a ast::Arm) {
474 visit::walk_arm(self, arm)
477 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
478 match &pattern.kind {
479 PatKind::Slice(pats) => {
482 let inner_pat = match &pat.kind {
483 PatKind::Ident(.., Some(pat)) => pat,
486 if inner_pat.is_rest() {
491 "subslice patterns are unstable"
496 PatKind::Box(..) => {
501 "box pattern syntax is experimental"
504 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
507 exclusive_range_pattern,
509 "exclusive range pattern syntax is experimental"
514 visit::walk_pat(self, pattern)
520 fn_decl: &'a ast::FnDecl,
524 if let Some(header) = fn_kind.header() {
525 // Stability of const fn methods are covered in
526 // `visit_trait_item` and `visit_impl_item` below; this is
527 // because default methods don't pass through this point.
528 self.check_extern(header.ext);
531 if fn_decl.c_variadic() {
532 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
535 visit::walk_fn(self, fn_kind, fn_decl, span)
538 fn visit_generic_param(&mut self, param: &'a GenericParam) {
540 GenericParamKind::Const { .. } => gate_feature_post!(
544 "const generics are unstable"
548 visit::walk_generic_param(self, param)
551 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
552 match constraint.kind {
553 AssocTyConstraintKind::Bound { .. } => gate_feature_post!(
555 associated_type_bounds,
557 "associated type bounds are unstable"
561 visit::walk_assoc_ty_constraint(self, constraint)
564 fn visit_trait_item(&mut self, ti: &'a ast::AssocItem) {
566 ast::AssocItemKind::Fn(ref sig, ref block) => {
568 self.check_extern(sig.header.ext);
570 if sig.header.constness.node == ast::Constness::Const {
571 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
574 ast::AssocItemKind::TyAlias(_, ref default) => {
575 if let Some(_) = default {
578 associated_type_defaults,
580 "associated type defaults are unstable"
586 visit::walk_trait_item(self, ti)
589 fn visit_assoc_item(&mut self, ii: &'a ast::AssocItem) {
590 if ii.defaultness == ast::Defaultness::Default {
591 gate_feature_post!(&self, specialization, ii.span, "specialization is unstable");
595 ast::AssocItemKind::Fn(ref sig, _) => {
596 if sig.decl.c_variadic() {
601 "C-variadic functions are unstable"
605 ast::AssocItemKind::TyAlias(_, ref ty) => {
606 if let Some(ty) = ty {
607 self.check_impl_trait(ty);
609 self.check_gat(&ii.generics, ii.span);
613 visit::walk_assoc_item(self, ii)
616 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
617 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
620 crate_visibility_modifier,
622 "`crate` visibility modifier is experimental"
625 visit::walk_vis(self, vis)
631 parse_sess: &ParseSess,
633 unstable: UnstableFeatures,
635 maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
636 let mut visitor = PostExpansionVisitor { parse_sess, features };
638 let spans = parse_sess.gated_spans.spans.borrow();
639 macro_rules! gate_all {
640 ($gate:ident, $msg:literal) => {
641 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
642 gate_feature_post!(&visitor, $gate, *span, $msg);
646 gate_all!(let_chains, "`let` expressions in this position are experimental");
647 gate_all!(async_closure, "async closures are unstable");
648 gate_all!(generators, "yield syntax is experimental");
649 gate_all!(or_patterns, "or-patterns syntax is experimental");
650 gate_all!(const_extern_fn, "`const extern fn` definitions are unstable");
651 gate_all!(raw_ref_op, "raw address of syntax is experimental");
652 gate_all!(const_trait_bound_opt_out, "`?const` on trait bounds is experimental");
653 gate_all!(const_trait_impl, "const trait impls are experimental");
654 gate_all!(half_open_range_patterns, "half-open range patterns are unstable");
656 // All uses of `gate_all!` below this point were added in #65742,
657 // and subsequently disabled (with the non-early gating readded).
658 macro_rules! gate_all {
659 ($gate:ident, $msg:literal) => {
660 // FIXME(eddyb) do something more useful than always
661 // disabling these uses of early feature-gatings.
663 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
664 gate_feature_post!(&visitor, $gate, *span, $msg);
670 gate_all!(trait_alias, "trait aliases are experimental");
671 gate_all!(associated_type_bounds, "associated type bounds are unstable");
672 gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
673 gate_all!(const_generics, "const generics are unstable");
674 gate_all!(decl_macro, "`macro` is experimental");
675 gate_all!(box_patterns, "box pattern syntax is experimental");
676 gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
677 gate_all!(try_blocks, "`try` blocks are unstable");
678 gate_all!(label_break_value, "labels on blocks are unstable");
679 gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
680 // To avoid noise about type ascription in common syntax errors,
681 // only emit if it is the *only* error. (Also check it last.)
682 if parse_sess.span_diagnostic.err_count() == 0 {
683 gate_all!(type_ascription, "type ascription is experimental");
686 visit::walk_crate(&mut visitor, krate);
689 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
690 if !unstable.is_nightly_build() {
691 for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
696 "`#![feature]` may not be used on the {} release channel",
697 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")