Skip to main content

rustc_hir_analysis/check/
check.rs

1use std::cell::LazyCell;
2use std::ops::ControlFlow;
3
4use rustc_abi::{ExternAbi, FieldIdx, ScalableElt};
5use rustc_data_structures::unord::{UnordMap, UnordSet};
6use rustc_errors::codes::*;
7use rustc_errors::{EmissionGuarantee, MultiSpan};
8use rustc_hir as hir;
9use rustc_hir::attrs::ReprAttr::ReprPacked;
10use rustc_hir::def::{CtorKind, DefKind};
11use rustc_hir::{LangItem, Node, find_attr, intravisit};
12use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
13use rustc_infer::traits::{Obligation, ObligationCauseCode, WellFormedLoc};
14use rustc_lint_defs::builtin::{REPR_TRANSPARENT_NON_ZST_FIELDS, UNSUPPORTED_CALLING_CONVENTIONS};
15use rustc_middle::hir::nested_filter;
16use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
17use rustc_middle::middle::stability::EvalResult;
18use rustc_middle::ty::error::TypeErrorToStringExt;
19use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
20use rustc_middle::ty::util::Discr;
21use rustc_middle::ty::{
22    AdtDef, BottomUpFolder, FnSig, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable,
23    TypeVisitable, TypeVisitableExt, fold_regions,
24};
25use rustc_session::lint::builtin::UNINHABITED_STATIC;
26use rustc_span::source_map::Spanned;
27use rustc_target::spec::{AbiMap, AbiMapping};
28use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
29use rustc_trait_selection::traits;
30use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
31use tracing::{debug, instrument};
32use ty::TypingMode;
33
34use super::compare_impl_item::check_type_bounds;
35use super::*;
36use crate::check::wfcheck::{
37    check_associated_item, check_trait_item, check_variances_for_type_defn, check_where_clauses,
38    enter_wf_checking_ctxt,
39};
40
41fn add_abi_diag_help<T: EmissionGuarantee>(abi: ExternAbi, diag: &mut Diag<'_, T>) {
42    if let ExternAbi::Cdecl { unwind } = abi {
43        let c_abi = ExternAbi::C { unwind };
44        diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `extern {0}` instead", c_abi))
    })format!("use `extern {c_abi}` instead",));
45    } else if let ExternAbi::Stdcall { unwind } = abi {
46        let c_abi = ExternAbi::C { unwind };
47        let system_abi = ExternAbi::System { unwind };
48        diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you need `extern {0}` on win32 and `extern {1}` everywhere else, use `extern {2}`",
                abi, c_abi, system_abi))
    })format!(
49            "if you need `extern {abi}` on win32 and `extern {c_abi}` everywhere else, \
50                use `extern {system_abi}`"
51        ));
52    }
53}
54
55pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: ExternAbi) {
56    // FIXME: This should be checked earlier, e.g. in `rustc_ast_lowering`, as this
57    // currently only guards function imports, function definitions, and function pointer types.
58    // Functions in trait declarations can still use "deprecated" ABIs without any warning.
59
60    match AbiMap::from_target(&tcx.sess.target).canonize_abi(abi, false) {
61        AbiMapping::Direct(..) => (),
62        // already erred in rustc_ast_lowering
63        AbiMapping::Invalid => {
64            tcx.dcx().span_delayed_bug(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} should be rejected in ast_lowering",
                abi))
    })format!("{abi} should be rejected in ast_lowering"));
65        }
66        AbiMapping::Deprecated(..) => {
67            tcx.node_span_lint(UNSUPPORTED_CALLING_CONVENTIONS, hir_id, span, |lint| {
68                lint.primary_message(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} is not a supported ABI for the current target",
                abi))
    })format!(
69                    "{abi} is not a supported ABI for the current target"
70                ));
71                add_abi_diag_help(abi, lint);
72            });
73        }
74    }
75}
76
77pub fn check_custom_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, fn_sig: FnSig<'_>, fn_sig_span: Span) {
78    if fn_sig.abi == ExternAbi::Custom {
79        // Function definitions that use `extern "custom"` must be naked functions.
80        if !{

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in tcx.get_all_attrs(def_id) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(Naked(_)) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(tcx, def_id, Naked(_)) {
81            tcx.dcx().emit_err(crate::errors::AbiCustomClothedFunction {
82                span: fn_sig_span,
83                naked_span: tcx.def_span(def_id).shrink_to_lo(),
84            });
85        }
86    }
87}
88
89fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) {
90    let def = tcx.adt_def(def_id);
91    let span = tcx.def_span(def_id);
92    def.destructor(tcx); // force the destructor to be evaluated
93
94    if let Some(scalable) = def.repr().scalable {
95        check_scalable_vector(tcx, span, def_id, scalable);
96    } else if def.repr().simd() {
97        check_simd(tcx, span, def_id);
98    }
99
100    check_transparent(tcx, def);
101    check_packed(tcx, span, def);
102}
103
104fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) {
105    let def = tcx.adt_def(def_id);
106    let span = tcx.def_span(def_id);
107    def.destructor(tcx); // force the destructor to be evaluated
108    check_transparent(tcx, def);
109    check_union_fields(tcx, span, def_id);
110    check_packed(tcx, span, def);
111}
112
113fn allowed_union_or_unsafe_field<'tcx>(
114    tcx: TyCtxt<'tcx>,
115    ty: Ty<'tcx>,
116    typing_env: ty::TypingEnv<'tcx>,
117    span: Span,
118) -> bool {
119    // HACK (not that bad of a hack don't worry): Some codegen tests don't even define proper
120    // impls for `Copy`. Let's short-circuit here for this validity check, since a lot of them
121    // use unions. We should eventually fix all the tests to define that lang item or use
122    // minicore stubs.
123    if ty.is_trivially_pure_clone_copy() {
124        return true;
125    }
126    // If `BikeshedGuaranteedNoDrop` is not defined in a `#[no_core]` test, fall back to `Copy`.
127    // This is an underapproximation of `BikeshedGuaranteedNoDrop`,
128    let def_id = tcx
129        .lang_items()
130        .get(LangItem::BikeshedGuaranteedNoDrop)
131        .unwrap_or_else(|| tcx.require_lang_item(LangItem::Copy, span));
132    let Ok(ty) = tcx.try_normalize_erasing_regions(typing_env, ty) else {
133        tcx.dcx().span_delayed_bug(span, "could not normalize field type");
134        return true;
135    };
136    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
137    infcx.predicate_must_hold_modulo_regions(&Obligation::new(
138        tcx,
139        ObligationCause::dummy_with_span(span),
140        param_env,
141        ty::TraitRef::new(tcx, def_id, [ty]),
142    ))
143}
144
145/// Check that the fields of the `union` do not need dropping.
146fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
147    let def = tcx.adt_def(item_def_id);
148    if !def.is_union() {
    ::core::panicking::panic("assertion failed: def.is_union()")
};assert!(def.is_union());
149
150    let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
151    let args = ty::GenericArgs::identity_for_item(tcx, item_def_id);
152
153    for field in &def.non_enum_variant().fields {
154        if !allowed_union_or_unsafe_field(tcx, field.ty(tcx, args), typing_env, span) {
155            let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {
156                // We are currently checking the type this field came from, so it must be local.
157                Some(Node::Field(field)) => (field.span, field.ty.span),
158                _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("mir field has to correspond to hir field")));
}unreachable!("mir field has to correspond to hir field"),
159            };
160            tcx.dcx().emit_err(errors::InvalidUnionField {
161                field_span,
162                sugg: errors::InvalidUnionFieldSuggestion {
163                    lo: ty_span.shrink_to_lo(),
164                    hi: ty_span.shrink_to_hi(),
165                },
166                note: (),
167            });
168            return false;
169        }
170    }
171
172    true
173}
174
175/// Check that a `static` is inhabited.
176fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
177    // Make sure statics are inhabited.
178    // Other parts of the compiler assume that there are no uninhabited places. In principle it
179    // would be enough to check this for `extern` statics, as statics with an initializer will
180    // have UB during initialization if they are uninhabited, but there also seems to be no good
181    // reason to allow any statics to be uninhabited.
182    let ty = tcx.type_of(def_id).instantiate_identity();
183    let span = tcx.def_span(def_id);
184    let layout = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
185        Ok(l) => l,
186        // Foreign statics that overflow their allowed size should emit an error
187        Err(LayoutError::SizeOverflow(_))
188            if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
    DefKind::Static { .. } if
        tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod => true,
    _ => false,
}matches!(tcx.def_kind(def_id), DefKind::Static{ .. }
189                if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) =>
190        {
191            tcx.dcx().emit_err(errors::TooLargeStatic { span });
192            return;
193        }
194        // SIMD types with invalid layout (e.g., zero-length) should emit an error
195        Err(e @ LayoutError::InvalidSimd { .. }) => {
196            let ty_span = tcx.ty_span(def_id);
197            tcx.dcx().emit_err(Spanned { span: ty_span, node: e.into_diagnostic() });
198            return;
199        }
200        // Generic statics are rejected, but we still reach this case.
201        Err(e) => {
202            tcx.dcx().span_delayed_bug(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", e))
    })format!("{e:?}"));
