Skip to main content

rustc_ast_passes/
feature_gate.rs

1use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
2use rustc_ast::{self as ast, AttrVec, NodeId, PatKind, attr, token};
3use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute, Features};
4use rustc_session::Session;
5use rustc_session::parse::{feature_err, feature_warn};
6use rustc_span::source_map::Spanned;
7use rustc_span::{Span, Symbol, sym};
8use thin_vec::ThinVec;
9
10use crate::errors;
11
12/// The common case.
13macro_rules! gate {
14    ($visitor:expr, $feature:ident, $span:expr, $explain:expr) => {{
15        if !$visitor.features.$feature() && !$span.allows_unstable(sym::$feature) {
16            feature_err(&$visitor.sess, sym::$feature, $span, $explain).emit();
17        }
18    }};
19    ($visitor:expr, $feature:ident, $span:expr, $explain:expr, $help:expr) => {{
20        if !$visitor.features.$feature() && !$span.allows_unstable(sym::$feature) {
21            feature_err(&$visitor.sess, sym::$feature, $span, $explain).with_help($help).emit();
22        }
23    }};
24}
25
26/// The unusual case, where the `has_feature` condition is non-standard.
27macro_rules! gate_alt {
28    ($visitor:expr, $has_feature:expr, $name:expr, $span:expr, $explain:expr) => {{
29        if !$has_feature && !$span.allows_unstable($name) {
30            feature_err(&$visitor.sess, $name, $span, $explain).emit();
31        }
32    }};
33    ($visitor:expr, $has_feature:expr, $name:expr, $span:expr, $explain:expr, $notes: expr) => {{
34        if !$has_feature && !$span.allows_unstable($name) {
35            let mut diag = feature_err(&$visitor.sess, $name, $span, $explain);
36            for note in $notes {
37                diag.note(*note);
38            }
39            diag.emit();
40        }
41    }};
42}
43
44/// The case involving a multispan.
45macro_rules! gate_multi {
46    ($visitor:expr, $feature:ident, $spans:expr, $explain:expr) => {{
47        if !$visitor.features.$feature() {
48            let spans: Vec<_> =
49                $spans.filter(|span| !span.allows_unstable(sym::$feature)).collect();
50            if !spans.is_empty() {
51                feature_err(&$visitor.sess, sym::$feature, spans, $explain).emit();
52            }
53        }
54    }};
55}
56
57/// The legacy case.
58macro_rules! gate_legacy {
59    ($visitor:expr, $feature:ident, $span:expr, $explain:expr) => {{
60        if !$visitor.features.$feature() && !$span.allows_unstable(sym::$feature) {
61            feature_warn(&$visitor.sess, sym::$feature, $span, $explain);
62        }
63    }};
64}
65
66pub fn check_attribute(attr: &ast::Attribute, sess: &Session, features: &Features) {
67    PostExpansionVisitor { sess, features }.visit_attribute(attr)
68}
69
70struct PostExpansionVisitor<'a> {
71    sess: &'a Session,
72
73    // `sess` contains a `Features`, but this might not be that one.
74    features: &'a Features,
75}
76
77impl<'a> PostExpansionVisitor<'a> {
78    /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
79    fn check_impl_trait(&self, ty: &ast::Ty, in_associated_ty: bool) {
80        struct ImplTraitVisitor<'a> {
81            vis: &'a PostExpansionVisitor<'a>,
82            in_associated_ty: bool,
83        }
84        impl Visitor<'_> for ImplTraitVisitor<'_> {
85            fn visit_ty(&mut self, ty: &ast::Ty) {
86                if let ast::TyKind::ImplTrait(..) = ty.kind {
87                    if self.in_associated_ty {
88                        {
    if !(&self.vis).features.impl_trait_in_assoc_type() &&
            !ty.span.allows_unstable(sym::impl_trait_in_assoc_type) {
        feature_err(&(&self.vis).sess, sym::impl_trait_in_assoc_type, ty.span,
                "`impl Trait` in associated types is unstable").emit();
    }
};gate!(
89                            &self.vis,
90                            impl_trait_in_assoc_type,
91                            ty.span,
92                            "`impl Trait` in associated types is unstable"
93                        );
94                    } else {
95                        {
    if !(&self.vis).features.type_alias_impl_trait() &&
            !ty.span.allows_unstable(sym::type_alias_impl_trait) {
        feature_err(&(&self.vis).sess, sym::type_alias_impl_trait, ty.span,
                "`impl Trait` in type aliases is unstable").emit();
    }
};gate!(
96                            &self.vis,
97                            type_alias_impl_trait,
98                            ty.span,
99                            "`impl Trait` in type aliases is unstable"
100                        );
101                    }
102                }
103                visit::walk_ty(self, ty);
104            }
105
106            fn visit_anon_const(&mut self, _: &ast::AnonConst) -> Self::Result {
107                // We don't walk the anon const because it crosses a conceptual boundary: We're no
108                // longer "inside" the original type.
109                // Brittle: We assume that the callers of `check_impl_trait` will later recurse into
110                // the items found in the AnonConst to look for nested TyAliases.
111            }
112        }
113        ImplTraitVisitor { vis: self, in_associated_ty }.visit_ty(ty);
114    }
115
116    fn check_late_bound_lifetime_defs(&self, params: &[ast::GenericParam]) {
117        // Check only lifetime parameters are present and that the
118        // generic parameters that are present have no bounds.
119        let non_lt_param_spans = params.iter().filter_map(|param| match param.kind {
120            ast::GenericParamKind::Lifetime { .. } => None,
121            _ => Some(param.ident.span),
122        });
123        {
    if !(&self).features.non_lifetime_binders() {
        let spans: Vec<_> =
            non_lt_param_spans.filter(|span|
                        !span.allows_unstable(sym::non_lifetime_binders)).collect();
        if !spans.is_empty() {
            feature_err(&(&self).sess, sym::non_lifetime_binders, spans,
                    crate::fluent_generated::ast_passes_forbidden_non_lifetime_param).emit();
        }
    }
};gate_multi!(
124            &self,
125            non_lifetime_binders,
126            non_lt_param_spans,
127            crate::fluent_generated::ast_passes_forbidden_non_lifetime_param
128        );
129
130        // FIXME(non_lifetime_binders): Const bound params are pretty broken.
131        // Let's keep users from using this feature accidentally.
132        if self.features.non_lifetime_binders() {
133            let const_param_spans: Vec<_> = params
134                .iter()
135                .filter_map(|param| match param.kind {
136                    ast::GenericParamKind::Const { .. } => Some(param.ident.span),
137                    _ => None,
138                })
139                .collect();
140
141            if !const_param_spans.is_empty() {
142                self.sess.dcx().emit_err(errors::ForbiddenConstParam { const_param_spans });
143            }
144        }
145
146        for param in params {
147            if !param.bounds.is_empty() {
148                let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
149                self.sess.dcx().emit_err(errors::ForbiddenBound { spans });
150            }
151        }
152    }
153}
154
155impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
156    fn visit_attribute(&mut self, attr: &ast::Attribute) {
157        let attr_info = attr.name().and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name));
158        // Check feature gates for built-in attributes.
159        if let Some(BuiltinAttribute {
160            gate: AttributeGate::Gated { feature, message, check, notes, .. },
161            ..
162        }) = attr_info
163        {
164            {
    if !check(self.features) && !attr.span.allows_unstable(*feature) {
        let mut diag = feature_err(&self.sess, *feature, attr.span, *message);
        for note in *notes { diag.note(*note); }
        diag.emit();
    }
};gate_alt!(self, check(self.features), *feature, attr.span, *message, *notes);
165        }
166        // Check unstable flavors of the `#[doc]` attribute.
167        if attr.has_name(sym::doc) {
168            for meta_item_inner in attr.meta_item_list().unwrap_or_default() {
169                macro_rules! gate_doc { ($($s:literal { $($name:ident => $feature:ident)* })*) => {
170                    $($(if meta_item_inner.has_name(sym::$name) {
171                        let msg = concat!("`#[doc(", stringify!($name), ")]` is ", $s);
172                        gate!(self, $feature, attr.span, msg);
173                    })*)*
174                }}
175
176                if meta_item_inner.has_name(sym::search_unbox) {
    let msg = "`#[doc(search_unbox)]` is meant for internal use only";
    {
        if !self.features.rustdoc_internals() &&
                !attr.span.allows_unstable(sym::rustdoc_internals) {
            feature_err(&self.sess, sym::rustdoc_internals, attr.span,
                    msg).emit();
        }
    };
};gate_doc!(
177                    "experimental" {
178                        cfg => doc_cfg
179                        auto_cfg => doc_cfg
180                        masked => doc_masked
181                        notable_trait => doc_notable_trait
182                    }
183                    "meant for internal use only" {
184                        attribute => rustdoc_internals
185                        keyword => rustdoc_internals
186                        fake_variadic => rustdoc_internals
187                        search_unbox => rustdoc_internals
188                    }
189                );
190            }
191        }
192    }
193
194    fn visit_item(&mut self, i: &'a ast::Item) {
195        match &i.kind {
196            ast::ItemKind::ForeignMod(_foreign_module) => {
197                // handled during lowering
198            }
199            ast::ItemKind::Struct(..) | ast::ItemKind::Enum(..) | ast::ItemKind::Union(..) => {
200                for attr in attr::filter_by_name(&i.attrs, sym::repr) {
201                    for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) {
202                        if item.has_name(sym::simd) {
203                            {
    if !(&self).features.repr_simd() &&
            !attr.span.allows_unstable(sym::repr_simd) {
        feature_err(&(&self).sess, sym::repr_simd, attr.span,
                "SIMD types are experimental and possibly buggy").emit();
    }
};gate!(
204                                &self,
205                                repr_simd,
206                                attr.span,
207                                "SIMD types are experimental and possibly buggy"
208                            );
209                        }
210                    }
211                }
212            }
213
214            ast::ItemKind::Impl(ast::Impl { of_trait: Some(of_trait), .. }) => {
215                if let ast::ImplPolarity::Negative(span) = of_trait.polarity {
216                    {
    if !(&self).features.negative_impls() &&
            !span.to(of_trait.trait_ref.path.span).allows_unstable(sym::negative_impls)
        {
        feature_err(&(&self).sess, sym::negative_impls,
                span.to(of_trait.trait_ref.path.span),
                "negative trait bounds are not fully implemented; \
                         use marker types for now").emit();
    }
};gate!(
217                        &self,
218                        negative_impls,
219                        span.to(of_trait.trait_ref.path.span),
220                        "negative trait bounds are not fully implemented; \
221                         use marker types for now"
222                    );
223                }
224
225                if let ast::Defaultness::Default(_) = of_trait.defaultness {
226                    {
    if !(&self).features.specialization() &&
            !i.span.allows_unstable(sym::specialization) {
        feature_err(&(&self).sess, sym::specialization, i.span,
                "specialization is unstable").emit();
    }
};gate!(&self, specialization, i.span, "specialization is unstable");
227                }
228            }
229
230            ast::ItemKind::Trait(box ast::Trait { is_auto: ast::IsAuto::Yes, .. }) => {
231                {
    if !(&self).features.auto_traits() &&
            !i.span.allows_unstable(sym::auto_traits) {
        feature_err(&(&self).sess, sym::auto_traits, i.span,
                "auto traits are experimental and possibly buggy").emit();
    }
};gate!(
232                    &self,
233                    auto_traits,
234                    i.span,
235                    "auto traits are experimental and possibly buggy"
236                );
237            }
238
239            ast::ItemKind::TraitAlias(..) => {
240                {
    if !(&self).features.trait_alias() &&
            !i.span.allows_unstable(sym::trait_alias) {
        feature_err(&(&self).sess, sym::trait_alias, i.span,
                "trait aliases are experimental").emit();
    }
};gate!(&self, trait_alias, i.span, "trait aliases are experimental");
241            }
242
243            ast::ItemKind::MacroDef(_, ast::MacroDef { macro_rules: false, .. }) => {
244                let msg = "`macro` is experimental";
245                {
    if !(&self).features.decl_macro() &&
            !i.span.allows_unstable(sym::decl_macro) {
        feature_err(&(&self).sess, sym::decl_macro, i.span, msg).emit();
    }
};gate!(&self, decl_macro, i.span, msg);
246            }
247
248            ast::ItemKind::TyAlias(box ast::TyAlias { ty: Some(ty), .. }) => {
249                self.check_impl_trait(ty, false)
250            }
251
252            _ => {}
253        }
254
255        visit::walk_item(self, i);
256    }
257
258    fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
259        match i.kind {
260            ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
261                let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
262                let links_to_llvm = link_name.is_some_and(|val| val.as_str().starts_with("llvm."));
263                if links_to_llvm {
264                    {
    if !(&self).features.link_llvm_intrinsics() &&
            !i.span.allows_unstable(sym::link_llvm_intrinsics) {
        feature_err(&(&self).sess, sym::link_llvm_intrinsics, i.span,
                "linking to LLVM intrinsics is experimental").emit();
    }
};gate!(
265                        &self,
266                        link_llvm_intrinsics,
267                        i.span,
268                        "linking to LLVM intrinsics is experimental"
269                    );
270                }
271            }
272            ast::ForeignItemKind::TyAlias(..) => {
273                {
    if !(&self).features.extern_types() &&
            !i.span.allows_unstable(sym::extern_types) {
        feature_err(&(&self).sess, sym::extern_types, i.span,
                "extern types are experimental").emit();
    }
};gate!(&self, extern_types, i.span, "extern types are experimental");
274            }
275            ast::ForeignItemKind::MacCall(..) => {}
276        }
277
278        visit::walk_item(self, i)
279    }
280
281    fn visit_ty(&mut self, ty: &'a ast::Ty) {
282        match &ty.kind {
283            ast::TyKind::FnPtr(fn_ptr_ty) => {
284                // Function pointers cannot be `const`
285                self.check_late_bound_lifetime_defs(&fn_ptr_ty.generic_params);
286            }
287            ast::TyKind::Never => {
288                {
    if !(&self).features.never_type() &&
            !ty.span.allows_unstable(sym::never_type) {
        feature_err(&(&self).sess, sym::never_type, ty.span,
                "the `!` type is experimental").emit();
    }
};gate!(&self, never_type, ty.span, "the `!` type is experimental");
289            }
290            ast::TyKind::Pat(..) => {
291                {
    if !(&self).features.pattern_types() &&
            !ty.span.allows_unstable(sym::pattern_types) {
        feature_err(&(&self).sess, sym::pattern_types, ty.span,
                "pattern types are unstable").emit();
    }
};gate!(&self, pattern_types, ty.span, "pattern types are unstable");
292            }
293            _ => {}
294        }
295        visit::walk_ty(self, ty)
296    }
297
298    fn visit_where_predicate_kind(&mut self, kind: &'a ast::WherePredicateKind) {
299        if let ast::WherePredicateKind::BoundPredicate(bound) = kind {
300            // A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
301            self.check_late_bound_lifetime_defs(&bound.bound_generic_params);
302        }
303        visit::walk_where_predicate_kind(self, kind);
304    }
305
306    fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
307        if let ast::FnRetTy::Ty(output_ty) = ret_ty {
308            if let ast::TyKind::Never = output_ty.kind {
309                // Do nothing.
310            } else {
311                self.visit_ty(output_ty)
312            }
313        }
314    }
315
316    fn visit_generic_args(&mut self, args: &'a ast::GenericArgs) {
317        // This check needs to happen here because the never type can be returned from a function,
318        // but cannot be used in any other context. If this check was in `visit_fn_ret_ty`, it
319        // include both functions and generics like `impl Fn() -> !`.
320        if let ast::GenericArgs::Parenthesized(generic_args) = args
321            && let ast::FnRetTy::Ty(ref ty) = generic_args.output
322            && #[allow(non_exhaustive_omitted_patterns)] match ty.kind {
    ast::TyKind::Never => true,
    _ => false,
}matches!(ty.kind, ast::TyKind::Never)
323        {
324            {
    if !(&self).features.never_type() &&
            !ty.span.allows_unstable(sym::never_type) {
        feature_err(&(&self).sess, sym::never_type, ty.span,
                "the `!` type is experimental").emit();
    }
};gate!(&self, never_type, ty.span, "the `!` type is experimental");
325        }
326        visit::walk_generic_args(self, args);
327    }
328
329    fn visit_expr(&mut self, e: &'a ast::Expr) {
330        match e.kind {
331            ast::ExprKind::TryBlock(_, None) => {
332                {
    if !(&self).features.try_blocks() &&
            !e.span.allows_unstable(sym::try_blocks) {
        feature_err(&(&self).sess, sym::try_blocks, e.span,
                "`try` expression is experimental").emit();
    }
};gate!(&self, try_blocks, e.span, "`try` expression is experimental");
333            }
334            ast::ExprKind::TryBlock(_, Some(_)) => {
335                {
    if !(&self).features.try_blocks_heterogeneous() &&
            !e.span.allows_unstable(sym::try_blocks_heterogeneous) {
        feature_err(&(&self).sess, sym::try_blocks_heterogeneous, e.span,
                "`try bikeshed` expression is experimental").emit();
    }
};gate!(
336                    &self,
337                    try_blocks_heterogeneous,
338                    e.span,
339                    "`try bikeshed` expression is experimental"
340                );
341            }
342            ast::ExprKind::Lit(token::Lit {
343                kind: token::LitKind::Float | token::LitKind::Integer,
344                suffix,
345                ..
346            }) => match suffix {
347                Some(sym::f16) => {
348                    {
    if !(&self).features.f16() && !e.span.allows_unstable(sym::f16) {
        feature_err(&(&self).sess, sym::f16, e.span,
                "the type `f16` is unstable").emit();
    }
}gate!(&self, f16, e.span, "the type `f16` is unstable")
349                }
350                Some(sym::f128) => {
351                    {
    if !(&self).features.f128() && !e.span.allows_unstable(sym::f128) {
        feature_err(&(&self).sess, sym::f128, e.span,
                "the type `f128` is unstable").emit();
    }
}gate!(&self, f128, e.span, "the type `f128` is unstable")
352                }
353                _ => (),
354            },
355            _ => {}
356        }
357        visit::walk_expr(self, e)
358    }
359
360    fn visit_pat(&mut self, pattern: &'a ast::Pat) {
361        match &pattern.kind {
362            PatKind::Slice(pats) => {
363                for pat in pats {
364                    let inner_pat = match &pat.kind {
365                        PatKind::Ident(.., Some(pat)) => pat,
366                        _ => pat,
367                    };
368                    if let PatKind::Range(Some(_), None, Spanned { .. }) = inner_pat.kind {
369                        {
    if !(&self).features.half_open_range_patterns_in_slices() &&
            !pat.span.allows_unstable(sym::half_open_range_patterns_in_slices)
        {
        feature_err(&(&self).sess, sym::half_open_range_patterns_in_slices,
                pat.span, "`X..` patterns in slices are experimental").emit();
    }
};gate!(
370                            &self,
371                            half_open_range_patterns_in_slices,
372                            pat.span,
373                            "`X..` patterns in slices are experimental"
374                        );
375                    }
376                }
377            }
378            PatKind::Box(..) => {
379                {
    if !(&self).features.box_patterns() &&
            !pattern.span.allows_unstable(sym::box_patterns) {
        feature_err(&(&self).sess, sym::box_patterns, pattern.span,
                "box pattern syntax is experimental").emit();
    }
};gate!(&self, box_patterns, pattern.span, "box pattern syntax is experimental");
380            }
381            _ => {}
382        }
383        visit::walk_pat(self, pattern)
384    }
385
386    fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) {
387        self.check_late_bound_lifetime_defs(&t.bound_generic_params);
388        visit::walk_poly_trait_ref(self, t);
389    }
390
391    fn visit_fn(&mut self, fn_kind: FnKind<'a>, _: &AttrVec, span: Span, _: NodeId) {
392        if let Some(_header) = fn_kind.header() {
393            // Stability of const fn methods are covered in `visit_assoc_item` below.
394        }
395
396        if let FnKind::Closure(ast::ClosureBinder::For { generic_params, .. }, ..) = fn_kind {
397            self.check_late_bound_lifetime_defs(generic_params);
398        }
399
400        if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
401            {
    if !(&self).features.c_variadic() &&
            !span.allows_unstable(sym::c_variadic) {
        feature_err(&(&self).sess, sym::c_variadic, span,
                "C-variadic functions are unstable").emit();
    }
};gate!(&self, c_variadic, span, "C-variadic functions are unstable");
402        }
403
404        visit::walk_fn(self, fn_kind)
405    }
406
407    fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
408        let is_fn = match &i.kind {
409            ast::AssocItemKind::Fn(_) => true,
410            ast::AssocItemKind::Type(box ast::TyAlias { ty, .. }) => {
411                if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
412                    {
    if !(&self).features.associated_type_defaults() &&
            !i.span.allows_unstable(sym::associated_type_defaults) {
        feature_err(&(&self).sess, sym::associated_type_defaults, i.span,
                "associated type defaults are unstable").emit();
    }
};gate!(
413                        &self,
414                        associated_type_defaults,
415                        i.span,
416                        "associated type defaults are unstable"
417                    );
418                }
419                if let Some(ty) = ty {
420                    self.check_impl_trait(ty, true);
421                }
422                false
423            }
424            _ => false,
425        };
426        if let ast::Defaultness::Default(_) = i.kind.defaultness() {
427            // Limit `min_specialization` to only specializing functions.
428            {
    if !(self.features.specialization() ||
                    (is_fn && self.features.min_specialization())) &&
            !i.span.allows_unstable(sym::specialization) {
        feature_err(&(&self).sess, sym::specialization, i.span,
                "specialization is unstable").emit();
    }
};gate_alt!(
429                &self,
430                self.features.specialization() || (is_fn && self.features.min_specialization()),
431                sym::specialization,
432                i.span,
433                "specialization is unstable"
434            );
435        }
436        visit::walk_assoc_item(self, i, ctxt)
437    }
438}
439
440pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) {
441    maybe_stage_features(sess, features, krate);
442    check_incompatible_features(sess, features);
443    check_new_solver_banned_features(sess, features);
444
445    let mut visitor = PostExpansionVisitor { sess, features };
446
447    let spans = sess.psess.gated_spans.spans.borrow();
448    macro_rules! gate_all {
449        ($gate:ident, $msg:literal) => {
450            if let Some(spans) = spans.get(&sym::$gate) {
451                for span in spans {
452                    gate!(&visitor, $gate, *span, $msg);
453                }
454            }
455        };
456        ($gate:ident, $msg:literal, $help:literal) => {
457            if let Some(spans) = spans.get(&sym::$gate) {
458                for span in spans {
459                    gate!(&visitor, $gate, *span, $msg, $help);
460                }
461            }
462        };
463    }
464    if let Some(spans) = spans.get(&sym::if_let_guard) {
    for span in spans {
        {
            if !(&visitor).features.if_let_guard() &&
                    !(*span).allows_unstable(sym::if_let_guard) {
                feature_err(&(&visitor).sess, sym::if_let_guard, *span,
                            "`if let` guards are experimental").with_help("you can write `if matches!(<expr>, <pattern>)` instead of `if let <pattern> = <expr>`").emit();
            }
        };
    }
};gate_all!(
465        if_let_guard,
466        "`if let` guards are experimental",
467        "you can write `if matches!(<expr>, <pattern>)` instead of `if let <pattern> = <expr>`"
468    );
469    if let Some(spans) = spans.get(&sym::async_trait_bounds) {
    for span in spans {
        {
            if !(&visitor).features.async_trait_bounds() &&
                    !(*span).allows_unstable(sym::async_trait_bounds) {
                feature_err(&(&visitor).sess, sym::async_trait_bounds, *span,
                            "`async` trait bounds are unstable").with_help("use the desugared name of the async trait, such as `AsyncFn`").emit();
            }
        };
    }
};gate_all!(
470        async_trait_bounds,
471        "`async` trait bounds are unstable",
472        "use the desugared name of the async trait, such as `AsyncFn`"
473    );
474    if let Some(spans) = spans.get(&sym::async_for_loop) {
    for span in spans {
        {
            if !(&visitor).features.async_for_loop() &&
                    !(*span).allows_unstable(sym::async_for_loop) {
                feature_err(&(&visitor).sess, sym::async_for_loop, *span,
                        "`for await` loops are experimental").emit();
            }
        };
    }
};gate_all!(async_for_loop, "`for await` loops are experimental");
475    if let Some(spans) = spans.get(&sym::closure_lifetime_binder) {
    for span in spans {
        {
            if !(&visitor).features.closure_lifetime_binder() &&
                    !(*span).allows_unstable(sym::closure_lifetime_binder) {
                feature_err(&(&visitor).sess, sym::closure_lifetime_binder,
                            *span,
                            "`for<...>` binders for closures are experimental").with_help("consider removing `for<...>`").emit();
            }
        };
    }
};gate_all!(
476        closure_lifetime_binder,
477        "`for<...>` binders for closures are experimental",
478        "consider removing `for<...>`"
479    );
480    if let Some(spans) = spans.get(&sym::more_qualified_paths) {
    for span in spans {
        {
            if !(&visitor).features.more_qualified_paths() &&
                    !(*span).allows_unstable(sym::more_qualified_paths) {
                feature_err(&(&visitor).sess, sym::more_qualified_paths,
                        *span,
                        "usage of qualified paths in this context is experimental").emit();
            }
        };
    }
};gate_all!(more_qualified_paths, "usage of qualified paths in this context is experimental");
481    // yield can be enabled either by `coroutines` or `gen_blocks`
482    if let Some(spans) = spans.get(&sym::yield_expr) {
483        for span in spans {
484            if (!visitor.features.coroutines() && !span.allows_unstable(sym::coroutines))
485                && (!visitor.features.gen_blocks() && !span.allows_unstable(sym::gen_blocks))
486                && (!visitor.features.yield_expr() && !span.allows_unstable(sym::yield_expr))
487            {
488                // Emit yield_expr as the error, since that will be sufficient. You can think of it
489                // as coroutines and gen_blocks imply yield_expr.
490                feature_err(&visitor.sess, sym::yield_expr, *span, "yield syntax is experimental")
491                    .emit();
492            }
493        }
494    }
495    if let Some(spans) = spans.get(&sym::gen_blocks) {
    for span in spans {
        {
            if !(&visitor).features.gen_blocks() &&
                    !(*span).allows_unstable(sym::gen_blocks) {
                feature_err(&(&visitor).sess, sym::gen_blocks, *span,
                        "gen blocks are experimental").emit();
            }
        };
    }
};gate_all!(gen_blocks, "gen blocks are experimental");
496    if let Some(spans) = spans.get(&sym::const_trait_impl) {
    for span in spans {
        {
            if !(&visitor).features.const_trait_impl() &&
                    !(*span).allows_unstable(sym::const_trait_impl) {
                feature_err(&(&visitor).sess, sym::const_trait_impl, *span,
                        "const trait impls are experimental").emit();
            }
        };
    }
};gate_all!(const_trait_impl, "const trait impls are experimental");
497    if let Some(spans) = spans.get(&sym::half_open_range_patterns_in_slices) {
    for span in spans {
        {
            if !(&visitor).features.half_open_range_patterns_in_slices() &&
                    !(*span).allows_unstable(sym::half_open_range_patterns_in_slices)
                {
                feature_err(&(&visitor).sess,
                        sym::half_open_range_patterns_in_slices, *span,
                        "half-open range patterns in slices are unstable").emit();
            }
        };
    }
};gate_all!(
498        half_open_range_patterns_in_slices,
499        "half-open range patterns in slices are unstable"
500    );
501    if let Some(spans) = spans.get(&sym::yeet_expr) {
    for span in spans {
        {
            if !(&visitor).features.yeet_expr() &&
                    !(*span).allows_unstable(sym::yeet_expr) {
                feature_err(&(&visitor).sess, sym::yeet_expr, *span,
                        "`do yeet` expression is experimental").emit();
            }
        };
    }
};gate_all!(yeet_expr, "`do yeet` expression is experimental");
502    if let Some(spans) = spans.get(&sym::const_closures) {
    for span in spans {
        {
            if !(&visitor).features.const_closures() &&
                    !(*span).allows_unstable(sym::const_closures) {
                feature_err(&(&visitor).sess, sym::const_closures, *span,
                        "const closures are experimental").emit();
            }
        };
    }
};gate_all!(const_closures, "const closures are experimental");
503    if let Some(spans) = spans.get(&sym::builtin_syntax) {
    for span in spans {
        {
            if !(&visitor).features.builtin_syntax() &&
                    !(*span).allows_unstable(sym::builtin_syntax) {
                feature_err(&(&visitor).sess, sym::builtin_syntax, *span,
                        "`builtin #` syntax is unstable").emit();
            }
        };
    }
};gate_all!(builtin_syntax, "`builtin #` syntax is unstable");
504    if let Some(spans) = spans.get(&sym::ergonomic_clones) {
    for span in spans {
        {
            if !(&visitor).features.ergonomic_clones() &&
                    !(*span).allows_unstable(sym::ergonomic_clones) {
                feature_err(&(&visitor).sess, sym::ergonomic_clones, *span,
                        "ergonomic clones are experimental").emit();
            }
        };
    }
};gate_all!(ergonomic_clones, "ergonomic clones are experimental");
505    if let Some(spans) = spans.get(&sym::explicit_tail_calls) {
    for span in spans {
        {
            if !(&visitor).features.explicit_tail_calls() &&
                    !(*span).allows_unstable(sym::explicit_tail_calls) {
                feature_err(&(&visitor).sess, sym::explicit_tail_calls, *span,
                        "`become` expression is experimental").emit();
            }
        };
    }
};gate_all!(explicit_tail_calls, "`become` expression is experimental");
506    if let Some(spans) = spans.get(&sym::generic_const_items) {
    for span in spans {
        {
            if !(&visitor).features.generic_const_items() &&
                    !(*span).allows_unstable(sym::generic_const_items) {
                feature_err(&(&visitor).sess, sym::generic_const_items, *span,
                        "generic const items are experimental").emit();
            }
        };
    }
};gate_all!(generic_const_items, "generic const items are experimental");
507    if let Some(spans) = spans.get(&sym::guard_patterns) {
    for span in spans {
        {
            if !(&visitor).features.guard_patterns() &&
                    !(*span).allows_unstable(sym::guard_patterns) {
                feature_err(&(&visitor).sess, sym::guard_patterns, *span,
                            "guard patterns are experimental").with_help("consider using match arm guards").emit();
            }
        };
    }
};gate_all!(guard_patterns, "guard patterns are experimental", "consider using match arm guards");
508    if let Some(spans) = spans.get(&sym::default_field_values) {
    for span in spans {
        {
            if !(&visitor).features.default_field_values() &&
                    !(*span).allows_unstable(sym::default_field_values) {
                feature_err(&(&visitor).sess, sym::default_field_values,
                        *span, "default values on fields are experimental").emit();
            }
        };
    }
};gate_all!(default_field_values, "default values on fields are experimental");
509    if let Some(spans) = spans.get(&sym::fn_delegation) {
    for span in spans {
        {
            if !(&visitor).features.fn_delegation() &&
                    !(*span).allows_unstable(sym::fn_delegation) {
                feature_err(&(&visitor).sess, sym::fn_delegation, *span,
                        "functions delegation is not yet fully implemented").emit();
            }
        };
    }
};gate_all!(fn_delegation, "functions delegation is not yet fully implemented");
510    if let Some(spans) = spans.get(&sym::postfix_match) {
    for span in spans {
        {
            if !(&visitor).features.postfix_match() &&
                    !(*span).allows_unstable(sym::postfix_match) {
                feature_err(&(&visitor).sess, sym::postfix_match, *span,
                        "postfix match is experimental").emit();
            }
        };
    }
};gate_all!(postfix_match, "postfix match is experimental");
511    if let Some(spans) = spans.get(&sym::mut_ref) {
    for span in spans {
        {
            if !(&visitor).features.mut_ref() &&
                    !(*span).allows_unstable(sym::mut_ref) {
                feature_err(&(&visitor).sess, sym::mut_ref, *span,
                        "mutable by-reference bindings are experimental").emit();
            }
        };
    }
};gate_all!(mut_ref, "mutable by-reference bindings are experimental");
512    if let Some(spans) = spans.get(&sym::min_generic_const_args) {
    for span in spans {
        {
            if !(&visitor).features.min_generic_const_args() &&
                    !(*span).allows_unstable(sym::min_generic_const_args) {
                feature_err(&(&visitor).sess, sym::min_generic_const_args,
                        *span,
                        "unbraced const blocks as const args are experimental").emit();
            }
        };
    }
};gate_all!(min_generic_const_args, "unbraced const blocks as const args are experimental");
513    // associated_const_equality is stabilized as part of min_generic_const_args
514    if let Some(spans) = spans.get(&sym::associated_const_equality) {
515        for span in spans {
516            if !visitor.features.min_generic_const_args()
517                && !span.allows_unstable(sym::min_generic_const_args)
518            {
519                feature_err(
520                    &visitor.sess,
521                    sym::min_generic_const_args,
522                    *span,
523                    "associated const equality is incomplete",
524                )
525                .emit();
526            }
527        }
528    }
529    if let Some(spans) = spans.get(&sym::global_registration) {
    for span in spans {
        {
            if !(&visitor).features.global_registration() &&
                    !(*span).allows_unstable(sym::global_registration) {
                feature_err(&(&visitor).sess, sym::global_registration, *span,
                        "global registration is experimental").emit();
            }
        };
    }
};gate_all!(global_registration, "global registration is experimental");
530    if let Some(spans) = spans.get(&sym::return_type_notation) {
    for span in spans {
        {
            if !(&visitor).features.return_type_notation() &&
                    !(*span).allows_unstable(sym::return_type_notation) {
                feature_err(&(&visitor).sess, sym::return_type_notation,
                        *span, "return type notation is experimental").emit();
            }
        };
    }
};gate_all!(return_type_notation, "return type notation is experimental");
531    if let Some(spans) = spans.get(&sym::pin_ergonomics) {
    for span in spans {
        {
            if !(&visitor).features.pin_ergonomics() &&
                    !(*span).allows_unstable(sym::pin_ergonomics) {
                feature_err(&(&visitor).sess, sym::pin_ergonomics, *span,
                        "pinned reference syntax is experimental").emit();
            }
        };
    }
};gate_all!(pin_ergonomics, "pinned reference syntax is experimental");
532    if let Some(spans) = spans.get(&sym::unsafe_fields) {
    for span in spans {
        {
            if !(&visitor).features.unsafe_fields() &&
                    !(*span).allows_unstable(sym::unsafe_fields) {
                feature_err(&(&visitor).sess, sym::unsafe_fields, *span,
                        "`unsafe` fields are experimental").emit();
            }
        };
    }
};gate_all!(unsafe_fields, "`unsafe` fields are experimental");
533    if let Some(spans) = spans.get(&sym::unsafe_binders) {
    for span in spans {
        {
            if !(&visitor).features.unsafe_binders() &&
                    !(*span).allows_unstable(sym::unsafe_binders) {
                feature_err(&(&visitor).sess, sym::unsafe_binders, *span,
                        "unsafe binder types are experimental").emit();
            }
        };
    }
};gate_all!(unsafe_binders, "unsafe binder types are experimental");
534    if let Some(spans) = spans.get(&sym::contracts) {
    for span in spans {
        {
            if !(&visitor).features.contracts() &&
                    !(*span).allows_unstable(sym::contracts) {
                feature_err(&(&visitor).sess, sym::contracts, *span,
                        "contracts are incomplete").emit();
            }
        };
    }
};gate_all!(contracts, "contracts are incomplete");
535    if let Some(spans) = spans.get(&sym::contracts_internals) {
    for span in spans {
        {
            if !(&visitor).features.contracts_internals() &&
                    !(*span).allows_unstable(sym::contracts_internals) {
                feature_err(&(&visitor).sess, sym::contracts_internals, *span,
                        "contract internal machinery is for internal use only").emit();
            }
        };
    }
};gate_all!(contracts_internals, "contract internal machinery is for internal use only");
536    if let Some(spans) = spans.get(&sym::where_clause_attrs) {
    for span in spans {
        {
            if !(&visitor).features.where_clause_attrs() &&
                    !(*span).allows_unstable(sym::where_clause_attrs) {
                feature_err(&(&visitor).sess, sym::where_clause_attrs, *span,
                        "attributes in `where` clause are unstable").emit();
            }
        };
    }
};gate_all!(where_clause_attrs, "attributes in `where` clause are unstable");
537    if let Some(spans) = spans.get(&sym::super_let) {
    for span in spans {
        {
            if !(&visitor).features.super_let() &&
                    !(*span).allows_unstable(sym::super_let) {
                feature_err(&(&visitor).sess, sym::super_let, *span,
                        "`super let` is experimental").emit();
            }
        };
    }
};gate_all!(super_let, "`super let` is experimental");
538    if let Some(spans) = spans.get(&sym::frontmatter) {
    for span in spans {
        {
            if !(&visitor).features.frontmatter() &&
                    !(*span).allows_unstable(sym::frontmatter) {
                feature_err(&(&visitor).sess, sym::frontmatter, *span,
                        "frontmatters are experimental").emit();
            }
        };
    }
};gate_all!(frontmatter, "frontmatters are experimental");
539    if let Some(spans) = spans.get(&sym::coroutines) {
    for span in spans {
        {
            if !(&visitor).features.coroutines() &&
                    !(*span).allows_unstable(sym::coroutines) {
                feature_err(&(&visitor).sess, sym::coroutines, *span,
                        "coroutine syntax is experimental").emit();
            }
        };
    }
};gate_all!(coroutines, "coroutine syntax is experimental");
540    if let Some(spans) = spans.get(&sym::const_block_items) {
    for span in spans {
        {
            if !(&visitor).features.const_block_items() &&
                    !(*span).allows_unstable(sym::const_block_items) {
                feature_err(&(&visitor).sess, sym::const_block_items, *span,
                        "const block items are experimental").emit();
            }
        };
    }
};gate_all!(const_block_items, "const block items are experimental");
541
542    if !visitor.features.never_patterns() {
543        if let Some(spans) = spans.get(&sym::never_patterns) {
544            for &span in spans {
545                if span.allows_unstable(sym::never_patterns) {
546                    continue;
547                }
548                let sm = sess.source_map();
549                // We gate two types of spans: the span of a `!` pattern, and the span of a
550                // match arm without a body. For the latter we want to give the user a normal
551                // error.
552                if let Ok(snippet) = sm.span_to_snippet(span)
553                    && snippet == "!"
554                {
555                    feature_err(sess, sym::never_patterns, span, "`!` patterns are experimental")
556                        .emit();
557                } else {
558                    let suggestion = span.shrink_to_hi();
559                    sess.dcx().emit_err(errors::MatchArmWithNoBody { span, suggestion });
560                }
561            }
562        }
563    }
564
565    if !visitor.features.negative_bounds() {
566        for &span in spans.get(&sym::negative_bounds).iter().copied().flatten() {
567            sess.dcx().emit_err(errors::NegativeBoundUnsupported { span });
568        }
569    }
570
571    // All uses of `gate_all_legacy_dont_use!` below this point were added in #65742,
572    // and subsequently disabled (with the non-early gating readded).
573    // We emit an early future-incompatible warning for these.
574    // New syntax gates should go above here to get a hard error gate.
575    macro_rules! gate_all_legacy_dont_use {
576        ($gate:ident, $msg:literal) => {
577            for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
578                gate_legacy!(&visitor, $gate, *span, $msg);
579            }
580        };
581    }
582
583    for span in spans.get(&sym::box_patterns).unwrap_or(&::alloc::vec::Vec::new())
    {
    {
        if !(&visitor).features.box_patterns() &&
                !(*span).allows_unstable(sym::box_patterns) {
            feature_warn(&(&visitor).sess, sym::box_patterns, *span,
                "box pattern syntax is experimental");
        }
    };
};gate_all_legacy_dont_use!(box_patterns, "box pattern syntax is experimental");
584    for span in spans.get(&sym::trait_alias).unwrap_or(&::alloc::vec::Vec::new())
    {
    {
        if !(&visitor).features.trait_alias() &&
                !(*span).allows_unstable(sym::trait_alias) {
            feature_warn(&(&visitor).sess, sym::trait_alias, *span,
                "trait aliases are experimental");
        }
    };
};gate_all_legacy_dont_use!(trait_alias, "trait aliases are experimental");
585    for span in spans.get(&sym::decl_macro).unwrap_or(&::alloc::vec::Vec::new()) {
    {
        if !(&visitor).features.decl_macro() &&
                !(*span).allows_unstable(sym::decl_macro) {
            feature_warn(&(&visitor).sess, sym::decl_macro, *span,
                "`macro` is experimental");
        }
    };
};gate_all_legacy_dont_use!(decl_macro, "`macro` is experimental");
586    for span in spans.get(&sym::try_blocks).unwrap_or(&::alloc::vec::Vec::new()) {
    {
        if !(&visitor).features.try_blocks() &&
                !(*span).allows_unstable(sym::try_blocks) {
            feature_warn(&(&visitor).sess, sym::try_blocks, *span,
                "`try` blocks are unstable");
        }
    };
};gate_all_legacy_dont_use!(try_blocks, "`try` blocks are unstable");
587    for span in spans.get(&sym::auto_traits).unwrap_or(&::alloc::vec::Vec::new())
    {
    {
        if !(&visitor).features.auto_traits() &&
                !(*span).allows_unstable(sym::auto_traits) {
            feature_warn(&(&visitor).sess, sym::auto_traits, *span,
                "`auto` traits are unstable");
        }
    };
};gate_all_legacy_dont_use!(auto_traits, "`auto` traits are unstable");
588
589    visit::walk_crate(&mut visitor, krate);
590}
591
592fn maybe_stage_features(sess: &Session, features: &Features, krate: &ast::Crate) {
593    // checks if `#![feature]` has been used to enable any feature.
594    if sess.opts.unstable_features.is_nightly_build() {
595        return;
596    }
597    if features.enabled_features().is_empty() {
598        return;
599    }
600    let mut errored = false;
601    for attr in krate.attrs.iter().filter(|attr| attr.has_name(sym::feature)) {
602        // `feature(...)` used on non-nightly. This is definitely an error.
603        let mut err = errors::FeatureOnNonNightly {
604            span: attr.span,
605            channel: ::core::option::Option::Some("nightly")option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)"),
606            stable_features: ::alloc::vec::Vec::new()vec![],
607            sugg: None,
608        };
609
610        let mut all_stable = true;
611        for ident in attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident()) {
612            let name = ident.name;
613            let stable_since = features
614                .enabled_lang_features()
615                .iter()
616                .find(|feat| feat.gate_name == name)
617                .map(|feat| feat.stable_since)
618                .flatten();
619            if let Some(since) = stable_since {
620                err.stable_features.push(errors::StableFeature { name, since });
621            } else {
622                all_stable = false;
623            }
624        }
625        if all_stable {
626            err.sugg = Some(attr.span);
627        }
628        sess.dcx().emit_err(err);
629        errored = true;
630    }
631    // Just make sure we actually error if anything is listed in `enabled_features`.
632    if !errored { ::core::panicking::panic("assertion failed: errored") };assert!(errored);
633}
634
635fn check_incompatible_features(sess: &Session, features: &Features) {
636    let enabled_features = features.enabled_features_iter_stable_order();
637
638    for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES
639        .iter()
640        .filter(|(f1, f2)| features.enabled(*f1) && features.enabled(*f2))
641    {
642        if let Some((f1_name, f1_span)) = enabled_features.clone().find(|(name, _)| name == f1)
643            && let Some((f2_name, f2_span)) = enabled_features.clone().find(|(name, _)| name == f2)
644        {
645            let spans = <[_]>::into_vec(::alloc::boxed::box_new([f1_span, f2_span]))vec![f1_span, f2_span];
646            sess.dcx().emit_err(errors::IncompatibleFeatures { spans, f1: f1_name, f2: f2_name });
647        }
648    }
649}
650
651fn check_new_solver_banned_features(sess: &Session, features: &Features) {
652    if !sess.opts.unstable_opts.next_solver.globally {
653        return;
654    }
655
656    // Ban GCE with the new solver, because it does not implement GCE correctly.
657    if let Some(gce_span) = features
658        .enabled_lang_features()
659        .iter()
660        .find(|feat| feat.gate_name == sym::generic_const_exprs)
661        .map(|feat| feat.attr_sp)
662    {
663        #[allow(rustc::symbol_intern_string_literal)]
664        sess.dcx().emit_err(errors::IncompatibleFeatures {
665            spans: <[_]>::into_vec(::alloc::boxed::box_new([gce_span]))vec![gce_span],
666            f1: Symbol::intern("-Znext-solver=globally"),
667            f2: sym::generic_const_exprs,
668        });
669    }
670}