203            return;
204        }
205    };
206    if layout.is_uninhabited() {
207        tcx.node_span_lint(
208            UNINHABITED_STATIC,
209            tcx.local_def_id_to_hir_id(def_id),
210            span,
211            |lint| {
212                lint.primary_message("static of uninhabited type");
213                lint
214                .note("uninhabited statics cannot be initialized, and any access would be an immediate error");
215            },
216        );
217    }
218}
219
220/// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
221/// projections that would result in "inheriting lifetimes".
222fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
223    let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);
224
225    // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
226    // `async-std` (and `pub async fn` in general).
227    // Since rustdoc doesn't care about the hidden type behind `impl Trait`, just don't look at it!
228    // See https://github.com/rust-lang/rust/issues/75100
229    if tcx.sess.opts.actually_rustdoc {
230        return;
231    }
232
233    if tcx.type_of(def_id).instantiate_identity().references_error() {
234        return;
235    }
236    if check_opaque_for_cycles(tcx, def_id).is_err() {
237        return;
238    }
239
240    let _ = check_opaque_meets_bounds(tcx, def_id, origin);
241}
242
243/// Checks that an opaque type does not contain cycles.
244pub(super) fn check_opaque_for_cycles<'tcx>(
245    tcx: TyCtxt<'tcx>,
246    def_id: LocalDefId,
247) -> Result<(), ErrorGuaranteed> {
248    let args = GenericArgs::identity_for_item(tcx, def_id);
249
250    // First, try to look at any opaque expansion cycles, considering coroutine fields
251    // (even though these aren't necessarily true errors).
252    if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() {
253        let reported = opaque_type_cycle_error(tcx, def_id);
254        return Err(reported);
255    }
256
257    Ok(())
258}
259
260/// Check that the hidden type behind `impl Trait` actually implements `Trait`.
261///
262/// This is mostly checked at the places that specify the opaque type, but we
263/// check those cases in the `param_env` of that function, which may have
264/// bounds not on this opaque type:
265///
266/// ```ignore (illustrative)
267/// type X<T> = impl Clone;
268/// fn f<T: Clone>(t: T) -> X<T> {
269///     t
270/// }
271/// ```
272///
273/// Without this check the above code is incorrectly accepted: we would ICE if
274/// some tried, for example, to clone an `Option<X<&mut ()>>`.
275#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_opaque_meets_bounds",
                                    "rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/check.rs"),
                                    ::tracing_core::__macro_support::Option::Some(275u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                                    ::tracing_core::field::FieldSet::new(&["def_id", "origin"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (span, definition_def_id) =
                if let Some((span, def_id)) =
                        best_definition_site_of_opaque(tcx, def_id, origin) {
                    (span, Some(def_id))
                } else { (tcx.def_span(def_id), None) };
            let defining_use_anchor =
                match origin {
                    hir::OpaqueTyOrigin::FnReturn { parent, .. } |
                        hir::OpaqueTyOrigin::AsyncFn { parent, .. } |
                        hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
                };
            let param_env = tcx.param_env(defining_use_anchor);
            let infcx =
                tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
                        TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
                    } else {
                        TypingMode::analysis_in_body(tcx, defining_use_anchor)
                    });
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            let args =
                match origin {
                    hir::OpaqueTyOrigin::FnReturn { parent, .. } |
                        hir::OpaqueTyOrigin::AsyncFn { parent, .. } |
                        hir::OpaqueTyOrigin::TyAlias { parent, .. } =>
                        GenericArgs::identity_for_item(tcx,
                                parent).extend_to(tcx, def_id.to_def_id(),
                            |param, _|
                                {
                                    tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
                                }),
                };
            let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
            let hidden_ty =
                tcx.type_of(def_id.to_def_id()).instantiate(tcx, args);
            let hidden_ty =
                fold_regions(tcx, hidden_ty,
                    |re, _dbi|
                        match re.kind() {
                            ty::ReErased =>
                                infcx.next_region_var(RegionVariableOrigin::Misc(span)),
                            _ => re,
                        });
            for (predicate, pred_span) in
                tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx,
                    args) {
                let predicate =
                    predicate.fold_with(&mut BottomUpFolder {
                                tcx,
                                ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
                                lt_op: |lt| lt,
                                ct_op: |ct| ct,
                            });
                ocx.register_obligation(Obligation::new(tcx,
                        ObligationCause::new(span, def_id,
                            ObligationCauseCode::OpaqueTypeBound(pred_span,
                                definition_def_id)), param_env, predicate));
            }
            let misc_cause = ObligationCause::misc(span, def_id);
            match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
                Ok(()) => {}
                Err(ty_err) => {
                    let ty_err = ty_err.to_string(tcx);
                    let guar =
                        tcx.dcx().span_delayed_bug(span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("could not unify `{0}` with revealed type:\n{1}",
                                            hidden_ty, ty_err))
                                }));
                    return Err(guar);
                }
            }
            let predicate =
                ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
            ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(),
                    param_env, predicate));
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if !errors.is_empty() {
                let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
                return Err(guar);
            }
            let wf_tys =
                ocx.assumed_wf_types_and_report_errors(param_env,
                        defining_use_anchor)?;
            ocx.resolve_regions_and_report_errors(defining_use_anchor,
                    param_env, wf_tys)?;
            if infcx.next_trait_solver() {
                Ok(())
            } else if let hir::OpaqueTyOrigin::FnReturn { .. } |
                    hir::OpaqueTyOrigin::AsyncFn { .. } = origin {
                let _ = infcx.take_opaque_types();
                Ok(())
            } else {
                for (mut key, mut ty) in infcx.take_opaque_types() {
                    ty.ty = infcx.resolve_vars_if_possible(ty.ty);
                    key = infcx.resolve_vars_if_possible(key);
                    sanity_check_found_hidden_type(tcx, key, ty)?;
                }
                Ok(())
            }
        }
    }
}#[instrument(level = "debug", skip(tcx))]
276fn check_opaque_meets_bounds<'tcx>(
277    tcx: TyCtxt<'tcx>,
278    def_id: LocalDefId,
279    origin: hir::OpaqueTyOrigin<LocalDefId>,
280) -> Result<(), ErrorGuaranteed> {
281    let (span, definition_def_id) =
282        if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {
283            (span, Some(def_id))
284        } else {
285            (tcx.def_span(def_id), None)
286        };
287
288    let defining_use_anchor = match origin {
289        hir::OpaqueTyOrigin::FnReturn { parent, .. }
290        | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
291        | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
292    };
293    let param_env = tcx.param_env(defining_use_anchor);
294
295    // FIXME(#132279): Once `PostBorrowckAnalysis` is supported in the old solver, this branch should be removed.
296    let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
297        TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
298    } else {
299        TypingMode::analysis_in_body(tcx, defining_use_anchor)
300    });
301    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
302
303    let args = match origin {
304        hir::OpaqueTyOrigin::FnReturn { parent, .. }
305        | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
306        | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(
307            tcx, parent,
308        )
309        .extend_to(tcx, def_id.to_def_id(), |param, _| {
310            tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
311        }),
312    };
313
314    let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
315
316    // `ReErased` regions appear in the "parent_args" of closures/coroutines.
317    // We're ignoring them here and replacing them with fresh region variables.
318    // See tests in ui/type-alias-impl-trait/closure_{parent_args,wf_outlives}.rs.
319    //
320    // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it
321    // here rather than using ReErased.
322    let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args);
323    let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {
324        ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)),
325        _ => re,
326    });
327
328    // HACK: We eagerly instantiate some bounds to report better errors for them...
329    // This isn't necessary for correctness, since we register these bounds when
330    // equating the opaque below, but we should clean this up in the new solver.
331    for (predicate, pred_span) in
332        tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx, args)
333    {
334        let predicate = predicate.fold_with(&mut BottomUpFolder {
335            tcx,
336            ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
337            lt_op: |lt| lt,
338            ct_op: |ct| ct,
339        });
340
341        ocx.register_obligation(Obligation::new(
342            tcx,
343            ObligationCause::new(
344                span,
345                def_id,
346                ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
347            ),
348            param_env,
349            predicate,
350        ));
351    }
352
353    let misc_cause = ObligationCause::misc(span, def_id);
354    // FIXME: We should just register the item bounds here, rather than equating.
355    // FIXME(const_trait_impl): When we do that, please make sure to also register
356    // the `[const]` bounds.
357    match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
358        Ok(()) => {}
359        Err(ty_err) => {
360            // Some types may be left "stranded" if they can't be reached
361            // from a lowered rustc_middle bound but they're mentioned in the HIR.
362            // This will happen, e.g., when a nested opaque is inside of a non-
363            // existent associated type, like `impl Trait<Missing = impl Trait>`.
364            // See <tests/ui/impl-trait/stranded-opaque.rs>.
365            let ty_err = ty_err.to_string(tcx);
366            let guar = tcx.dcx().span_delayed_bug(
367                span,
368                format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
369            );
370            return Err(guar);
371        }
372    }
373
374    // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
375    // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
376    // hidden type is well formed even without those bounds.
377    let predicate =
378        ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
379    ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
380
381    // Check that all obligations are satisfied by the implementation's
382    // version.
383    let errors = ocx.evaluate_obligations_error_on_ambiguity();
384    if !errors.is_empty() {
385        let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
386        return Err(guar);
387    }
388
389    let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
390    ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
391
392    if infcx.next_trait_solver() {
393        Ok(())
394    } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
395        origin
396    {
397        // HACK: this should also fall through to the hidden type check below, but the original
398        // implementation had a bug where equivalent lifetimes are not identical. This caused us
399        // to reject existing stable code that is otherwise completely fine. The real fix is to
400        // compare the hidden types via our type equivalence/relation infra instead of doing an
401        // identity check.
402        let _ = infcx.take_opaque_types();
403        Ok(())
404    } else {
405        // Check that any hidden types found during wf checking match the hidden types that `type_of` sees.
406        for (mut key, mut ty) in infcx.take_opaque_types() {
407            ty.ty = infcx.resolve_vars_if_possible(ty.ty);
408            key = infcx.resolve_vars_if_possible(key);
409            sanity_check_found_hidden_type(tcx, key, ty)?;
410        }
411        Ok(())
412    }
413}
414
415fn best_definition_site_of_opaque<'tcx>(
416    tcx: TyCtxt<'tcx>,
417    opaque_def_id: LocalDefId,
418    origin: hir::OpaqueTyOrigin<LocalDefId>,
419) -> Option<(Span, LocalDefId)> {
420    struct TaitConstraintLocator<'tcx> {
421        opaque_def_id: LocalDefId,
422        tcx: TyCtxt<'tcx>,
423    }
424    impl<'tcx> TaitConstraintLocator<'tcx> {
425        fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
426            if !self.tcx.has_typeck_results(item_def_id) {
427                return ControlFlow::Continue(());
428            }
429
430            let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
431            // Don't try to check items that cannot possibly constrain the type.
432            if !opaque_types_defined_by.contains(&self.opaque_def_id) {
433                return ControlFlow::Continue(());
434            }
435
436            if let Some(hidden_ty) = self
437                .tcx
438                .mir_borrowck(item_def_id)
439                .ok()
440                .and_then(|opaque_types| opaque_types.get(&self.opaque_def_id))
441            {
442                ControlFlow::Break((hidden_ty.span, item_def_id))
443            } else {
444                ControlFlow::Continue(())
445            }
446        }
447    }
448    impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
449        type NestedFilter = nested_filter::All;
450        type Result = ControlFlow<(Span, LocalDefId)>;
451        fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
452            self.tcx
453        }
454        fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
455            intravisit::walk_expr(self, ex)
456        }
457        fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
458            self.check(it.owner_id.def_id)?;
459            intravisit::walk_item(self, it)
460        }
461        fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
462            self.check(it.owner_id.def_id)?;
463            intravisit::walk_impl_item(self, it)
464        }
465        fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
466            self.check(it.owner_id.def_id)?;
467            intravisit::walk_trait_item(self, it)
468        }
469        fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
470            intravisit::walk_foreign_item(self, it)
471        }
472    }
473
474    let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
475    match origin {
476        hir::OpaqueTyOrigin::FnReturn { parent, .. }
477        | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
478        hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
479            let impl_def_id = tcx.local_parent(parent);
480            for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
481                match assoc.kind {
482                    ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
483                        if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
484                        {
485                            return Some(span);
486                        }
487                    }
488                    ty::AssocKind::Type { .. } => {}
489                }
490            }
491
492            None
493        }
494        hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
495            tcx.hir_walk_toplevel_module(&mut locator).break_value()
496        }
497    }
498}
499
500fn sanity_check_found_hidden_type<'tcx>(
501    tcx: TyCtxt<'tcx>,
502    key: ty::OpaqueTypeKey<'tcx>,
503    mut ty: ty::ProvisionalHiddenType<'tcx>,
504) -> Result<(), ErrorGuaranteed> {
505    if ty.ty.is_ty_var() {
506        // Nothing was actually constrained.
507        return Ok(());
508    }
509    if let ty::Alias(ty::Opaque, alias) = ty.ty.kind() {
510        if alias.def_id == key.def_id.to_def_id() && alias.args == key.args {
511            // Nothing was actually constrained, this is an opaque usage that was
512            // only discovered to be opaque after inference vars resolved.
513            return Ok(());
514        }
515    }
516    let erase_re_vars = |ty: Ty<'tcx>| {
517        fold_regions(tcx, ty, |r, _| match r.kind() {
518            RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
519            _ => r,
520        })
521    };
522    // Closures frequently end up containing erased lifetimes in their final representation.
523    // These correspond to lifetime variables that never got resolved, so we patch this up here.
524    ty.ty = erase_re_vars(ty.ty);
525    // Get the hidden type.
526    let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args);
527    let hidden_ty = erase_re_vars(hidden_ty);
528
529    // If the hidden types differ, emit a type mismatch diagnostic.
530    if hidden_ty == ty.ty {
531        Ok(())
532    } else {
533        let span = tcx.def_span(key.def_id);
534        let other = ty::ProvisionalHiddenType { ty: hidden_ty, span };
535        Err(ty.build_mismatch_error(&other, tcx)?.emit())
536    }
537}
538
539/// Check that the opaque's precise captures list is valid (if present).
540/// We check this for regular `impl Trait`s and also RPITITs, even though the latter
541/// are technically GATs.
542///
543/// This function is responsible for:
544/// 1. Checking that all type/const params are mention in the captures list.
545/// 2. Checking that all lifetimes that are implicitly captured are mentioned.
546/// 3. Asserting that all parameters mentioned in the captures list are invariant.
547fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
548    let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
549    let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
550        hir::GenericBound::Use(bounds, ..) => Some(bounds),
551        _ => None,
552    }) else {
553        // No precise capturing args; nothing to validate
554        return;
555    };
556
557    let mut expected_captures = UnordSet::default();
558    let mut shadowed_captures = UnordSet::default();
559    let mut seen_params = UnordMap::default();
560    let mut prev_non_lifetime_param = None;
561    for arg in precise_capturing_args {
562        let (hir_id, ident) = match *arg {
563            hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
564                hir_id,
565                ident,
566                ..
567            }) => {
568                if prev_non_lifetime_param.is_none() {
569                    prev_non_lifetime_param = Some(ident);
570                }
571                (hir_id, ident)
572            }
573            hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
574                if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
575                    tcx.dcx().emit_err(errors::LifetimesMustBeFirst {
576                        lifetime_span: ident.span,
577                        name: ident.name,
578                        other_span: prev_non_lifetime_param.span,
579                    });
580                }
581                (hir_id, ident)
582            }
583        };
584
585        let ident = ident.normalize_to_macros_2_0();
586        if let Some(span) = seen_params.insert(ident, ident.span) {
587            tcx.dcx().emit_err(errors::DuplicatePreciseCapture {
588                name: ident.name,
589                first_span: span,
590                second_span: ident.span,
591            });
592        }
593
594        match tcx.named_bound_var(hir_id) {
595            Some(ResolvedArg::EarlyBound(def_id)) => {
596                expected_captures.insert(def_id.to_def_id());
597
598                // Make sure we allow capturing these lifetimes through `Self` and
599                // `T::Assoc` projection syntax, too. These will occur when we only
600                // see lifetimes are captured after hir-lowering -- this aligns with
601                // the cases that were stabilized with the `impl_trait_projection`
602                // feature -- see <https://github.com/rust-lang/rust/pull/115659>.
603                if let DefKind::LifetimeParam = tcx.def_kind(def_id)
604                    && let Some(def_id) = tcx
605                        .map_opaque_lifetime_to_parent_lifetime(def_id)
606                        .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
607                {
608                    shadowed_captures.insert(def_id);
609                }
610            }
611            _ => {
612                tcx.dcx()
613                    .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
614            }
615        }
616    }
617
618    let variances = tcx.variances_of(opaque_def_id);
619    let mut def_id = Some(opaque_def_id.to_def_id());
620    while let Some(generics) = def_id {
621        let generics = tcx.generics_of(generics);
622        def_id = generics.parent;
623
624        for param in &generics.own_params {
625            if expected_captures.contains(&param.def_id) {
626                match (&variances[param.index as usize], &ty::Invariant) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("precise captured param should be invariant")));
        }
    }
};assert_eq!(
627                    variances[param.index as usize],
628                    ty::Invariant,
629                    "precise captured param should be invariant"
630                );
631                continue;
632            }
633            // If a param is shadowed by a early-bound (duplicated) lifetime, then
634            // it may or may not be captured as invariant, depending on if it shows
635            // up through `Self` or `T::Assoc` syntax.
636            if shadowed_captures.contains(&param.def_id) {
637                continue;
638            }
639
640            match param.kind {
641                ty::GenericParamDefKind::Lifetime => {
642                    let use_span = tcx.def_span(param.def_id);
643                    let opaque_span = tcx.def_span(opaque_def_id);
644                    // Check if the lifetime param was captured but isn't named in the precise captures list.
645                    if variances[param.index as usize] == ty::Invariant {
646                        if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
647                            && let Some(def_id) = tcx
648                                .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
649                                .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
650                        {
651                            tcx.dcx().emit_err(errors::LifetimeNotCaptured {
652                                opaque_span,
653                                use_span,
654                                param_span: tcx.def_span(def_id),
655                            });
656                        } else {
657                            if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
658                                tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured {
659                                    opaque_span,
660                                    param_span: tcx.def_span(param.def_id),
661                                });
662                            } else {
663                                // If the `use_span` is actually just the param itself, then we must
664                                // have not duplicated the lifetime but captured the original.
665                                // The "effective" `use_span` will be the span of the opaque itself,
666                                // and the param span will be the def span of the param.
667                                tcx.dcx().emit_err(errors::LifetimeNotCaptured {
668                                    opaque_span,
669                                    use_span: opaque_span,
670                                    param_span: use_span,
671                                });
672                            }
673                        }
674                        continue;
675                    }
676                }
677                ty::GenericParamDefKind::Type { .. } => {
678                    if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(param.def_id) {
    DefKind::Trait | DefKind::TraitAlias => true,
    _ => false,
}matches!(tcx.def_kind(param.def_id), DefKind::Trait | DefKind::TraitAlias) {
679                        // FIXME(precise_capturing): Structured suggestion for this would be useful
680                        tcx.dcx().emit_err(errors::SelfTyNotCaptured {
681                            trait_span: tcx.def_span(param.def_id),
682                            opaque_span: tcx.def_span(opaque_def_id),
683                        });
684                    } else {
685                        // FIXME(precise_capturing): Structured suggestion for this would be useful
686                        tcx.dcx().emit_err(errors::ParamNotCaptured {
687                            param_span: tcx.def_span(param.def_id),
688                            opaque_span: tcx.def_span(opaque_def_id),
689                            kind: "type",
690                        });
691                    }
692                }
693                ty::GenericParamDefKind::Const { .. } => {
694                    // FIXME(precise_capturing): Structured suggestion for this would be useful
695                    tcx.dcx().emit_err(errors::ParamNotCaptured {
696                        param_span: tcx.def_span(param.def_id),
697                        opaque_span: tcx.def_span(opaque_def_id),
698                        kind: "const",
699                    });
700                }
701            }
702        }
703    }
704}
705
706fn is_enum_of_nonnullable_ptr<'tcx>(
707    tcx: TyCtxt<'tcx>,
708    adt_def: AdtDef<'tcx>,
709    args: GenericArgsRef<'tcx>,
710) -> bool {
711    if adt_def.repr().inhibit_enum_layout_opt() {
712        return false;
713    }
714
715    let [var_one, var_two] = &adt_def.variants().raw[..] else {
716        return false;
717    };
718    let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
719        return false;
720    };
721    #[allow(non_exhaustive_omitted_patterns)] match field.ty(tcx, args).kind() {
    ty::FnPtr(..) | ty::Ref(..) => true,
    _ => false,
}matches!(field.ty(tcx, args).kind(), ty::FnPtr(..) | ty::Ref(..))
722}
723
724fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
725    if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
726        if match tcx.type_of(def_id).instantiate_identity().kind() {
727            ty::RawPtr(_, _) => false,
728            ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
729            _ => true,
730        } {
731            tcx.dcx().emit_err(errors::LinkageType { span: tcx.def_span(def_id) });
732        }
733    }
734}
735
736pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
737    let mut res = Ok(());
738    let generics = tcx.generics_of(def_id);
739
740    for param in &generics.own_params {
741        match param.kind {
742            ty::GenericParamDefKind::Lifetime { .. } => {}
743            ty::GenericParamDefKind::Type { has_default, .. } => {
744                if has_default {
745                    tcx.ensure_ok().type_of(param.def_id);
746                }
747            }
748            ty::GenericParamDefKind::Const { has_default, .. } => {
749                tcx.ensure_ok().type_of(param.def_id);
750                if has_default {
751                    // need to store default and type of default
752                    let ct = tcx.const_param_default(param.def_id).skip_binder();
753                    if let ty::ConstKind::Unevaluated(uv) = ct.kind() {
754                        tcx.ensure_ok().type_of(uv.def);
755                    }
756                }
757            }
758        }
759    }
760
761    match tcx.def_kind(def_id) {
762        DefKind::Static { .. } => {
763            tcx.ensure_ok().generics_of(def_id);
764            tcx.ensure_ok().type_of(def_id);
765            tcx.ensure_ok().predicates_of(def_id);
766
767            check_static_inhabited(tcx, def_id);
768            check_static_linkage(tcx, def_id);
769            let ty = tcx.type_of(def_id).instantiate_identity();
770            res = res.and(wfcheck::check_static_item(
771                tcx, def_id, ty, /* should_check_for_sync */ true,
772            ));
773
774            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
775            // checks. Returning early here does not miss any checks and
776            // avoids this query from having a direct dependency edge on the HIR
777            return res;
778        }
779        DefKind::Enum => {
780            tcx.ensure_ok().generics_of(def_id);
781            tcx.ensure_ok().type_of(def_id);
782            tcx.ensure_ok().predicates_of(def_id);
783            crate::collect::lower_enum_variant_types(tcx, def_id);
784            check_enum(tcx, def_id);
785            check_variances_for_type_defn(tcx, def_id);
786        }
787        DefKind::Fn => {
788            tcx.ensure_ok().generics_of(def_id);
789            tcx.ensure_ok().type_of(def_id);
790            tcx.ensure_ok().predicates_of(def_id);
791            tcx.ensure_ok().fn_sig(def_id);
792            tcx.ensure_ok().codegen_fn_attrs(def_id);
793            if let Some(i) = tcx.intrinsic(def_id) {
794                intrinsic::check_intrinsic_type(
795                    tcx,
796                    def_id,
797                    tcx.def_ident_span(def_id).unwrap(),
798                    i.name,
799                )
800            }
801        }
802        DefKind::Impl { of_trait } => {
803            tcx.ensure_ok().generics_of(def_id);
804            tcx.ensure_ok().type_of(def_id);
805            tcx.ensure_ok().predicates_of(def_id);
806            tcx.ensure_ok().associated_items(def_id);
807            if of_trait {
808                let impl_trait_header = tcx.impl_trait_header(def_id);
809                res = res.and(
810                    tcx.ensure_ok()
811                        .coherent_trait(impl_trait_header.trait_ref.instantiate_identity().def_id),
812                );
813
814                if res.is_ok() {
815                    // Checking this only makes sense if the all trait impls satisfy basic
816                    // requirements (see `coherent_trait` query), otherwise
817                    // we run into infinite recursions a lot.
818                    check_impl_items_against_trait(tcx, def_id, impl_trait_header);
819                }
820            }
821        }
822        DefKind::Trait => {
823            tcx.ensure_ok().generics_of(def_id);
824            tcx.ensure_ok().trait_def(def_id);
825            tcx.ensure_ok().explicit_super_predicates_of(def_id);
826            tcx.ensure_ok().predicates_of(def_id);
827            tcx.ensure_ok().associated_items(def_id);
828            let assoc_items = tcx.associated_items(def_id);
829
830            for &assoc_item in assoc_items.in_definition_order() {
831                match assoc_item.kind {
832                    ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {
833                        let trait_args = GenericArgs::identity_for_item(tcx, def_id);
834                        let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
835                            tcx,
836                            assoc_item,
837                            assoc_item,
838                            ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),
839                        );
840                    }
841                    _ => {}
842                }
843            }
844        }
845        DefKind::TraitAlias => {
846            tcx.ensure_ok().generics_of(def_id);
847            tcx.ensure_ok().explicit_implied_predicates_of(def_id);
848            tcx.ensure_ok().explicit_super_predicates_of(def_id);
849            tcx.ensure_ok().predicates_of(def_id);
850        }
851        def_kind @ (DefKind::Struct | DefKind::Union) => {
852            tcx.ensure_ok().generics_of(def_id);
853            tcx.ensure_ok().type_of(def_id);
854            tcx.ensure_ok().predicates_of(def_id);
855
856            let adt = tcx.adt_def(def_id).non_enum_variant();
857            for f in adt.fields.iter() {
858                tcx.ensure_ok().generics_of(f.did);
859                tcx.ensure_ok().type_of(f.did);
860                tcx.ensure_ok().predicates_of(f.did);
861            }
862
863            if let Some((_, ctor_def_id)) = adt.ctor {
864                crate::collect::lower_variant_ctor(tcx, ctor_def_id.expect_local());
865            }
866            match def_kind {
867                DefKind::Struct => check_struct(tcx, def_id),
868                DefKind::Union => check_union(tcx, def_id),
869                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
870            }
871            check_variances_for_type_defn(tcx, def_id);
872        }
873        DefKind::OpaqueTy => {
874            check_opaque_precise_captures(tcx, def_id);
875
876            let origin = tcx.local_opaque_ty_origin(def_id);
877            if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
878            | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin
879                && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
880                && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
881            {
882                // Skip opaques from RPIT in traits with no default body.
883            } else {
884                check_opaque(tcx, def_id);
885            }
886
887            tcx.ensure_ok().predicates_of(def_id);
888            tcx.ensure_ok().explicit_item_bounds(def_id);
889            tcx.ensure_ok().explicit_item_self_bounds(def_id);
890            if tcx.is_conditionally_const(def_id) {
891                tcx.ensure_ok().explicit_implied_const_bounds(def_id);
892                tcx.ensure_ok().const_conditions(def_id);
893            }
894
895            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
896            // checks. Returning early here does not miss any checks and
897            // avoids this query from having a direct dependency edge on the HIR
898            return res;
899        }
900        DefKind::Const => {
901            tcx.ensure_ok().generics_of(def_id);
902            tcx.ensure_ok().type_of(def_id);
903            tcx.ensure_ok().predicates_of(def_id);
904
905            res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
906                let ty = tcx.type_of(def_id).instantiate_identity();
907                let ty_span = tcx.ty_span(def_id);
908                let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
909                wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
910                wfcx.register_bound(
911                    traits::ObligationCause::new(
912                        ty_span,
913                        def_id,
914                        ObligationCauseCode::SizedConstOrStatic,
915                    ),
916                    tcx.param_env(def_id),
917                    ty,
918                    tcx.require_lang_item(LangItem::Sized, ty_span),
919                );
920                check_where_clauses(wfcx, def_id);
921
922                if tcx.is_type_const(def_id) {
923                    wfcheck::check_type_const(wfcx, def_id, ty, true)?;
924                }
925                Ok(())
926            }));
927
928            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
929            // checks. Returning early here does not miss any checks and
930            // avoids this query from having a direct dependency edge on the HIR
931            return res;
932        }
933        DefKind::TyAlias => {
934            tcx.ensure_ok().generics_of(def_id);
935            tcx.ensure_ok().type_of(def_id);
936            tcx.ensure_ok().predicates_of(def_id);
937            check_type_alias_type_params_are_used(tcx, def_id);
938            if tcx.type_alias_is_lazy(def_id) {
939                res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
940                    let ty = tcx.type_of(def_id).instantiate_identity();
941                    let span = tcx.def_span(def_id);
942                    let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
943                    wfcx.register_wf_obligation(
944                        span,
945                        Some(WellFormedLoc::Ty(def_id)),
946                        item_ty.into(),
947                    );
948                    check_where_clauses(wfcx, def_id);
949                    Ok(())
950                }));
951                check_variances_for_type_defn(tcx, def_id);
952            }
953
954            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
955            // checks. Returning early here does not miss any checks and
956            // avoids this query from having a direct dependency edge on the HIR
957            return res;
958        }
959        DefKind::ForeignMod => {
960            let it = tcx.hir_expect_item(def_id);
961            let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
962                return Ok(());
963            };
964
965            check_abi(tcx, it.hir_id(), it.span, abi);
966
967            for &item in items {
968                let def_id = item.owner_id.def_id;
969
970                let generics = tcx.generics_of(def_id);
971                let own_counts = generics.own_counts();
972                if generics.own_params.len() - own_counts.lifetimes != 0 {
973                    let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
974                        (_, 0) => ("type", "types", Some("u32")),
975                        // We don't specify an example value, because we can't generate
976                        // a valid value for any type.
977                        (0, _) => ("const", "consts", None),
978                        _ => ("type or const", "types or consts", None),
979                    };
980                    let name = if {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in tcx.get_all_attrs(def_id) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(RustcEiiForeignItem) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcEiiForeignItem) {
981                        "externally implementable items"
982                    } else {
983                        "foreign items"
984                    };
985
986                    let span = tcx.def_span(def_id);
987                    {
    tcx.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} may not have {1} parameters",
                            name, kinds))
                })).with_code(E0044)
}struct_span_code_err!(
988                        tcx.dcx(),
989                        span,
990                        E0044,
991                        "{name} may not have {kinds} parameters",
992                    )
993                    .with_span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("can\'t have {0} parameters",
                kinds))
    })format!("can't have {kinds} parameters"))
994                    .with_help(
995                        // FIXME: once we start storing spans for type arguments, turn this
996                        // into a suggestion.
997                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("replace the {0} parameters with concrete {1}{2}",
                kinds, kinds_pl,
                egs.map(|egs|
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!(" like `{0}`", egs))
                                })).unwrap_or_default()))
    })format!(
998                            "replace the {} parameters with concrete {}{}",
999                            kinds,
1000                            kinds_pl,
1001                            egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
1002                        ),
1003                    )
1004                    .emit();
1005                }
1006
1007                tcx.ensure_ok().generics_of(def_id);
1008                tcx.ensure_ok().type_of(def_id);
1009                tcx.ensure_ok().predicates_of(def_id);
1010                if tcx.is_conditionally_const(def_id) {
1011                    tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1012                    tcx.ensure_ok().const_conditions(def_id);
1013                }
1014                match tcx.def_kind(def_id) {
1015                    DefKind::Fn => {
1016                        tcx.ensure_ok().codegen_fn_attrs(def_id);
1017                        tcx.ensure_ok().fn_sig(def_id);
1018                        let item = tcx.hir_foreign_item(item);
1019                        let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
1020                        check_c_variadic_abi(tcx, sig.decl, abi, item.span);
1021                    }
1022                    DefKind::Static { .. } => {
1023                        tcx.ensure_ok().codegen_fn_attrs(def_id);
1024                    }
1025                    _ => (),
1026                }
1027            }
1028        }
1029        DefKind::Closure => {
1030            // This is guaranteed to be called by metadata encoding,
1031            // we still call it in wfcheck eagerly to ensure errors in codegen
1032            // attrs prevent lints from spamming the output.
1033            tcx.ensure_ok().codegen_fn_attrs(def_id);
1034            // We do not call `type_of` for closures here as that
1035            // depends on typecheck and would therefore hide
1036            // any further errors in case one typeck fails.
1037
1038            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1039            // checks. Returning early here does not miss any checks and
1040            // avoids this query from having a direct dependency edge on the HIR
1041            return res;
1042        }
1043        DefKind::AssocFn => {
1044            tcx.ensure_ok().codegen_fn_attrs(def_id);
1045            tcx.ensure_ok().type_of(def_id);
1046            tcx.ensure_ok().fn_sig(def_id);
1047            tcx.ensure_ok().predicates_of(def_id);
1048            res = res.and(check_associated_item(tcx, def_id));
1049            let assoc_item = tcx.associated_item(def_id);
1050            match assoc_item.container {
1051                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1052                ty::AssocContainer::Trait => {
1053                    res = res.and(check_trait_item(tcx, def_id));
1054                }
1055            }
1056
1057            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1058            // checks. Returning early here does not miss any checks and
1059            // avoids this query from having a direct dependency edge on the HIR
1060            return res;
1061        }
1062        DefKind::AssocConst => {
1063            tcx.ensure_ok().type_of(def_id);
1064            tcx.ensure_ok().predicates_of(def_id);
1065            res = res.and(check_associated_item(tcx, def_id));
1066            let assoc_item = tcx.associated_item(def_id);
1067            match assoc_item.container {
1068                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1069                ty::AssocContainer::Trait => {
1070                    res = res.and(check_trait_item(tcx, def_id));
1071                }
1072            }
1073
1074            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1075            // checks. Returning early here does not miss any checks and
1076            // avoids this query from having a direct dependency edge on the HIR
1077            return res;
1078        }
1079        DefKind::AssocTy => {
1080            tcx.ensure_ok().predicates_of(def_id);
1081            res = res.and(check_associated_item(tcx, def_id));
1082
1083            let assoc_item = tcx.associated_item(def_id);
1084            let has_type = match assoc_item.container {
1085                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1086                ty::AssocContainer::Trait => {
1087                    tcx.ensure_ok().explicit_item_bounds(def_id);
1088                    tcx.ensure_ok().explicit_item_self_bounds(def_id);
1089                    if tcx.is_conditionally_const(def_id) {
1090                        tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1091                        tcx.ensure_ok().const_conditions(def_id);
1092                    }
1093                    res = res.and(check_trait_item(tcx, def_id));
1094                    assoc_item.defaultness(tcx).has_value()
1095                }
1096            };
1097            if has_type {
1098                tcx.ensure_ok().type_of(def_id);
1099            }
1100
1101            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1102            // checks. Returning early here does not miss any checks and
1103            // avoids this query from having a direct dependency edge on the HIR
1104            return res;
1105        }
1106
1107        // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1108        // checks. Returning early here does not miss any checks and
1109        // avoids this query from having a direct dependency edge on the HIR
1110        DefKind::AnonConst | DefKind::InlineConst => return res,
1111        _ => {}
1112    }
1113    let node = tcx.hir_node_by_def_id(def_id);
1114    res.and(match node {
1115        hir::Node::Crate(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("check_well_formed cannot be applied to the crate root"))bug!("check_well_formed cannot be applied to the crate root"),
1116        hir::Node::Item(item) => wfcheck::check_item(tcx, item),
1117        hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),
1118        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{0:?}", node)));
}unreachable!("{node:?}"),
1119    })
1120}
1121
1122pub(super) fn check_specialization_validity<'tcx>(
1123    tcx: TyCtxt<'tcx>,
1124    trait_def: &ty::TraitDef,
1125    trait_item: ty::AssocItem,
1126    impl_id: DefId,
1127    impl_item: DefId,
1128) {
1129    let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
1130    let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
1131        if parent.is_from_trait() {
1132            None
1133        } else {
1134            Some((parent, parent.item(tcx, trait_item.def_id)))
1135        }
1136    });
1137
1138    let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1139        match parent_item {
1140            // Parent impl exists, and contains the parent item we're trying to specialize, but
1141            // doesn't mark it `default`.
1142            Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
1143                Some(Err(parent_impl.def_id()))
1144            }
1145
1146            // Parent impl contains item and makes it specializable.
1147            Some(_) => Some(Ok(())),
1148
1149            // Parent impl doesn't mention the item. This means it's inherited from the
1150            // grandparent. In that case, if parent is a `default impl`, inherited items use the
1151            // "defaultness" from the grandparent, else they are final.
1152            None => {
1153                if tcx.defaultness(parent_impl.def_id()).is_default() {
1154                    None
1155                } else {
1156                    Some(Err(parent_impl.def_id()))
1157                }
1158            }
1159        }
1160    });
1161
1162    // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
1163    // item. This is allowed, the item isn't actually getting specialized here.
1164    let result = opt_result.unwrap_or(Ok(()));
1165
1166    if let Err(parent_impl) = result {
1167        if !tcx.is_impl_trait_in_trait(impl_item) {
1168            let span = tcx.def_span(impl_item);
1169            let ident = tcx.item_ident(impl_item);
1170
1171            let err = match tcx.span_of_impl(parent_impl) {
1172                Ok(sp) => errors::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp },
1173                Err(cname) => errors::ImplNotMarkedDefault::Err { span, ident, cname },
1174            };
1175
1176            tcx.dcx().emit_err(err);
1177        } else {
1178            tcx.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("parent item: {0:?} not marked as default",
                parent_impl))
    })format!("parent item: {parent_impl:?} not marked as default"));
1179        }
1180    }
1181}
1182
1183fn check_overriding_final_trait_item<'tcx>(
1184    tcx: TyCtxt<'tcx>,
1185    trait_item: ty::AssocItem,
1186    impl_item: ty::AssocItem,
1187) {
1188    if trait_item.defaultness(tcx).is_final() {
1189        tcx.dcx().emit_err(errors::OverridingFinalTraitFunction {
1190            impl_span: tcx.def_span(impl_item.def_id),
1191            trait_span: tcx.def_span(trait_item.def_id),
1192            ident: tcx.item_ident(impl_item.def_id),
1193        });
1194    }
1195}
1196
1197fn check_impl_items_against_trait<'tcx>(
1198    tcx: TyCtxt<'tcx>,
1199    impl_id: LocalDefId,
1200    impl_trait_header: ty::ImplTraitHeader<'tcx>,
1201) {
1202    let trait_ref = impl_trait_header.trait_ref.instantiate_identity();
1203    // If the trait reference itself is erroneous (so the compilation is going
1204    // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1205    // isn't populated for such impls.
1206    if trait_ref.references_error() {
1207        return;
1208    }
1209
1210    let impl_item_refs = tcx.associated_item_def_ids(impl_id);
1211
1212    // Negative impls are not expected to have any items
1213    match impl_trait_header.polarity {
1214        ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
1215        ty::ImplPolarity::Negative => {
1216            if let [first_item_ref, ..] = *impl_item_refs {
1217                let first_item_span = tcx.def_span(first_item_ref);
1218                {
    tcx.dcx().struct_span_err(first_item_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("negative impls cannot have any items"))
                })).with_code(E0749)
}struct_span_code_err!(
1219                    tcx.dcx(),
1220                    first_item_span,
1221                    E0749,
1222                    "negative impls cannot have any items"
1223                )
1224                .emit();
1225            }
1226            return;
1227        }
1228    }
1229
1230    let trait_def = tcx.trait_def(trait_ref.def_id);
1231
1232    let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
1233
1234    for &impl_item in impl_item_refs {
1235        let ty_impl_item = tcx.associated_item(impl_item);
1236        let ty_trait_item = match ty_impl_item.expect_trait_impl() {
1237            Ok(trait_item_id) => tcx.associated_item(trait_item_id),
1238            Err(ErrorGuaranteed { .. }) => continue,
1239        };
1240
1241        let res = tcx.ensure_ok().compare_impl_item(impl_item.expect_local());
1242
1243        if res.is_ok() {
1244            match ty_impl_item.kind {
1245                ty::AssocKind::Fn { .. } => {
1246                    compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1247                        tcx,
1248                        ty_impl_item,
1249                        ty_trait_item,
1250                        tcx.impl_trait_ref(ty_impl_item.container_id(tcx)).instantiate_identity(),
1251                    );
1252                }
1253                ty::AssocKind::Const { .. } => {}
1254                ty::AssocKind::Type { .. } => {}
1255            }
1256        }
1257
1258        if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1259            tcx.emit_node_span_lint(
1260                rustc_lint_defs::builtin::DEAD_CODE,
1261                tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1262                tcx.def_span(ty_impl_item.def_id),
1263                errors::UselessImplItem,
1264            )
1265        }
1266
1267        check_specialization_validity(
1268            tcx,
1269            trait_def,
1270            ty_trait_item,
1271            impl_id.to_def_id(),
1272            impl_item,
1273        );
1274
1275        check_overriding_final_trait_item(tcx, ty_trait_item, ty_impl_item);
1276    }
1277
1278    if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1279        // Check for missing items from trait
1280        let mut missing_items = Vec::new();
1281
1282        let mut must_implement_one_of: Option<&[Ident]> =
1283            trait_def.must_implement_one_of.as_deref();
1284
1285        for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1286            let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1287
1288            let is_implemented = leaf_def
1289                .as_ref()
1290                .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1291
1292            if !is_implemented
1293                && tcx.defaultness(impl_id).is_final()
1294                // unsized types don't need to implement methods that have `Self: Sized` bounds.
1295                && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1296            {
1297                missing_items.push(tcx.associated_item(trait_item_id));
1298            }
1299
1300            // true if this item is specifically implemented in this impl
1301            let is_implemented_here =
1302                leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1303
1304            if !is_implemented_here {
1305                let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1306                match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1307                    EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1308                        tcx,
1309                        full_impl_span,
1310                        trait_item_id,
1311                        feature,
1312                        reason,
1313                        issue,
1314                    ),
1315
1316                    // Unmarked default bodies are considered stable (at least for now).
1317                    EvalResult::Allow | EvalResult::Unmarked => {}
1318                }
1319            }
1320
1321            if let Some(required_items) = &must_implement_one_of {
1322                if is_implemented_here {
1323                    let trait_item = tcx.associated_item(trait_item_id);
1324                    if required_items.contains(&trait_item.ident(tcx)) {
1325                        must_implement_one_of = None;
1326                    }
1327                }
1328            }
1329
1330            if let Some(leaf_def) = &leaf_def
1331                && !leaf_def.is_final()
1332                && let def_id = leaf_def.item.def_id
1333                && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1334            {
1335                let def_kind = tcx.def_kind(def_id);
1336                let descr = tcx.def_kind_descr(def_kind, def_id);
1337                let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1338                    (
1339                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("async {0} in trait cannot be specialized",
                descr))
    })format!("async {descr} in trait cannot be specialized"),
1340                        "async functions in traits",
1341                    )
1342                } else {
1343                    (
1344                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} with return-position `impl Trait` in trait cannot be specialized",
                descr))
    })format!(
1345                            "{descr} with return-position `impl Trait` in trait cannot be specialized"
1346                        ),
1347                        "return position `impl Trait` in traits",
1348                    )
1349                };
1350                tcx.dcx()
1351                    .struct_span_err(tcx.def_span(def_id), msg)
1352                    .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("specialization behaves in inconsistent and surprising ways with {0}, and for now is disallowed",
                feature))
    })format!(
1353                        "specialization behaves in inconsistent and surprising ways with \
1354                        {feature}, and for now is disallowed"
1355                    ))
1356                    .emit();
1357            }
1358        }
1359
1360        if !missing_items.is_empty() {
1361            let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1362            missing_items_err(tcx, impl_id, &missing_items, full_impl_span);
1363        }
1364
1365        if let Some(missing_items) = must_implement_one_of {
1366            let attr_span = {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in tcx.get_all_attrs(trait_ref.def_id) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcMustImplementOneOf {
                            attr_span, .. }) => {
                            break 'done Some(*attr_span);
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }
}find_attr!(tcx, trait_ref.def_id, RustcMustImplementOneOf {attr_span, ..} => *attr_span);
1367
1368            missing_items_must_implement_one_of_err(
1369                tcx,
1370                tcx.def_span(impl_id),
1371                missing_items,
1372                attr_span,
1373            );
1374        }
1375    }
1376}
1377
1378fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1379    let t = tcx.type_of(def_id).instantiate_identity();
1380    if let ty::Adt(def, args) = t.kind()
1381        && def.is_struct()
1382    {
1383        let fields = &def.non_enum_variant().fields;
1384        if fields.is_empty() {
1385            {
    tcx.dcx().struct_span_err(sp,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("SIMD vector cannot be empty"))
                })).with_code(E0075)
}struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1386            return;
1387        }
1388
1389        let array_field = &fields[FieldIdx::ZERO];
1390        let array_ty = array_field.ty(tcx, args);
1391        let ty::Array(element_ty, len_const) = array_ty.kind() else {
1392            {
    tcx.dcx().struct_span_err(sp,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("SIMD vector\'s only field must be an array"))
                })).with_code(E0076)
}struct_span_code_err!(
1393                tcx.dcx(),
1394                sp,
1395                E0076,
1396                "SIMD vector's only field must be an array"
1397            )
1398            .with_span_label(tcx.def_span(array_field.did), "not an array")
1399            .emit();
1400            return;
1401        };
1402
1403        if let Some(second_field) = fields.get(FieldIdx::ONE) {
1404            {
    tcx.dcx().struct_span_err(sp,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("SIMD vector cannot have multiple fields"))
                })).with_code(E0075)
}struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot have multiple fields")
1405                .with_span_label(tcx.def_span(second_field.did), "excess field")
1406                .emit();
1407            return;
1408        }
1409
1410        // FIXME(repr_simd): This check is nice, but perhaps unnecessary due to the fact
1411        // we do not expect users to implement their own `repr(simd)` types. If they could,
1412        // this check is easily side-steppable by hiding the const behind normalization.
1413        // The consequence is that the error is, in general, only observable post-mono.
1414        if let Some(len) = len_const.try_to_target_usize(tcx) {
1415            if len == 0 {
1416                {
    tcx.dcx().struct_span_err(sp,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("SIMD vector cannot be empty"))
                })).with_code(E0075)
}struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1417                return;
1418            } else if len > MAX_SIMD_LANES {
1419                {
    tcx.dcx().struct_span_err(sp,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("SIMD vector cannot have more than {0} elements",
                            MAX_SIMD_LANES))
                })).with_code(E0075)
}struct_span_code_err!(
1420                    tcx.dcx(),
1421                    sp,
1422                    E0075,
1423                    "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1424                )
1425                .emit();
1426                return;
1427            }
1428        }
1429
1430        // Check that we use types valid for use in the lanes of a SIMD "vector register"
1431        // These are scalar types which directly match a "machine" type
1432        // Yes: Integers, floats, "thin" pointers
1433        // No: char, "wide" pointers, compound types
1434        match element_ty.kind() {
1435            ty::Param(_) => (), // pass struct<T>([T; 4]) through, let monomorphization catch errors
1436            ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), // struct([u8; 4]) is ok
1437            _ => {
1438                {
    tcx.dcx().struct_span_err(sp,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("SIMD vector element type should be a primitive scalar (integer/float/pointer) type"))
                })).with_code(E0077)
}struct_span_code_err!(
1439                    tcx.dcx(),
1440                    sp,
1441                    E0077,
1442                    "SIMD vector element type should be a \
1443                        primitive scalar (integer/float/pointer) type"
1444                )
1445                .emit();
1446                return;
1447            }
1448        }
1449    }
1450}
1451
1452#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_scalable_vector",
                                    "rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/check.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1452u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                                    ::tracing_core::field::FieldSet::new(&["span", "def_id",
                                                    "scalable"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalable)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty = tcx.type_of(def_id).instantiate_identity();
            let ty::Adt(def, args) = ty.kind() else { return };
            if !def.is_struct() {
                tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");
                return;
            }
            let fields = &def.non_enum_variant().fields;
            match scalable {
                ScalableElt::ElementCount(..) if fields.is_empty() => {
                    let mut err =
                        tcx.dcx().struct_span_err(span,
                            "scalable vectors must have a single field");
                    err.help("scalable vector types' only field must be a primitive scalar type");
                    err.emit();
                    return;
                }
                ScalableElt::ElementCount(..) if fields.len() >= 2 => {
                    tcx.dcx().struct_span_err(span,
                            "scalable vectors cannot have multiple fields").emit();
                    return;
                }
                ScalableElt::Container if fields.is_empty() => {
                    let mut err =
                        tcx.dcx().struct_span_err(span,
                            "scalable vectors must have a single field");
                    err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
                    err.emit();
                    return;
                }
                _ => {}
            }
            match scalable {
                ScalableElt::ElementCount(..) => {
                    let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args);
                    match element_ty.kind() {
                        ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Bool => (),
                        _ => {
                            let mut err =
                                tcx.dcx().struct_span_err(span,
                                    "element type of a scalable vector must be a primitive scalar");
                            err.help("only `u*`, `i*`, `f*` and `bool` types are accepted");
                            err.emit();
                        }
                    }
                }
                ScalableElt::Container => {
                    let mut prev_field_ty = None;
                    for field in fields.iter() {
                        let element_ty = field.ty(tcx, args);
                        if let ty::Adt(def, _) = element_ty.kind() &&
                                def.repr().scalable() {
                            match def.repr().scalable.expect("`repr().scalable.is_some()` != `repr().scalable()`")
                                {
                                ScalableElt::ElementCount(_) => {}
                                ScalableElt::Container => {
                                    tcx.dcx().span_err(tcx.def_span(field.did),
                                        "scalable vector structs cannot contain other scalable vector structs");
                                    break;
                                }
                            }
                        } else {
                            tcx.dcx().span_err(tcx.def_span(field.did),
                                "scalable vector structs can only have scalable vector fields");
                            break;
                        }
                        if let Some(prev_ty) = prev_field_ty.replace(element_ty) &&
                                prev_ty != element_ty {
                            tcx.dcx().span_err(tcx.def_span(field.did),
                                "all fields in a scalable vector struct must be the same type");
                            break;
                        }
                    }
                }
            }
        }
    }
}#[tracing::instrument(skip(tcx), level = "debug")]
1453fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalable: ScalableElt) {
1454    let ty = tcx.type_of(def_id).instantiate_identity();
1455    let ty::Adt(def, args) = ty.kind() else { return };
1456    if !def.is_struct() {
1457        tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");
1458        return;
1459    }
1460
1461    let fields = &def.non_enum_variant().fields;
1462    match scalable {
1463        ScalableElt::ElementCount(..) if fields.is_empty() => {
1464            let mut err =
1465                tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");
1466            err.help("scalable vector types' only field must be a primitive scalar type");
1467            err.emit();
1468            return;
1469        }
1470        ScalableElt::ElementCount(..) if fields.len() >= 2 => {
1471            tcx.dcx().struct_span_err(span, "scalable vectors cannot have multiple fields").emit();
1472            return;
1473        }
1474        ScalableElt::Container if fields.is_empty() => {
1475            let mut err =
1476                tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");
1477            err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1478            err.emit();
1479            return;
1480        }
1481        _ => {}
1482    }
1483
1484    match scalable {
1485        ScalableElt::ElementCount(..) => {
1486            let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args);
1487
1488            // Check that `element_ty` only uses types valid in the lanes of a scalable vector
1489            // register: scalar types which directly match a "machine" type - integers, floats and
1490            // bools
1491            match element_ty.kind() {
1492                ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Bool => (),
1493                _ => {
1494                    let mut err = tcx.dcx().struct_span_err(
1495                        span,
1496                        "element type of a scalable vector must be a primitive scalar",
1497                    );
1498                    err.help("only `u*`, `i*`, `f*` and `bool` types are accepted");
1499                    err.emit();
1500                }
1501            }
1502        }
1503        ScalableElt::Container => {
1504            let mut prev_field_ty = None;
1505            for field in fields.iter() {
1506                let element_ty = field.ty(tcx, args);
1507                if let ty::Adt(def, _) = element_ty.kind()
1508                    && def.repr().scalable()
1509                {
1510                    match def
1511                        .repr()
1512                        .scalable
1513                        .expect("`repr().scalable.is_some()` != `repr().scalable()`")
1514                    {
1515                        ScalableElt::ElementCount(_) => { /* expected field */ }
1516                        ScalableElt::Container => {
1517                            tcx.dcx().span_err(
1518                                tcx.def_span(field.did),
1519                                "scalable vector structs cannot contain other scalable vector structs",
1520                            );
1521                            break;
1522                        }
1523                    }
1524                } else {
1525                    tcx.dcx().span_err(
1526                        tcx.def_span(field.did),
1527                        "scalable vector structs can only have scalable vector fields",
1528                    );
1529                    break;
1530                }
1531
1532                if let Some(prev_ty) = prev_field_ty.replace(element_ty)
1533                    && prev_ty != element_ty
1534                {
1535                    tcx.dcx().span_err(
1536                        tcx.def_span(field.did),
1537                        "all fields in a scalable vector struct must be the same type",
1538                    );
1539                    break;
1540                }
1541            }
1542        }
1543    }
1544}
1545
1546pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1547    let repr = def.repr();
1548    if repr.packed() {
1549        if let Some(reprs) = {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in tcx.get_all_attrs(def.did()) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(Repr { reprs, .. }) => {
                            break 'done Some(reprs);
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }
}find_attr!(tcx, def.did(), Repr { reprs, .. } => reprs) {
1550            for (r, _) in reprs {
1551                if let ReprPacked(pack) = r
1552                    && let Some(repr_pack) = repr.pack
1553                    && pack != &repr_pack
1554                {
1555                    {
    tcx.dcx().struct_span_err(sp,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("type has conflicting packed representation hints"))
                })).with_code(E0634)
}struct_span_code_err!(
1556                        tcx.dcx(),
1557                        sp,
1558                        E0634,
1559                        "type has conflicting packed representation hints"
1560                    )
1561                    .emit();
1562                }
1563            }
1564        }
1565        if repr.align.is_some() {
1566            {
    tcx.dcx().struct_span_err(sp,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("type has conflicting packed and align representation hints"))
                })).with_code(E0587)
}struct_span_code_err!(
1567                tcx.dcx(),
1568                sp,
1569                E0587,
1570                "type has conflicting packed and align representation hints"
1571            )
1572            .emit();
1573        } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut ::alloc::vec::Vec::new()vec![]) {
1574            let mut err = {
    tcx.dcx().struct_span_err(sp,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("packed type cannot transitively contain a `#[repr(align)]` type"))
                })).with_code(E0588)
}struct_span_code_err!(
1575                tcx.dcx(),
1576                sp,
1577                E0588,
1578                "packed type cannot transitively contain a `#[repr(align)]` type"
1579            );
1580
1581            err.span_note(
1582                tcx.def_span(def_spans[0].0),
1583                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` has a `#[repr(align)]` attribute",
                tcx.item_name(def_spans[0].0)))
    })format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),
1584            );
1585
1586            if def_spans.len() > 2 {
1587                let mut first = true;
1588                for (adt_def, span) in def_spans.iter().skip(1).rev() {
1589                    let ident = tcx.item_name(*adt_def);
1590                    err.span_note(
1591                        *span,
1592                        if first {
1593                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` contains a field of type `{1}`",
                tcx.type_of(def.did()).instantiate_identity(), ident))
    })format!(
1594                                "`{}` contains a field of type `{}`",
1595                                tcx.type_of(def.did()).instantiate_identity(),
1596                                ident
1597                            )
1598                        } else {
1599                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("...which contains a field of type `{0}`",
                ident))
    })format!("...which contains a field of type `{ident}`")
1600                        },
1601                    );
1602                    first = false;
1603                }
1604            }
1605
1606            err.emit();
1607        }
1608    }
1609}
1610
1611pub(super) fn check_packed_inner(
1612    tcx: TyCtxt<'_>,
1613    def_id: DefId,
1614    stack: &mut Vec<DefId>,
1615) -> Option<Vec<(DefId, Span)>> {
1616    if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().kind() {
1617        if def.is_struct() || def.is_union() {
1618            if def.repr().align.is_some() {
1619                return Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(def.did(), DUMMY_SP)]))vec![(def.did(), DUMMY_SP)]);
1620            }
1621
1622            stack.push(def_id);
1623            for field in &def.non_enum_variant().fields {
1624                if let ty::Adt(def, _) = field.ty(tcx, args).kind()
1625                    && !stack.contains(&def.did())
1626                    && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1627                {
1628                    defs.push((def.did(), field.ident(tcx).span));
1629                    return Some(defs);
1630                }
1631            }
1632            stack.pop();
1633        }
1634    }
1635
1636    None
1637}
1638
1639pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1640    if !adt.repr().transparent() {
1641        return;
1642    }
1643
1644    if adt.is_union() && !tcx.features().transparent_unions() {
1645        feature_err(
1646            &tcx.sess,
1647            sym::transparent_unions,
1648            tcx.def_span(adt.did()),
1649            "transparent unions are unstable",
1650        )
1651        .emit();
1652    }
1653
1654    if adt.variants().len() != 1 {
1655        bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1656        // Don't bother checking the fields.
1657        return;
1658    }
1659
1660    let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
1661    // For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1662    struct FieldInfo<'tcx> {
1663        span: Span,
1664        trivial: bool,
1665        ty: Ty<'tcx>,
1666    }
1667
1668    let field_infos = adt.all_fields().map(|field| {
1669        let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did));
1670        let layout = tcx.layout_of(typing_env.as_query_input(ty));
1671        // We are currently checking the type this field came from, so it must be local
1672        let span = tcx.hir_span_if_local(field.did).unwrap();
1673        let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1674        FieldInfo { span, trivial, ty }
1675    });
1676
1677    let non_trivial_fields = field_infos
1678        .clone()
1679        .filter_map(|field| if !field.trivial { Some(field.span) } else { None });
1680    let non_trivial_count = non_trivial_fields.clone().count();
1681    if non_trivial_count >= 2 {
1682        bad_non_zero_sized_fields(
1683            tcx,
1684            adt,
1685            non_trivial_count,
1686            non_trivial_fields,
1687            tcx.def_span(adt.did()),
1688        );
1689        return;
1690    }
1691
1692    // Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1693    // fields or `repr(C)`. We call those fields "unsuited".
1694    struct UnsuitedInfo<'tcx> {
1695        /// The source of the problem, a type that is found somewhere within the field type.
1696        ty: Ty<'tcx>,
1697        reason: UnsuitedReason,
1698    }
1699    enum UnsuitedReason {
1700        NonExhaustive,
1701        PrivateField,
1702        ReprC,
1703    }
1704
1705    fn check_unsuited<'tcx>(
1706        tcx: TyCtxt<'tcx>,
1707        typing_env: ty::TypingEnv<'tcx>,
1708        ty: Ty<'tcx>,
1709    ) -> ControlFlow<UnsuitedInfo<'tcx>> {
1710        // We can encounter projections during traversal, so ensure the type is normalized.
1711        let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1712        match ty.kind() {
1713            ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1714            ty::Array(ty, _) => check_unsuited(tcx, typing_env, *ty),
1715            ty::Adt(def, args) => {
1716                if !def.did().is_local() && !{

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in tcx.get_all_attrs(def.did()) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(RustcPubTransparent(_)) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(tcx, def.did(), RustcPubTransparent(_)) {
1717                    let non_exhaustive = def.is_variant_list_non_exhaustive()
1718                        || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1719                    let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1720                    if non_exhaustive || has_priv {
1721                        return ControlFlow::Break(UnsuitedInfo {
1722                            ty,
1723                            reason: if non_exhaustive {
1724                                UnsuitedReason::NonExhaustive
1725                            } else {
1726                                UnsuitedReason::PrivateField
1727                            },
1728                        });
1729                    }
1730                }
1731                if def.repr().c() {
1732                    return ControlFlow::Break(UnsuitedInfo { ty, reason: UnsuitedReason::ReprC });
1733                }
1734                def.all_fields()
1735                    .map(|field| field.ty(tcx, args))
1736                    .try_for_each(|t| check_unsuited(tcx, typing_env, t))
1737            }
1738            _ => ControlFlow::Continue(()),
1739        }
1740    }
1741
1742    let mut prev_unsuited_1zst = false;
1743    for field in field_infos {
1744        if field.trivial
1745            && let Some(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1746        {
1747            // If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
1748            // Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
1749            if non_trivial_count > 0 || prev_unsuited_1zst {
1750                tcx.node_span_lint(
1751                    REPR_TRANSPARENT_NON_ZST_FIELDS,
1752                    tcx.local_def_id_to_hir_id(adt.did().expect_local()),
1753                    field.span,
1754                    |lint| {
1755                        let title = match unsuited.reason {
1756                            UnsuitedReason::NonExhaustive => "external non-exhaustive types",
1757                            UnsuitedReason::PrivateField => "external types with private fields",
1758                            UnsuitedReason::ReprC => "`repr(C)` types",
1759                        };
1760                        lint.primary_message(
1761                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("zero-sized fields in `repr(transparent)` cannot contain {0}",
                title))
    })format!("zero-sized fields in `repr(transparent)` cannot contain {title}"),
1762                        );
1763                        let note = match unsuited.reason {
1764                            UnsuitedReason::NonExhaustive => "is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future.",
1765                            UnsuitedReason::PrivateField => "contains private fields, so it could become non-zero-sized in the future.",
1766                            UnsuitedReason::ReprC => "is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets.",
1767                        };
1768                        lint.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this field contains `{0}`, which {1}",
                unsuited.ty, note))
    })format!(
1769                            "this field contains `{field_ty}`, which {note}",
1770                            field_ty = unsuited.ty,
1771                        ));
1772                    },
1773                );
1774            } else {
1775                prev_unsuited_1zst = true;
1776            }
1777        }
1778    }
1779}
1780
1781#[allow(trivial_numeric_casts)]
1782fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1783    let def = tcx.adt_def(def_id);
1784    def.destructor(tcx); // force the destructor to be evaluated
1785
1786    if def.variants().is_empty() {
1787        {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in tcx.get_all_attrs(def_id) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(Repr { reprs, first_span }) =>
                            {
                            break 'done
                                Some({
                                        {
                                                    tcx.dcx().struct_span_err(reprs.first().map(|repr|
                                                                        repr.1).unwrap_or(*first_span),
                                                            ::alloc::__export::must_use({
                                                                    ::alloc::fmt::format(format_args!("unsupported representation for zero-variant enum"))
                                                                })).with_code(E0084)
                                                }.with_span_label(tcx.def_span(def_id),
                                                "zero-variant enum").emit();
                                    });
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }
};find_attr!(tcx, def_id, Repr { reprs, first_span } => {
1788            struct_span_code_err!(
1789                tcx.dcx(),
1790                reprs.first().map(|repr| repr.1).unwrap_or(*first_span),
1791                E0084,
1792                "unsupported representation for zero-variant enum"
1793            )
1794            .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1795            .emit();
1796        });
1797    }
1798
1799    for v in def.variants() {
1800        if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1801            tcx.ensure_ok().typeck(discr_def_id.expect_local());
1802        }
1803    }
1804
1805    if def.repr().int.is_none() {
1806        let is_unit = |var: &ty::VariantDef| #[allow(non_exhaustive_omitted_patterns)] match var.ctor_kind() {
    Some(CtorKind::Const) => true,
    _ => false,
}matches!(var.ctor_kind(), Some(CtorKind::Const));
1807        let get_disr = |var: &ty::VariantDef| match var.discr {
1808            ty::VariantDiscr::Explicit(disr) => Some(disr),
1809            ty::VariantDiscr::Relative(_) => None,
1810        };
1811
1812        let non_unit = def.variants().iter().find(|var| !is_unit(var));
1813        let disr_unit =
1814            def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var));
1815        let disr_non_unit =
1816            def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var));
1817
1818        if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) {
1819            let mut err = {
    tcx.dcx().struct_span_err(tcx.def_span(def_id),
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"))
                })).with_code(E0732)
}struct_span_code_err!(
1820                tcx.dcx(),
1821                tcx.def_span(def_id),
1822                E0732,
1823                "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"
1824            );
1825            if let Some(disr_non_unit) = disr_non_unit {
1826                err.span_label(
1827                    tcx.def_span(disr_non_unit),
1828                    "explicit discriminant on non-unit variant specified here",
1829                );
1830            } else {
1831                err.span_label(
1832                    tcx.def_span(disr_unit.unwrap()),
1833                    "explicit discriminant specified here",
1834                );
1835                err.span_label(
1836                    tcx.def_span(non_unit.unwrap().def_id),
1837                    "non-unit discriminant declared here",
1838                );
1839            }
1840            err.emit();
1841        }
1842    }
1843
1844    detect_discriminant_duplicate(tcx, def);
1845    check_transparent(tcx, def);
1846}
1847
1848/// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1849fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1850    // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1851    // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1852    let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1853        let var = adt.variant(idx); // HIR for the duplicate discriminant
1854        let (span, display_discr) = match var.discr {
1855            ty::VariantDiscr::Explicit(discr_def_id) => {
1856                // In the case the discriminant is both a duplicate and overflowed, let the user know
1857                if let hir::Node::AnonConst(expr) =
1858                    tcx.hir_node_by_def_id(discr_def_id.expect_local())
1859                    && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1860                    && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1861                    && *lit_value != dis.val
1862                {
1863                    (tcx.def_span(discr_def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` (overflowed from `{1}`)",
                dis, lit_value))
    })format!("`{dis}` (overflowed from `{lit_value}`)"))
1864                } else {
1865                    // Otherwise, format the value as-is
1866                    (tcx.def_span(discr_def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", dis))
    })format!("`{dis}`"))
1867                }
1868            }
1869            // This should not happen.
1870            ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", dis))
    })format!("`{dis}`")),
1871            ty::VariantDiscr::Relative(distance_to_explicit) => {
1872                // At this point we know this discriminant is a duplicate, and was not explicitly
1873                // assigned by the user. Here we iterate backwards to fetch the HIR for the last
1874                // explicitly assigned discriminant, and letting the user know that this was the
1875                // increment startpoint, and how many steps from there leading to the duplicate
1876                if let Some(explicit_idx) =
1877                    idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1878                {
1879                    let explicit_variant = adt.variant(explicit_idx);
1880                    let ve_ident = var.name;
1881                    let ex_ident = explicit_variant.name;
1882                    let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1883
1884                    err.span_label(
1885                        tcx.def_span(explicit_variant.def_id),
1886                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("discriminant for `{0}` incremented from this startpoint (`{1}` + {2} {3} later => `{0}` = {4})",
                ve_ident, ex_ident, distance_to_explicit, sp, dis))
    })format!(
1887                            "discriminant for `{ve_ident}` incremented from this startpoint \
1888                            (`{ex_ident}` + {distance_to_explicit} {sp} later \
1889                             => `{ve_ident}` = {dis})"
1890                        ),
1891                    );
1892                }
1893
1894                (tcx.def_span(var.def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", dis))
    })format!("`{dis}`"))
1895            }
1896        };
1897
1898        err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} assigned here", display_discr))
    })format!("{display_discr} assigned here"));
1899    };
1900
1901    let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1902
1903    // Here we loop through the discriminants, comparing each discriminant to another.
1904    // When a duplicate is detected, we instantiate an error and point to both
1905    // initial and duplicate value. The duplicate discriminant is then discarded by swapping
1906    // it with the last element and decrementing the `vec.len` (which is why we have to evaluate
1907    // `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
1908    // style as we are mutating `discrs` on the fly).
1909    let mut i = 0;
1910    while i < discrs.len() {
1911        let var_i_idx = discrs[i].0;
1912        let mut error: Option<Diag<'_, _>> = None;
1913
1914        let mut o = i + 1;
1915        while o < discrs.len() {
1916            let var_o_idx = discrs[o].0;
1917
1918            if discrs[i].1.val == discrs[o].1.val {
1919                let err = error.get_or_insert_with(|| {
1920                    let mut ret = {
    tcx.dcx().struct_span_err(tcx.def_span(adt.did()),
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("discriminant value `{0}` assigned more than once",
                            discrs[i].1))
                })).with_code(E0081)
}struct_span_code_err!(
1921                        tcx.dcx(),
1922                        tcx.def_span(adt.did()),
1923                        E0081,
1924                        "discriminant value `{}` assigned more than once",
1925                        discrs[i].1,
1926                    );
1927
1928                    report(discrs[i].1, var_i_idx, &mut ret);
1929
1930                    ret
1931                });
1932
1933                report(discrs[o].1, var_o_idx, err);
1934
1935                // Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
1936                discrs[o] = *discrs.last().unwrap();
1937                discrs.pop();
1938            } else {
1939                o += 1;
1940            }
1941        }
1942
1943        if let Some(e) = error {
1944            e.emit();
1945        }
1946
1947        i += 1;
1948    }
1949}
1950
1951fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1952    if tcx.type_alias_is_lazy(def_id) {
1953        // Since we compute the variances for lazy type aliases and already reject bivariant
1954        // parameters as unused, we can and should skip this check for lazy type aliases.
1955        return;
1956    }
1957
1958    let generics = tcx.generics_of(def_id);
1959    if generics.own_counts().types == 0 {
1960        return;
1961    }
1962
1963    let ty = tcx.type_of(def_id).instantiate_identity();
1964    if ty.references_error() {
1965        // If there is already another error, do not emit an error for not using a type parameter.
1966        return;
1967    }
1968
1969    // Lazily calculated because it is only needed in case of an error.
1970    let bounded_params = LazyCell::new(|| {
1971        tcx.explicit_predicates_of(def_id)
1972            .predicates
1973            .iter()
1974            .filter_map(|(predicate, span)| {
1975                let bounded_ty = match predicate.kind().skip_binder() {
1976                    ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
1977                    ty::ClauseKind::TypeOutlives(pred) => pred.0,
1978                    _ => return None,
1979                };
1980                if let ty::Param(param) = bounded_ty.kind() {
1981                    Some((param.index, span))
1982                } else {
1983                    None
1984                }
1985            })
1986            // FIXME: This assumes that elaborated `Sized` bounds come first (which does hold at the
1987            // time of writing). This is a bit fragile since we later use the span to detect elaborated
1988            // `Sized` bounds. If they came last for example, this would break `Trait + /*elab*/Sized`
1989            // since it would overwrite the span of the user-written bound. This could be fixed by
1990            // folding the spans with `Span::to` which requires a bit of effort I think.
1991            .collect::<FxIndexMap<_, _>>()
1992    });
1993
1994    let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
1995    for leaf in ty.walk() {
1996        if let GenericArgKind::Type(leaf_ty) = leaf.kind()
1997            && let ty::Param(param) = leaf_ty.kind()
1998        {
1999            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/check.rs:1999",
                        "rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(1999u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("found use of ty param {0:?}",
                                                    param) as &dyn Value))])
            });
    } else { ; }
};debug!("found use of ty param {:?}", param);
2000            params_used.insert(param.index);
2001        }
2002    }
2003
2004    for param in &generics.own_params {
2005        if !params_used.contains(param.index)
2006            && let ty::GenericParamDefKind::Type { .. } = param.kind
2007        {
2008            let span = tcx.def_span(param.def_id);
2009            let param_name = Ident::new(param.name, span);
2010
2011            // The corresponding predicates are post-`Sized`-elaboration. Therefore we
2012            // * check for emptiness to detect lone user-written `?Sized` bounds
2013            // * compare the param span to the pred span to detect lone user-written `Sized` bounds
2014            let has_explicit_bounds = bounded_params.is_empty()
2015                || (*bounded_params).get(&param.index).is_some_and(|&&pred_sp| pred_sp != span);
2016            let const_param_help = !has_explicit_bounds;
2017
2018            let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2019                span,
2020                param_name,
2021                param_def_kind: tcx.def_descr(param.def_id),
2022                help: errors::UnusedGenericParameterHelp::TyAlias { param_name },
2023                usage_spans: ::alloc::vec::Vec::new()vec![],
2024                const_param_help,
2025            });
2026            diag.code(E0091);
2027            diag.emit();
2028        }
2029    }
2030}
2031
2032/// Emit an error for recursive opaque types.
2033///
2034/// If this is a return `impl Trait`, find the item's return expressions and point at them. For
2035/// direct recursion this is enough, but for indirect recursion also point at the last intermediary
2036/// `impl Trait`.
2037///
2038/// If all the return expressions evaluate to `!`, then we explain that the error will go away
2039/// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
2040fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
2041    let span = tcx.def_span(opaque_def_id);
2042    let mut err = {
    tcx.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("cannot resolve opaque type"))
                })).with_code(E0720)
}struct_span_code_err!(tcx.dcx(), span, E0720, "cannot resolve opaque type");
2043
2044    let mut label = false;
2045    if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
2046        let typeck_results = tcx.typeck(def_id);
2047        if visitor
2048            .returns
2049            .iter()
2050            .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
2051            .all(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Never => true,
    _ => false,
}matches!(ty.kind(), ty::Never))
2052        {
2053            let spans = visitor
2054                .returns
2055                .iter()
2056                .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
2057                .map(|expr| expr.span)
2058                .collect::<Vec<Span>>();
2059            let span_len = spans.len();
2060            if span_len == 1 {
2061                err.span_label(spans[0], "this returned value is of `!` type");
2062            } else {
2063                let mut multispan: MultiSpan = spans.clone().into();
2064                for span in spans {
2065                    multispan.push_span_label(span, "this returned value is of `!` type");
2066                }
2067                err.span_note(multispan, "these returned values have a concrete \"never\" type");
2068            }
2069            err.help("this error will resolve once the item's body returns a concrete type");
2070        } else {
2071            let mut seen = FxHashSet::default();
2072            seen.insert(span);
2073            err.span_label(span, "recursive opaque type");
2074            label = true;
2075            for (sp, ty) in visitor
2076                .returns
2077                .iter()
2078                .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
2079                .filter(|(_, ty)| !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Never => true,
    _ => false,
}matches!(ty.kind(), ty::Never))
2080            {
2081                #[derive(#[automatically_derived]
impl ::core::default::Default for OpaqueTypeCollector {
    #[inline]
    fn default() -> OpaqueTypeCollector {
        OpaqueTypeCollector {
            opaques: ::core::default::Default::default(),
            closures: ::core::default::Default::default(),
        }
    }
}Default)]
2082                struct OpaqueTypeCollector {
2083                    opaques: Vec<DefId>,
2084                    closures: Vec<DefId>,
2085                }
2086                impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
2087                    fn visit_ty(&mut self, t: Ty<'tcx>) {
2088                        match *t.kind() {
2089                            ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
2090                                self.opaques.push(def);
2091                            }
2092                            ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
2093                                self.closures.push(def_id);
2094                                t.super_visit_with(self);
2095                            }
2096                            _ => t.super_visit_with(self),
2097                        }
2098                    }
2099                }
2100
2101                let mut visitor = OpaqueTypeCollector::default();
2102                ty.visit_with(&mut visitor);
2103                for def_id in visitor.opaques {
2104                    let ty_span = tcx.def_span(def_id);
2105                    if !seen.contains(&ty_span) {
2106                        let descr = if ty.is_impl_trait() { "opaque " } else { "" };
2107                        err.span_label(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("returning this {0}type `{1}`",
                descr, ty))
    })format!("returning this {descr}type `{ty}`"));
2108                        seen.insert(ty_span);
2109                    }
2110                    err.span_label(sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("returning here with type `{0}`",
                ty))
    })format!("returning here with type `{ty}`"));
2111                }
2112
2113                for closure_def_id in visitor.closures {
2114                    let Some(closure_local_did) = closure_def_id.as_local() else {
2115                        continue;
2116                    };
2117                    let typeck_results = tcx.typeck(closure_local_did);
2118
2119                    let mut label_match = |ty: Ty<'_>, span| {
2120                        for arg in ty.walk() {
2121                            if let ty::GenericArgKind::Type(ty) = arg.kind()
2122                                && let ty::Alias(
2123                                    ty::Opaque,
2124                                    ty::AliasTy { def_id: captured_def_id, .. },
2125                                ) = *ty.kind()
2126                                && captured_def_id == opaque_def_id.to_def_id()
2127                            {
2128                                err.span_label(
2129                                    span,
2130                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} captures itself here",
                tcx.def_descr(closure_def_id)))
    })format!(
2131                                        "{} captures itself here",
2132                                        tcx.def_descr(closure_def_id)
2133                                    ),
2134                                );
2135                            }
2136                        }
2137                    };
2138
2139                    // Label any closure upvars that capture the opaque
2140                    for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
2141                    {
2142                        label_match(capture.place.ty(), capture.get_path_span(tcx));
2143                    }
2144                    // Label any coroutine locals that capture the opaque
2145                    if tcx.is_coroutine(closure_def_id)
2146                        && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
2147                    {
2148                        for interior_ty in &coroutine_layout.field_tys {
2149                            label_match(interior_ty.ty, interior_ty.source_info.span);
2150                        }
2151                    }
2152                }
2153            }
2154        }
2155    }
2156    if !label {
2157        err.span_label(span, "cannot resolve opaque type");
2158    }
2159    err.emit()
2160}
2161
2162pub(super) fn check_coroutine_obligations(
2163    tcx: TyCtxt<'_>,
2164    def_id: LocalDefId,
2165) -> Result<(), ErrorGuaranteed> {
2166    if true {
    if !!tcx.is_typeck_child(def_id.to_def_id()) {
        ::core::panicking::panic("assertion failed: !tcx.is_typeck_child(def_id.to_def_id())")
    };
};debug_assert!(!tcx.is_typeck_child(def_id.to_def_id()));
2167
2168    let typeck_results = tcx.typeck(def_id);
2169    let param_env = tcx.param_env(def_id);
2170
2171    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/check.rs:2171",
                        "rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(2171u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                        ::tracing_core::field::FieldSet::new(&["typeck_results.coroutine_stalled_predicates"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&typeck_results.coroutine_stalled_predicates)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?typeck_results.coroutine_stalled_predicates);
2172
2173    let mode = if tcx.next_trait_solver_globally() {
2174        // This query is conceptually between HIR typeck and
2175        // MIR borrowck. We use the opaque types defined by HIR
2176        // and ignore region constraints.
2177        TypingMode::borrowck(tcx, def_id)
2178    } else {
2179        TypingMode::analysis_in_body(tcx, def_id)
2180    };
2181
2182    // Typeck writeback gives us predicates with their regions erased.
2183    // We only need to check the goals while ignoring lifetimes to give good
2184    // error message and to avoid breaking the assumption of `mir_borrowck`
2185    // that all obligations already hold modulo regions.
2186    let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
2187
2188    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2189    for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
2190        ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
2191    }
2192
2193    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2194    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/check.rs:2194",
                        "rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(2194u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                        ::tracing_core::field::FieldSet::new(&["errors"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&errors) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?errors);
2195    if !errors.is_empty() {
2196        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2197    }
2198
2199    if !tcx.next_trait_solver_globally() {
2200        // Check that any hidden types found when checking these stalled coroutine obligations
2201        // are valid.
2202        for (key, ty) in infcx.take_opaque_types() {
2203            let hidden_type = infcx.resolve_vars_if_possible(ty);
2204            let key = infcx.resolve_vars_if_possible(key);
2205            sanity_check_found_hidden_type(tcx, key, hidden_type)?;
2206        }
2207    } else {
2208        // We're not checking region constraints here, so we can simply drop the
2209        // added opaque type uses in `TypingMode::Borrowck`.
2210        let _ = infcx.take_opaque_types();
2211    }
2212
2213    Ok(())
2214}
2215
2216pub(super) fn check_potentially_region_dependent_goals<'tcx>(
2217    tcx: TyCtxt<'tcx>,
2218    def_id: LocalDefId,
2219) -> Result<(), ErrorGuaranteed> {
2220    if !tcx.next_trait_solver_globally() {
2221        return Ok(());
2222    }
2223    let typeck_results = tcx.typeck(def_id);
2224    let param_env = tcx.param_env(def_id);
2225
2226    // We use `TypingMode::Borrowck` as we want to use the opaque types computed by HIR typeck.
2227    let typing_mode = TypingMode::borrowck(tcx, def_id);
2228    let infcx = tcx.infer_ctxt().ignoring_regions().build(typing_mode);
2229    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2230    for (predicate, cause) in &typeck_results.potentially_region_dependent_goals {
2231        let predicate = fold_regions(tcx, *predicate, |_, _| {
2232            infcx.next_region_var(RegionVariableOrigin::Misc(cause.span))
2233        });
2234        ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate));
2235    }
2236
2237    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2238    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/check.rs:2238",
                        "rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/check.rs"),
                        ::tracing_core::__macro_support::Option::Some(2238u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                        ::tracing_core::field::FieldSet::new(&["errors"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&errors) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?errors);
2239    if errors.is_empty() { Ok(()) } else { Err(infcx.err_ctxt().report_fulfillment_errors(errors)) }
2240}