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::AttributeKind;
10use rustc_hir::attrs::ReprAttr::ReprPacked;
11use rustc_hir::def::{CtorKind, DefKind};
12use rustc_hir::{LangItem, Node, attrs, find_attr, intravisit};
13use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
14use rustc_infer::traits::{Obligation, ObligationCauseCode, WellFormedLoc};
15use rustc_lint_defs::builtin::{REPR_TRANSPARENT_NON_ZST_FIELDS, UNSUPPORTED_CALLING_CONVENTIONS};
16use rustc_middle::hir::nested_filter;
17use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
18use rustc_middle::middle::stability::EvalResult;
19use rustc_middle::ty::error::TypeErrorToStringExt;
20use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
21use rustc_middle::ty::util::Discr;
22use rustc_middle::ty::{
23    AdtDef, BottomUpFolder, FnSig, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable,
24    TypeVisitable, TypeVisitableExt, fold_regions,
25};
26use rustc_session::lint::builtin::UNINHABITED_STATIC;
27use rustc_target::spec::{AbiMap, AbiMapping};
28use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
29use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective;
30use rustc_trait_selection::traits;
31use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
32use tracing::{debug, instrument};
33use ty::TypingMode;
34
35use super::compare_impl_item::check_type_bounds;
36use super::*;
37use crate::check::wfcheck::{
38    check_associated_item, check_trait_item, check_variances_for_type_defn, check_where_clauses,
39    enter_wf_checking_ctxt,
40};
41
42fn add_abi_diag_help<T: EmissionGuarantee>(abi: ExternAbi, diag: &mut Diag<'_, T>) {
43    if let ExternAbi::Cdecl { unwind } = abi {
44        let c_abi = ExternAbi::C { unwind };
45        diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `extern {0}` instead", c_abi))
    })format!("use `extern {c_abi}` instead",));
46    } else if let ExternAbi::Stdcall { unwind } = abi {
47        let c_abi = ExternAbi::C { unwind };
48        let system_abi = ExternAbi::System { unwind };
49        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!(
50            "if you need `extern {abi}` on win32 and `extern {c_abi}` everywhere else, \
51                use `extern {system_abi}`"
52        ));
53    }
54}
55
56pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: ExternAbi) {
57    // FIXME: This should be checked earlier, e.g. in `rustc_ast_lowering`, as this
58    // currently only guards function imports, function definitions, and function pointer types.
59    // Functions in trait declarations can still use "deprecated" ABIs without any warning.
60
61    match AbiMap::from_target(&tcx.sess.target).canonize_abi(abi, false) {
62        AbiMapping::Direct(..) => (),
63        // already erred in rustc_ast_lowering
64        AbiMapping::Invalid => {
65            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"));
66        }
67        AbiMapping::Deprecated(..) => {
68            tcx.node_span_lint(UNSUPPORTED_CALLING_CONVENTIONS, hir_id, span, |lint| {
69                lint.primary_message(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} is not a supported ABI for the current target",
                abi))
    })format!(
70                    "{abi} is not a supported ABI for the current target"
71                ));
72                add_abi_diag_help(abi, lint);
73            });
74        }
75    }
76}
77
78pub fn check_custom_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, fn_sig: FnSig<'_>, fn_sig_span: Span) {
79    if fn_sig.abi == ExternAbi::Custom {
80        // Function definitions that use `extern "custom"` must be naked functions.
81        if !{
    {
            'done:
                {
                for i in tcx.get_all_attrs(def_id) {
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AttributeKind::Naked(_)) => {
                            break 'done Some(());
                        }
                        _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Naked(_)) {
82            tcx.dcx().emit_err(crate::errors::AbiCustomClothedFunction {
83                span: fn_sig_span,
84                naked_span: tcx.def_span(def_id).shrink_to_lo(),
85            });
86        }
87    }
88}
89
90fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) {
91    let def = tcx.adt_def(def_id);
92    let span = tcx.def_span(def_id);
93    def.destructor(tcx); // force the destructor to be evaluated
94
95    if let Some(scalable) = def.repr().scalable {
96        check_scalable_vector(tcx, span, def_id, scalable);
97    } else if def.repr().simd() {
98        check_simd(tcx, span, def_id);
99    }
100
101    check_transparent(tcx, def);
102    check_packed(tcx, span, def);
103}
104
105fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) {
106    let def = tcx.adt_def(def_id);
107    let span = tcx.def_span(def_id);
108    def.destructor(tcx); // force the destructor to be evaluated
109    check_transparent(tcx, def);
110    check_union_fields(tcx, span, def_id);
111    check_packed(tcx, span, def);
112}
113
114fn allowed_union_or_unsafe_field<'tcx>(
115    tcx: TyCtxt<'tcx>,
116    ty: Ty<'tcx>,
117    typing_env: ty::TypingEnv<'tcx>,
118    span: Span,
119) -> bool {
120    // HACK (not that bad of a hack don't worry): Some codegen tests don't even define proper
121    // impls for `Copy`. Let's short-circuit here for this validity check, since a lot of them
122    // use unions. We should eventually fix all the tests to define that lang item or use
123    // minicore stubs.
124    if ty.is_trivially_pure_clone_copy() {
125        return true;
126    }
127    // If `BikeshedGuaranteedNoDrop` is not defined in a `#[no_core]` test, fall back to `Copy`.
128    // This is an underapproximation of `BikeshedGuaranteedNoDrop`,
129    let def_id = tcx
130        .lang_items()
131        .get(LangItem::BikeshedGuaranteedNoDrop)
132        .unwrap_or_else(|| tcx.require_lang_item(LangItem::Copy, span));
133    let Ok(ty) = tcx.try_normalize_erasing_regions(typing_env, ty) else {
134        tcx.dcx().span_delayed_bug(span, "could not normalize field type");
135        return true;
136    };
137    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
138    infcx.predicate_must_hold_modulo_regions(&Obligation::new(
139        tcx,
140        ObligationCause::dummy_with_span(span),
141        param_env,
142        ty::TraitRef::new(tcx, def_id, [ty]),
143    ))
144}
145
146/// Check that the fields of the `union` do not need dropping.
147fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
148    let def = tcx.adt_def(item_def_id);
149    if !def.is_union() {
    ::core::panicking::panic("assertion failed: def.is_union()")
};assert!(def.is_union());
150
151    let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
152    let args = ty::GenericArgs::identity_for_item(tcx, item_def_id);
153
154    for field in &def.non_enum_variant().fields {
155        if !allowed_union_or_unsafe_field(tcx, field.ty(tcx, args), typing_env, span) {
156            let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {
157                // We are currently checking the type this field came from, so it must be local.
158                Some(Node::Field(field)) => (field.span, field.ty.span),
159                _ => {
    ::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"),
160            };
161            tcx.dcx().emit_err(errors::InvalidUnionField {
162                field_span,
163                sugg: errors::InvalidUnionFieldSuggestion {
164                    lo: ty_span.shrink_to_lo(),
165                    hi: ty_span.shrink_to_hi(),
166                },
167                note: (),
168            });
169            return false;
170        }
171    }
172
173    true
174}
175
176/// Check that a `static` is inhabited.
177fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
178    // Make sure statics are inhabited.
179    // Other parts of the compiler assume that there are no uninhabited places. In principle it
180    // would be enough to check this for `extern` statics, as statics with an initializer will
181    // have UB during initialization if they are uninhabited, but there also seems to be no good
182    // reason to allow any statics to be uninhabited.
183    let ty = tcx.type_of(def_id).instantiate_identity();
184    let span = tcx.def_span(def_id);
185    let layout = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
186        Ok(l) => l,
187        // Foreign statics that overflow their allowed size should emit an error
188        Err(LayoutError::SizeOverflow(_))
189            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{ .. }
190                if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) =>
191        {
192            tcx.dcx().emit_err(errors::TooLargeStatic { span });
193            return;
194        }
195        // Generic statics are rejected, but we still reach this case.
196        Err(e) => {
197            tcx.dcx().span_delayed_bug(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", e))
    })format!("{e:?}"));
198            return;
199        }
200    };
201    if layout.is_uninhabited() {
202        tcx.node_span_lint(
203            UNINHABITED_STATIC,
204            tcx.local_def_id_to_hir_id(def_id),
205            span,
206            |lint| {
207                lint.primary_message("static of uninhabited type");
208                lint
209                .note("uninhabited statics cannot be initialized, and any access would be an immediate error");
210            },
211        );
212    }
213}
214
215/// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
216/// projections that would result in "inheriting lifetimes".
217fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
218    let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);
219
220    // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
221    // `async-std` (and `pub async fn` in general).
222    // Since rustdoc doesn't care about the hidden type behind `impl Trait`, just don't look at it!
223    // See https://github.com/rust-lang/rust/issues/75100
224    if tcx.sess.opts.actually_rustdoc {
225        return;
226    }
227
228    if tcx.type_of(def_id).instantiate_identity().references_error() {
229        return;
230    }
231    if check_opaque_for_cycles(tcx, def_id).is_err() {
232        return;
233    }
234
235    let _ = check_opaque_meets_bounds(tcx, def_id, origin);
236}
237
238/// Checks that an opaque type does not contain cycles.
239pub(super) fn check_opaque_for_cycles<'tcx>(
240    tcx: TyCtxt<'tcx>,
241    def_id: LocalDefId,
242) -> Result<(), ErrorGuaranteed> {
243    let args = GenericArgs::identity_for_item(tcx, def_id);
244
245    // First, try to look at any opaque expansion cycles, considering coroutine fields
246    // (even though these aren't necessarily true errors).
247    if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() {
248        let reported = opaque_type_cycle_error(tcx, def_id);
249        return Err(reported);
250    }
251
252    Ok(())
253}
254
255/// Check that the hidden type behind `impl Trait` actually implements `Trait`.
256///
257/// This is mostly checked at the places that specify the opaque type, but we
258/// check those cases in the `param_env` of that function, which may have
259/// bounds not on this opaque type:
260///
261/// ```ignore (illustrative)
262/// type X<T> = impl Clone;
263/// fn f<T: Clone>(t: T) -> X<T> {
264///     t
265/// }
266/// ```
267///
268/// Without this check the above code is incorrectly accepted: we would ICE if
269/// some tried, for example, to clone an `Option<X<&mut ()>>`.
270#[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(270u32),
                                    ::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))]
271fn check_opaque_meets_bounds<'tcx>(
272    tcx: TyCtxt<'tcx>,
273    def_id: LocalDefId,
274    origin: hir::OpaqueTyOrigin<LocalDefId>,
275) -> Result<(), ErrorGuaranteed> {
276    let (span, definition_def_id) =
277        if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {
278            (span, Some(def_id))
279        } else {
280            (tcx.def_span(def_id), None)
281        };
282
283    let defining_use_anchor = match origin {
284        hir::OpaqueTyOrigin::FnReturn { parent, .. }
285        | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
286        | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
287    };
288    let param_env = tcx.param_env(defining_use_anchor);
289
290    // FIXME(#132279): Once `PostBorrowckAnalysis` is supported in the old solver, this branch should be removed.
291    let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
292        TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
293    } else {
294        TypingMode::analysis_in_body(tcx, defining_use_anchor)
295    });
296    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
297
298    let args = match origin {
299        hir::OpaqueTyOrigin::FnReturn { parent, .. }
300        | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
301        | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(
302            tcx, parent,
303        )
304        .extend_to(tcx, def_id.to_def_id(), |param, _| {
305            tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
306        }),
307    };
308
309    let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
310
311    // `ReErased` regions appear in the "parent_args" of closures/coroutines.
312    // We're ignoring them here and replacing them with fresh region variables.
313    // See tests in ui/type-alias-impl-trait/closure_{parent_args,wf_outlives}.rs.
314    //
315    // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it
316    // here rather than using ReErased.
317    let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args);
318    let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {
319        ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)),
320        _ => re,
321    });
322
323    // HACK: We eagerly instantiate some bounds to report better errors for them...
324    // This isn't necessary for correctness, since we register these bounds when
325    // equating the opaque below, but we should clean this up in the new solver.
326    for (predicate, pred_span) in
327        tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx, args)
328    {
329        let predicate = predicate.fold_with(&mut BottomUpFolder {
330            tcx,
331            ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
332            lt_op: |lt| lt,
333            ct_op: |ct| ct,
334        });
335
336        ocx.register_obligation(Obligation::new(
337            tcx,
338            ObligationCause::new(
339                span,
340                def_id,
341                ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
342            ),
343            param_env,
344            predicate,
345        ));
346    }
347
348    let misc_cause = ObligationCause::misc(span, def_id);
349    // FIXME: We should just register the item bounds here, rather than equating.
350    // FIXME(const_trait_impl): When we do that, please make sure to also register
351    // the `[const]` bounds.
352    match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
353        Ok(()) => {}
354        Err(ty_err) => {
355            // Some types may be left "stranded" if they can't be reached
356            // from a lowered rustc_middle bound but they're mentioned in the HIR.
357            // This will happen, e.g., when a nested opaque is inside of a non-
358            // existent associated type, like `impl Trait<Missing = impl Trait>`.
359            // See <tests/ui/impl-trait/stranded-opaque.rs>.
360            let ty_err = ty_err.to_string(tcx);
361            let guar = tcx.dcx().span_delayed_bug(
362                span,
363                format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
364            );
365            return Err(guar);
366        }
367    }
368
369    // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
370    // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
371    // hidden type is well formed even without those bounds.
372    let predicate =
373        ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
374    ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
375
376    // Check that all obligations are satisfied by the implementation's
377    // version.
378    let errors = ocx.evaluate_obligations_error_on_ambiguity();
379    if !errors.is_empty() {
380        let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
381        return Err(guar);
382    }
383
384    let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
385    ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
386
387    if infcx.next_trait_solver() {
388        Ok(())
389    } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
390        origin
391    {
392        // HACK: this should also fall through to the hidden type check below, but the original
393        // implementation had a bug where equivalent lifetimes are not identical. This caused us
394        // to reject existing stable code that is otherwise completely fine. The real fix is to
395        // compare the hidden types via our type equivalence/relation infra instead of doing an
396        // identity check.
397        let _ = infcx.take_opaque_types();
398        Ok(())
399    } else {
400        // Check that any hidden types found during wf checking match the hidden types that `type_of` sees.
401        for (mut key, mut ty) in infcx.take_opaque_types() {
402            ty.ty = infcx.resolve_vars_if_possible(ty.ty);
403            key = infcx.resolve_vars_if_possible(key);
404            sanity_check_found_hidden_type(tcx, key, ty)?;
405        }
406        Ok(())
407    }
408}
409
410fn best_definition_site_of_opaque<'tcx>(
411    tcx: TyCtxt<'tcx>,
412    opaque_def_id: LocalDefId,
413    origin: hir::OpaqueTyOrigin<LocalDefId>,
414) -> Option<(Span, LocalDefId)> {
415    struct TaitConstraintLocator<'tcx> {
416        opaque_def_id: LocalDefId,
417        tcx: TyCtxt<'tcx>,
418    }
419    impl<'tcx> TaitConstraintLocator<'tcx> {
420        fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
421            if !self.tcx.has_typeck_results(item_def_id) {
422                return ControlFlow::Continue(());
423            }
424
425            let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
426            // Don't try to check items that cannot possibly constrain the type.
427            if !opaque_types_defined_by.contains(&self.opaque_def_id) {
428                return ControlFlow::Continue(());
429            }
430
431            if let Some(hidden_ty) = self
432                .tcx
433                .mir_borrowck(item_def_id)
434                .ok()
435                .and_then(|opaque_types| opaque_types.get(&self.opaque_def_id))
436            {
437                ControlFlow::Break((hidden_ty.span, item_def_id))
438            } else {
439                ControlFlow::Continue(())
440            }
441        }
442    }
443    impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
444        type NestedFilter = nested_filter::All;
445        type Result = ControlFlow<(Span, LocalDefId)>;
446        fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
447            self.tcx
448        }
449        fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
450            intravisit::walk_expr(self, ex)
451        }
452        fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
453            self.check(it.owner_id.def_id)?;
454            intravisit::walk_item(self, it)
455        }
456        fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
457            self.check(it.owner_id.def_id)?;
458            intravisit::walk_impl_item(self, it)
459        }
460        fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
461            self.check(it.owner_id.def_id)?;
462            intravisit::walk_trait_item(self, it)
463        }
464        fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
465            intravisit::walk_foreign_item(self, it)
466        }
467    }
468
469    let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
470    match origin {
471        hir::OpaqueTyOrigin::FnReturn { parent, .. }
472        | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
473        hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
474            let impl_def_id = tcx.local_parent(parent);
475            for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
476                match assoc.kind {
477                    ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
478                        if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
479                        {
480                            return Some(span);
481                        }
482                    }
483                    ty::AssocKind::Type { .. } => {}
484                }
485            }
486
487            None
488        }
489        hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
490            tcx.hir_walk_toplevel_module(&mut locator).break_value()
491        }
492    }
493}
494
495fn sanity_check_found_hidden_type<'tcx>(
496    tcx: TyCtxt<'tcx>,
497    key: ty::OpaqueTypeKey<'tcx>,
498    mut ty: ty::ProvisionalHiddenType<'tcx>,
499) -> Result<(), ErrorGuaranteed> {
500    if ty.ty.is_ty_var() {
501        // Nothing was actually constrained.
502        return Ok(());
503    }
504    if let ty::Alias(ty::Opaque, alias) = ty.ty.kind() {
505        if alias.def_id == key.def_id.to_def_id() && alias.args == key.args {
506            // Nothing was actually constrained, this is an opaque usage that was
507            // only discovered to be opaque after inference vars resolved.
508            return Ok(());
509        }
510    }
511    let erase_re_vars = |ty: Ty<'tcx>| {
512        fold_regions(tcx, ty, |r, _| match r.kind() {
513            RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
514            _ => r,
515        })
516    };
517    // Closures frequently end up containing erased lifetimes in their final representation.
518    // These correspond to lifetime variables that never got resolved, so we patch this up here.
519    ty.ty = erase_re_vars(ty.ty);
520    // Get the hidden type.
521    let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args);
522    let hidden_ty = erase_re_vars(hidden_ty);
523
524    // If the hidden types differ, emit a type mismatch diagnostic.
525    if hidden_ty == ty.ty {
526        Ok(())
527    } else {
528        let span = tcx.def_span(key.def_id);
529        let other = ty::ProvisionalHiddenType { ty: hidden_ty, span };
530        Err(ty.build_mismatch_error(&other, tcx)?.emit())
531    }
532}
533
534/// Check that the opaque's precise captures list is valid (if present).
535/// We check this for regular `impl Trait`s and also RPITITs, even though the latter
536/// are technically GATs.
537///
538/// This function is responsible for:
539/// 1. Checking that all type/const params are mention in the captures list.
540/// 2. Checking that all lifetimes that are implicitly captured are mentioned.
541/// 3. Asserting that all parameters mentioned in the captures list are invariant.
542fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
543    let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
544    let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
545        hir::GenericBound::Use(bounds, ..) => Some(bounds),
546        _ => None,
547    }) else {
548        // No precise capturing args; nothing to validate
549        return;
550    };
551
552    let mut expected_captures = UnordSet::default();
553    let mut shadowed_captures = UnordSet::default();
554    let mut seen_params = UnordMap::default();
555    let mut prev_non_lifetime_param = None;
556    for arg in precise_capturing_args {
557        let (hir_id, ident) = match *arg {
558            hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
559                hir_id,
560                ident,
561                ..
562            }) => {
563                if prev_non_lifetime_param.is_none() {
564                    prev_non_lifetime_param = Some(ident);
565                }
566                (hir_id, ident)
567            }
568            hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
569                if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
570                    tcx.dcx().emit_err(errors::LifetimesMustBeFirst {
571                        lifetime_span: ident.span,
572                        name: ident.name,
573                        other_span: prev_non_lifetime_param.span,
574                    });
575                }
576                (hir_id, ident)
577            }
578        };
579
580        let ident = ident.normalize_to_macros_2_0();
581        if let Some(span) = seen_params.insert(ident, ident.span) {
582            tcx.dcx().emit_err(errors::DuplicatePreciseCapture {
583                name: ident.name,
584                first_span: span,
585                second_span: ident.span,
586            });
587        }
588
589        match tcx.named_bound_var(hir_id) {
590            Some(ResolvedArg::EarlyBound(def_id)) => {
591                expected_captures.insert(def_id.to_def_id());
592
593                // Make sure we allow capturing these lifetimes through `Self` and
594                // `T::Assoc` projection syntax, too. These will occur when we only
595                // see lifetimes are captured after hir-lowering -- this aligns with
596                // the cases that were stabilized with the `impl_trait_projection`
597                // feature -- see <https://github.com/rust-lang/rust/pull/115659>.
598                if let DefKind::LifetimeParam = tcx.def_kind(def_id)
599                    && let Some(def_id) = tcx
600                        .map_opaque_lifetime_to_parent_lifetime(def_id)
601                        .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
602                {
603                    shadowed_captures.insert(def_id);
604                }
605            }
606            _ => {
607                tcx.dcx()
608                    .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
609            }
610        }
611    }
612
613    let variances = tcx.variances_of(opaque_def_id);
614    let mut def_id = Some(opaque_def_id.to_def_id());
615    while let Some(generics) = def_id {
616        let generics = tcx.generics_of(generics);
617        def_id = generics.parent;
618
619        for param in &generics.own_params {
620            if expected_captures.contains(&param.def_id) {
621                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!(
622                    variances[param.index as usize],
623                    ty::Invariant,
624                    "precise captured param should be invariant"
625                );
626                continue;
627            }
628            // If a param is shadowed by a early-bound (duplicated) lifetime, then
629            // it may or may not be captured as invariant, depending on if it shows
630            // up through `Self` or `T::Assoc` syntax.
631            if shadowed_captures.contains(&param.def_id) {
632                continue;
633            }
634
635            match param.kind {
636                ty::GenericParamDefKind::Lifetime => {
637                    let use_span = tcx.def_span(param.def_id);
638                    let opaque_span = tcx.def_span(opaque_def_id);
639                    // Check if the lifetime param was captured but isn't named in the precise captures list.
640                    if variances[param.index as usize] == ty::Invariant {
641                        if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
642                            && let Some(def_id) = tcx
643                                .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
644                                .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
645                        {
646                            tcx.dcx().emit_err(errors::LifetimeNotCaptured {
647                                opaque_span,
648                                use_span,
649                                param_span: tcx.def_span(def_id),
650                            });
651                        } else {
652                            if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
653                                tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured {
654                                    opaque_span,
655                                    param_span: tcx.def_span(param.def_id),
656                                });
657                            } else {
658                                // If the `use_span` is actually just the param itself, then we must
659                                // have not duplicated the lifetime but captured the original.
660                                // The "effective" `use_span` will be the span of the opaque itself,
661                                // and the param span will be the def span of the param.
662                                tcx.dcx().emit_err(errors::LifetimeNotCaptured {
663                                    opaque_span,
664                                    use_span: opaque_span,
665                                    param_span: use_span,
666                                });
667                            }
668                        }
669                        continue;
670                    }
671                }
672                ty::GenericParamDefKind::Type { .. } => {
673                    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) {
674                        // FIXME(precise_capturing): Structured suggestion for this would be useful
675                        tcx.dcx().emit_err(errors::SelfTyNotCaptured {
676                            trait_span: tcx.def_span(param.def_id),
677                            opaque_span: tcx.def_span(opaque_def_id),
678                        });
679                    } else {
680                        // FIXME(precise_capturing): Structured suggestion for this would be useful
681                        tcx.dcx().emit_err(errors::ParamNotCaptured {
682                            param_span: tcx.def_span(param.def_id),
683                            opaque_span: tcx.def_span(opaque_def_id),
684                            kind: "type",
685                        });
686                    }
687                }
688                ty::GenericParamDefKind::Const { .. } => {
689                    // FIXME(precise_capturing): Structured suggestion for this would be useful
690                    tcx.dcx().emit_err(errors::ParamNotCaptured {
691                        param_span: tcx.def_span(param.def_id),
692                        opaque_span: tcx.def_span(opaque_def_id),
693                        kind: "const",
694                    });
695                }
696            }
697        }
698    }
699}
700
701fn is_enum_of_nonnullable_ptr<'tcx>(
702    tcx: TyCtxt<'tcx>,
703    adt_def: AdtDef<'tcx>,
704    args: GenericArgsRef<'tcx>,
705) -> bool {
706    if adt_def.repr().inhibit_enum_layout_opt() {
707        return false;
708    }
709
710    let [var_one, var_two] = &adt_def.variants().raw[..] else {
711        return false;
712    };
713    let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
714        return false;
715    };
716    #[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(..))
717}
718
719fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
720    if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
721        if match tcx.type_of(def_id).instantiate_identity().kind() {
722            ty::RawPtr(_, _) => false,
723            ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
724            _ => true,
725        } {
726            tcx.dcx().emit_err(errors::LinkageType { span: tcx.def_span(def_id) });
727        }
728    }
729}
730
731pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
732    let mut res = Ok(());
733    let generics = tcx.generics_of(def_id);
734
735    for param in &generics.own_params {
736        match param.kind {
737            ty::GenericParamDefKind::Lifetime { .. } => {}
738            ty::GenericParamDefKind::Type { has_default, .. } => {
739                if has_default {
740                    tcx.ensure_ok().type_of(param.def_id);
741                }
742            }
743            ty::GenericParamDefKind::Const { has_default, .. } => {
744                tcx.ensure_ok().type_of(param.def_id);
745                if has_default {
746                    // need to store default and type of default
747                    let ct = tcx.const_param_default(param.def_id).skip_binder();
748                    if let ty::ConstKind::Unevaluated(uv) = ct.kind() {
749                        tcx.ensure_ok().type_of(uv.def);
750                    }
751                }
752            }
753        }
754    }
755
756    match tcx.def_kind(def_id) {
757        DefKind::Static { .. } => {
758            tcx.ensure_ok().generics_of(def_id);
759            tcx.ensure_ok().type_of(def_id);
760            tcx.ensure_ok().predicates_of(def_id);
761
762            check_static_inhabited(tcx, def_id);
763            check_static_linkage(tcx, def_id);
764            let ty = tcx.type_of(def_id).instantiate_identity();
765            res = res.and(wfcheck::check_static_item(
766                tcx, def_id, ty, /* should_check_for_sync */ true,
767            ));
768
769            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
770            // checks. Returning early here does not miss any checks and
771            // avoids this query from having a direct dependency edge on the HIR
772            return res;
773        }
774        DefKind::Enum => {
775            tcx.ensure_ok().generics_of(def_id);
776            tcx.ensure_ok().type_of(def_id);
777            tcx.ensure_ok().predicates_of(def_id);
778            crate::collect::lower_enum_variant_types(tcx, def_id);
779            check_enum(tcx, def_id);
780            check_variances_for_type_defn(tcx, def_id);
781        }
782        DefKind::Fn => {
783            tcx.ensure_ok().generics_of(def_id);
784            tcx.ensure_ok().type_of(def_id);
785            tcx.ensure_ok().predicates_of(def_id);
786            tcx.ensure_ok().fn_sig(def_id);
787            tcx.ensure_ok().codegen_fn_attrs(def_id);
788            if let Some(i) = tcx.intrinsic(def_id) {
789                intrinsic::check_intrinsic_type(
790                    tcx,
791                    def_id,
792                    tcx.def_ident_span(def_id).unwrap(),
793                    i.name,
794                )
795            }
796        }
797        DefKind::Impl { of_trait } => {
798            tcx.ensure_ok().generics_of(def_id);
799            tcx.ensure_ok().type_of(def_id);
800            tcx.ensure_ok().predicates_of(def_id);
801            tcx.ensure_ok().associated_items(def_id);
802            check_diagnostic_attrs(tcx, def_id);
803            if of_trait {
804                let impl_trait_header = tcx.impl_trait_header(def_id);
805                res = res.and(
806                    tcx.ensure_ok()
807                        .coherent_trait(impl_trait_header.trait_ref.instantiate_identity().def_id),
808                );
809
810                if res.is_ok() {
811                    // Checking this only makes sense if the all trait impls satisfy basic
812                    // requirements (see `coherent_trait` query), otherwise
813                    // we run into infinite recursions a lot.
814                    check_impl_items_against_trait(tcx, def_id, impl_trait_header);
815                }
816            }
817        }
818        DefKind::Trait => {
819            tcx.ensure_ok().generics_of(def_id);
820            tcx.ensure_ok().trait_def(def_id);
821            tcx.ensure_ok().explicit_super_predicates_of(def_id);
822            tcx.ensure_ok().predicates_of(def_id);
823            tcx.ensure_ok().associated_items(def_id);
824            let assoc_items = tcx.associated_items(def_id);
825            check_diagnostic_attrs(tcx, def_id);
826
827            for &assoc_item in assoc_items.in_definition_order() {
828                match assoc_item.kind {
829                    ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {
830                        let trait_args = GenericArgs::identity_for_item(tcx, def_id);
831                        let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
832                            tcx,
833                            assoc_item,
834                            assoc_item,
835                            ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),
836                        );
837                    }
838                    _ => {}
839                }
840            }
841        }
842        DefKind::TraitAlias => {
843            tcx.ensure_ok().generics_of(def_id);
844            tcx.ensure_ok().explicit_implied_predicates_of(def_id);
845            tcx.ensure_ok().explicit_super_predicates_of(def_id);
846            tcx.ensure_ok().predicates_of(def_id);
847        }
848        def_kind @ (DefKind::Struct | DefKind::Union) => {
849            tcx.ensure_ok().generics_of(def_id);
850            tcx.ensure_ok().type_of(def_id);
851            tcx.ensure_ok().predicates_of(def_id);
852
853            let adt = tcx.adt_def(def_id).non_enum_variant();
854            for f in adt.fields.iter() {
855                tcx.ensure_ok().generics_of(f.did);
856                tcx.ensure_ok().type_of(f.did);
857                tcx.ensure_ok().predicates_of(f.did);
858            }
859
860            if let Some((_, ctor_def_id)) = adt.ctor {
861                crate::collect::lower_variant_ctor(tcx, ctor_def_id.expect_local());
862            }
863            match def_kind {
864                DefKind::Struct => check_struct(tcx, def_id),
865                DefKind::Union => check_union(tcx, def_id),
866                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
867            }
868            check_variances_for_type_defn(tcx, def_id);
869        }
870        DefKind::OpaqueTy => {
871            check_opaque_precise_captures(tcx, def_id);
872
873            let origin = tcx.local_opaque_ty_origin(def_id);
874            if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
875            | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin
876                && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
877                && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
878            {
879                // Skip opaques from RPIT in traits with no default body.
880            } else {
881                check_opaque(tcx, def_id);
882            }
883
884            tcx.ensure_ok().predicates_of(def_id);
885            tcx.ensure_ok().explicit_item_bounds(def_id);
886            tcx.ensure_ok().explicit_item_self_bounds(def_id);
887            if tcx.is_conditionally_const(def_id) {
888                tcx.ensure_ok().explicit_implied_const_bounds(def_id);
889                tcx.ensure_ok().const_conditions(def_id);
890            }
891
892            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
893            // checks. Returning early here does not miss any checks and
894            // avoids this query from having a direct dependency edge on the HIR
895            return res;
896        }
897        DefKind::Const => {
898            tcx.ensure_ok().generics_of(def_id);
899            tcx.ensure_ok().type_of(def_id);
900            tcx.ensure_ok().predicates_of(def_id);
901
902            res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
903                let ty = tcx.type_of(def_id).instantiate_identity();
904                let ty_span = tcx.ty_span(def_id);
905                let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
906                wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
907                wfcx.register_bound(
908                    traits::ObligationCause::new(
909                        ty_span,
910                        def_id,
911                        ObligationCauseCode::SizedConstOrStatic,
912                    ),
913                    tcx.param_env(def_id),
914                    ty,
915                    tcx.require_lang_item(LangItem::Sized, ty_span),
916                );
917                check_where_clauses(wfcx, def_id);
918
919                if {
    {
            'done:
                {
                for i in tcx.get_all_attrs(def_id) {
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AttributeKind::TypeConst(_)) =>
                            {
                            break 'done Some(());
                        }
                        _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(tcx.get_all_attrs(def_id), AttributeKind::TypeConst(_)) {
920                    wfcheck::check_type_const(wfcx, def_id, ty, true)?;
921                }
922                Ok(())
923            }));
924
925            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
926            // checks. Returning early here does not miss any checks and
927            // avoids this query from having a direct dependency edge on the HIR
928            return res;
929        }
930        DefKind::TyAlias => {
931            tcx.ensure_ok().generics_of(def_id);
932            tcx.ensure_ok().type_of(def_id);
933            tcx.ensure_ok().predicates_of(def_id);
934            check_type_alias_type_params_are_used(tcx, def_id);
935            if tcx.type_alias_is_lazy(def_id) {
936                res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
937                    let ty = tcx.type_of(def_id).instantiate_identity();
938                    let span = tcx.def_span(def_id);
939                    let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
940                    wfcx.register_wf_obligation(
941                        span,
942                        Some(WellFormedLoc::Ty(def_id)),
943                        item_ty.into(),
944                    );
945                    check_where_clauses(wfcx, def_id);
946                    Ok(())
947                }));
948                check_variances_for_type_defn(tcx, def_id);
949            }
950
951            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
952            // checks. Returning early here does not miss any checks and
953            // avoids this query from having a direct dependency edge on the HIR
954            return res;
955        }
956        DefKind::ForeignMod => {
957            let it = tcx.hir_expect_item(def_id);
958            let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
959                return Ok(());
960            };
961
962            check_abi(tcx, it.hir_id(), it.span, abi);
963
964            for &item in items {
965                let def_id = item.owner_id.def_id;
966
967                let generics = tcx.generics_of(def_id);
968                let own_counts = generics.own_counts();
969                if generics.own_params.len() - own_counts.lifetimes != 0 {
970                    let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
971                        (_, 0) => ("type", "types", Some("u32")),
972                        // We don't specify an example value, because we can't generate
973                        // a valid value for any type.
974                        (0, _) => ("const", "consts", None),
975                        _ => ("type or const", "types or consts", None),
976                    };
977                    let name =
978                        if {
    {
            'done:
                {
                for i in tcx.get_all_attrs(def_id) {
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AttributeKind::EiiForeignItem)
                            => {
                            break 'done Some(());
                        }
                        _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(tcx.get_all_attrs(def_id), AttributeKind::EiiForeignItem) {
979                            "externally implementable items"
980                        } else {
981                            "foreign items"
982                        };
983
984                    let span = tcx.def_span(def_id);
985                    {
    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!(
986                        tcx.dcx(),
987                        span,
988                        E0044,
989                        "{name} may not have {kinds} parameters",
990                    )
991                    .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"))
992                    .with_help(
993                        // FIXME: once we start storing spans for type arguments, turn this
994                        // into a suggestion.
995                        ::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!(
996                            "replace the {} parameters with concrete {}{}",
997                            kinds,
998                            kinds_pl,
999                            egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
1000                        ),
1001                    )
1002                    .emit();
1003                }
1004
1005                tcx.ensure_ok().generics_of(def_id);
1006                tcx.ensure_ok().type_of(def_id);
1007                tcx.ensure_ok().predicates_of(def_id);
1008                if tcx.is_conditionally_const(def_id) {
1009                    tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1010                    tcx.ensure_ok().const_conditions(def_id);
1011                }
1012                match tcx.def_kind(def_id) {
1013                    DefKind::Fn => {
1014                        tcx.ensure_ok().codegen_fn_attrs(def_id);
1015                        tcx.ensure_ok().fn_sig(def_id);
1016                        let item = tcx.hir_foreign_item(item);
1017                        let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
1018                        check_c_variadic_abi(tcx, sig.decl, abi, item.span);
1019                    }
1020                    DefKind::Static { .. } => {
1021                        tcx.ensure_ok().codegen_fn_attrs(def_id);
1022                    }
1023                    _ => (),
1024                }
1025            }
1026        }
1027        DefKind::Closure => {
1028            // This is guaranteed to be called by metadata encoding,
1029            // we still call it in wfcheck eagerly to ensure errors in codegen
1030            // attrs prevent lints from spamming the output.
1031            tcx.ensure_ok().codegen_fn_attrs(def_id);
1032            // We do not call `type_of` for closures here as that
1033            // depends on typecheck and would therefore hide
1034            // any further errors in case one typeck fails.
1035
1036            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1037            // checks. Returning early here does not miss any checks and
1038            // avoids this query from having a direct dependency edge on the HIR
1039            return res;
1040        }
1041        DefKind::AssocFn => {
1042            tcx.ensure_ok().codegen_fn_attrs(def_id);
1043            tcx.ensure_ok().type_of(def_id);
1044            tcx.ensure_ok().fn_sig(def_id);
1045            tcx.ensure_ok().predicates_of(def_id);
1046            res = res.and(check_associated_item(tcx, def_id));
1047            let assoc_item = tcx.associated_item(def_id);
1048            match assoc_item.container {
1049                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1050                ty::AssocContainer::Trait => {
1051                    res = res.and(check_trait_item(tcx, def_id));
1052                }
1053            }
1054
1055            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1056            // checks. Returning early here does not miss any checks and
1057            // avoids this query from having a direct dependency edge on the HIR
1058            return res;
1059        }
1060        DefKind::AssocConst => {
1061            tcx.ensure_ok().type_of(def_id);
1062            tcx.ensure_ok().predicates_of(def_id);
1063            res = res.and(check_associated_item(tcx, def_id));
1064            let assoc_item = tcx.associated_item(def_id);
1065            match assoc_item.container {
1066                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1067                ty::AssocContainer::Trait => {
1068                    res = res.and(check_trait_item(tcx, def_id));
1069                }
1070            }
1071
1072            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1073            // checks. Returning early here does not miss any checks and
1074            // avoids this query from having a direct dependency edge on the HIR
1075            return res;
1076        }
1077        DefKind::AssocTy => {
1078            tcx.ensure_ok().predicates_of(def_id);
1079            res = res.and(check_associated_item(tcx, def_id));
1080
1081            let assoc_item = tcx.associated_item(def_id);
1082            let has_type = match assoc_item.container {
1083                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1084                ty::AssocContainer::Trait => {
1085                    tcx.ensure_ok().explicit_item_bounds(def_id);
1086                    tcx.ensure_ok().explicit_item_self_bounds(def_id);
1087                    if tcx.is_conditionally_const(def_id) {
1088                        tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1089                        tcx.ensure_ok().const_conditions(def_id);
1090                    }
1091                    res = res.and(check_trait_item(tcx, def_id));
1092                    assoc_item.defaultness(tcx).has_value()
1093                }
1094            };
1095            if has_type {
1096                tcx.ensure_ok().type_of(def_id);
1097            }
1098
1099            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1100            // checks. Returning early here does not miss any checks and
1101            // avoids this query from having a direct dependency edge on the HIR
1102            return res;
1103        }
1104
1105        // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1106        // checks. Returning early here does not miss any checks and
1107        // avoids this query from having a direct dependency edge on the HIR
1108        DefKind::AnonConst | DefKind::InlineConst => return res,
1109        _ => {}
1110    }
1111    let node = tcx.hir_node_by_def_id(def_id);
1112    res.and(match node {
1113        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"),
1114        hir::Node::Item(item) => wfcheck::check_item(tcx, item),
1115        hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),
1116        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{0:?}", node)));
}unreachable!("{node:?}"),
1117    })
1118}
1119
1120pub(super) fn check_diagnostic_attrs(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1121    // an error would be reported if this fails.
1122    let _ = OnUnimplementedDirective::of_item(tcx, def_id.to_def_id());
1123}
1124
1125pub(super) fn check_specialization_validity<'tcx>(
1126    tcx: TyCtxt<'tcx>,
1127    trait_def: &ty::TraitDef,
1128    trait_item: ty::AssocItem,
1129    impl_id: DefId,
1130    impl_item: DefId,
1131) {
1132    let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
1133    let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
1134        if parent.is_from_trait() {
1135            None
1136        } else {
1137            Some((parent, parent.item(tcx, trait_item.def_id)))
1138        }
1139    });
1140
1141    let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1142        match parent_item {
1143            // Parent impl exists, and contains the parent item we're trying to specialize, but
1144            // doesn't mark it `default`.
1145            Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
1146                Some(Err(parent_impl.def_id()))
1147            }
1148
1149            // Parent impl contains item and makes it specializable.
1150            Some(_) => Some(Ok(())),
1151
1152            // Parent impl doesn't mention the item. This means it's inherited from the
1153            // grandparent. In that case, if parent is a `default impl`, inherited items use the
1154            // "defaultness" from the grandparent, else they are final.
1155            None => {
1156                if tcx.defaultness(parent_impl.def_id()).is_default() {
1157                    None
1158                } else {
1159                    Some(Err(parent_impl.def_id()))
1160                }
1161            }
1162        }
1163    });
1164
1165    // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
1166    // item. This is allowed, the item isn't actually getting specialized here.
1167    let result = opt_result.unwrap_or(Ok(()));
1168
1169    if let Err(parent_impl) = result {
1170        if !tcx.is_impl_trait_in_trait(impl_item) {
1171            report_forbidden_specialization(tcx, impl_item, parent_impl);
1172        } else {
1173            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"));
1174        }
1175    }
1176}
1177
1178fn check_impl_items_against_trait<'tcx>(
1179    tcx: TyCtxt<'tcx>,
1180    impl_id: LocalDefId,
1181    impl_trait_header: ty::ImplTraitHeader<'tcx>,
1182) {
1183    let trait_ref = impl_trait_header.trait_ref.instantiate_identity();
1184    // If the trait reference itself is erroneous (so the compilation is going
1185    // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1186    // isn't populated for such impls.
1187    if trait_ref.references_error() {
1188        return;
1189    }
1190
1191    let impl_item_refs = tcx.associated_item_def_ids(impl_id);
1192
1193    // Negative impls are not expected to have any items
1194    match impl_trait_header.polarity {
1195        ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
1196        ty::ImplPolarity::Negative => {
1197            if let [first_item_ref, ..] = impl_item_refs {
1198                let first_item_span = tcx.def_span(first_item_ref);
1199                {
    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!(
1200                    tcx.dcx(),
1201                    first_item_span,
1202                    E0749,
1203                    "negative impls cannot have any items"
1204                )
1205                .emit();
1206            }
1207            return;
1208        }
1209    }
1210
1211    let trait_def = tcx.trait_def(trait_ref.def_id);
1212
1213    let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
1214
1215    for &impl_item in impl_item_refs {
1216        let ty_impl_item = tcx.associated_item(impl_item);
1217        let ty_trait_item = match ty_impl_item.expect_trait_impl() {
1218            Ok(trait_item_id) => tcx.associated_item(trait_item_id),
1219            Err(ErrorGuaranteed { .. }) => continue,
1220        };
1221
1222        let res = tcx.ensure_ok().compare_impl_item(impl_item.expect_local());
1223
1224        if res.is_ok() {
1225            match ty_impl_item.kind {
1226                ty::AssocKind::Fn { .. } => {
1227                    compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1228                        tcx,
1229                        ty_impl_item,
1230                        ty_trait_item,
1231                        tcx.impl_trait_ref(ty_impl_item.container_id(tcx)).instantiate_identity(),
1232                    );
1233                }
1234                ty::AssocKind::Const { .. } => {}
1235                ty::AssocKind::Type { .. } => {}
1236            }
1237        }
1238
1239        if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1240            tcx.emit_node_span_lint(
1241                rustc_lint_defs::builtin::DEAD_CODE,
1242                tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1243                tcx.def_span(ty_impl_item.def_id),
1244                errors::UselessImplItem,
1245            )
1246        }
1247
1248        check_specialization_validity(
1249            tcx,
1250            trait_def,
1251            ty_trait_item,
1252            impl_id.to_def_id(),
1253            impl_item,
1254        );
1255    }
1256
1257    if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1258        // Check for missing items from trait
1259        let mut missing_items = Vec::new();
1260
1261        let mut must_implement_one_of: Option<&[Ident]> =
1262            trait_def.must_implement_one_of.as_deref();
1263
1264        for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1265            let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1266
1267            let is_implemented = leaf_def
1268                .as_ref()
1269                .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1270
1271            if !is_implemented
1272                && tcx.defaultness(impl_id).is_final()
1273                // unsized types don't need to implement methods that have `Self: Sized` bounds.
1274                && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1275            {
1276                missing_items.push(tcx.associated_item(trait_item_id));
1277            }
1278
1279            // true if this item is specifically implemented in this impl
1280            let is_implemented_here =
1281                leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1282
1283            if !is_implemented_here {
1284                let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1285                match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1286                    EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1287                        tcx,
1288                        full_impl_span,
1289                        trait_item_id,
1290                        feature,
1291                        reason,
1292                        issue,
1293                    ),
1294
1295                    // Unmarked default bodies are considered stable (at least for now).
1296                    EvalResult::Allow | EvalResult::Unmarked => {}
1297                }
1298            }
1299
1300            if let Some(required_items) = &must_implement_one_of {
1301                if is_implemented_here {
1302                    let trait_item = tcx.associated_item(trait_item_id);
1303                    if required_items.contains(&trait_item.ident(tcx)) {
1304                        must_implement_one_of = None;
1305                    }
1306                }
1307            }
1308
1309            if let Some(leaf_def) = &leaf_def
1310                && !leaf_def.is_final()
1311                && let def_id = leaf_def.item.def_id
1312                && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1313            {
1314                let def_kind = tcx.def_kind(def_id);
1315                let descr = tcx.def_kind_descr(def_kind, def_id);
1316                let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1317                    (
1318                        ::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"),
1319                        "async functions in traits",
1320                    )
1321                } else {
1322                    (
1323                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} with return-position `impl Trait` in trait cannot be specialized",
                descr))
    })format!(
1324                            "{descr} with return-position `impl Trait` in trait cannot be specialized"
1325                        ),
1326                        "return position `impl Trait` in traits",
1327                    )
1328                };
1329                tcx.dcx()
1330                    .struct_span_err(tcx.def_span(def_id), msg)
1331                    .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!(
1332                        "specialization behaves in inconsistent and surprising ways with \
1333                        {feature}, and for now is disallowed"
1334                    ))
1335                    .emit();
1336            }
1337        }
1338
1339        if !missing_items.is_empty() {
1340            let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1341            missing_items_err(tcx, impl_id, &missing_items, full_impl_span);
1342        }
1343
1344        if let Some(missing_items) = must_implement_one_of {
1345            let attr_span = {
    'done:
        {
        for i in tcx.get_all_attrs(trait_ref.def_id) {
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(AttributeKind::RustcMustImplementOneOf {
                    attr_span, .. }) => {
                    break 'done Some(*attr_span);
                }
                _ => {}
            }
        }
        None
    }
}find_attr!(tcx.get_all_attrs(trait_ref.def_id), AttributeKind::RustcMustImplementOneOf {attr_span, ..} => *attr_span);
1346
1347            missing_items_must_implement_one_of_err(
1348                tcx,
1349                tcx.def_span(impl_id),
1350                missing_items,
1351                attr_span,
1352            );
1353        }
1354    }
1355}
1356
1357fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1358    let t = tcx.type_of(def_id).instantiate_identity();
1359    if let ty::Adt(def, args) = t.kind()
1360        && def.is_struct()
1361    {
1362        let fields = &def.non_enum_variant().fields;
1363        if fields.is_empty() {
1364            {
    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();
1365            return;
1366        }
1367
1368        let array_field = &fields[FieldIdx::ZERO];
1369        let array_ty = array_field.ty(tcx, args);
1370        let ty::Array(element_ty, len_const) = array_ty.kind() else {
1371            {
    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!(
1372                tcx.dcx(),
1373                sp,
1374                E0076,
1375                "SIMD vector's only field must be an array"
1376            )
1377            .with_span_label(tcx.def_span(array_field.did), "not an array")
1378            .emit();
1379            return;
1380        };
1381
1382        if let Some(second_field) = fields.get(FieldIdx::ONE) {
1383            {
    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")
1384                .with_span_label(tcx.def_span(second_field.did), "excess field")
1385                .emit();
1386            return;
1387        }
1388
1389        // FIXME(repr_simd): This check is nice, but perhaps unnecessary due to the fact
1390        // we do not expect users to implement their own `repr(simd)` types. If they could,
1391        // this check is easily side-steppable by hiding the const behind normalization.
1392        // The consequence is that the error is, in general, only observable post-mono.
1393        if let Some(len) = len_const.try_to_target_usize(tcx) {
1394            if len == 0 {
1395                {
    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();
1396                return;
1397            } else if len > MAX_SIMD_LANES {
1398                {
    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!(
1399                    tcx.dcx(),
1400                    sp,
1401                    E0075,
1402                    "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1403                )
1404                .emit();
1405                return;
1406            }
1407        }
1408
1409        // Check that we use types valid for use in the lanes of a SIMD "vector register"
1410        // These are scalar types which directly match a "machine" type
1411        // Yes: Integers, floats, "thin" pointers
1412        // No: char, "wide" pointers, compound types
1413        match element_ty.kind() {
1414            ty::Param(_) => (), // pass struct<T>([T; 4]) through, let monomorphization catch errors
1415            ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), // struct([u8; 4]) is ok
1416            _ => {
1417                {
    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!(
1418                    tcx.dcx(),
1419                    sp,
1420                    E0077,
1421                    "SIMD vector element type should be a \
1422                        primitive scalar (integer/float/pointer) type"
1423                )
1424                .emit();
1425                return;
1426            }
1427        }
1428    }
1429}
1430
1431#[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(1431u32),
                                    ::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")]
1432fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalable: ScalableElt) {
1433    let ty = tcx.type_of(def_id).instantiate_identity();
1434    let ty::Adt(def, args) = ty.kind() else { return };
1435    if !def.is_struct() {
1436        tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");
1437        return;
1438    }
1439
1440    let fields = &def.non_enum_variant().fields;
1441    match scalable {
1442        ScalableElt::ElementCount(..) if fields.is_empty() => {
1443            let mut err =
1444                tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");
1445            err.help("scalable vector types' only field must be a primitive scalar type");
1446            err.emit();
1447            return;
1448        }
1449        ScalableElt::ElementCount(..) if fields.len() >= 2 => {
1450            tcx.dcx().struct_span_err(span, "scalable vectors cannot have multiple fields").emit();
1451            return;
1452        }
1453        ScalableElt::Container if fields.is_empty() => {
1454            let mut err =
1455                tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");
1456            err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1457            err.emit();
1458            return;
1459        }
1460        _ => {}
1461    }
1462
1463    match scalable {
1464        ScalableElt::ElementCount(..) => {
1465            let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args);
1466
1467            // Check that `element_ty` only uses types valid in the lanes of a scalable vector
1468            // register: scalar types which directly match a "machine" type - integers, floats and
1469            // bools
1470            match element_ty.kind() {
1471                ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Bool => (),
1472                _ => {
1473                    let mut err = tcx.dcx().struct_span_err(
1474                        span,
1475                        "element type of a scalable vector must be a primitive scalar",
1476                    );
1477                    err.help("only `u*`, `i*`, `f*` and `bool` types are accepted");
1478                    err.emit();
1479                }
1480            }
1481        }
1482        ScalableElt::Container => {
1483            let mut prev_field_ty = None;
1484            for field in fields.iter() {
1485                let element_ty = field.ty(tcx, args);
1486                if let ty::Adt(def, _) = element_ty.kind()
1487                    && def.repr().scalable()
1488                {
1489                    match def
1490                        .repr()
1491                        .scalable
1492                        .expect("`repr().scalable.is_some()` != `repr().scalable()`")
1493                    {
1494                        ScalableElt::ElementCount(_) => { /* expected field */ }
1495                        ScalableElt::Container => {
1496                            tcx.dcx().span_err(
1497                                tcx.def_span(field.did),
1498                                "scalable vector structs cannot contain other scalable vector structs",
1499                            );
1500                            break;
1501                        }
1502                    }
1503                } else {
1504                    tcx.dcx().span_err(
1505                        tcx.def_span(field.did),
1506                        "scalable vector structs can only have scalable vector fields",
1507                    );
1508                    break;
1509                }
1510
1511                if let Some(prev_ty) = prev_field_ty.replace(element_ty)
1512                    && prev_ty != element_ty
1513                {
1514                    tcx.dcx().span_err(
1515                        tcx.def_span(field.did),
1516                        "all fields in a scalable vector struct must be the same type",
1517                    );
1518                    break;
1519                }
1520            }
1521        }
1522    }
1523}
1524
1525pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1526    let repr = def.repr();
1527    if repr.packed() {
1528        if let Some(reprs) = {
    'done:
        {
        for i in tcx.get_all_attrs(def.did()) {
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(attrs::AttributeKind::Repr {
                    reprs, .. }) => {
                    break 'done Some(reprs);
                }
                _ => {}
            }
        }
        None
    }
}find_attr!(tcx.get_all_attrs(def.did()), attrs::AttributeKind::Repr { reprs, .. } => reprs)
1529        {
1530            for (r, _) in reprs {
1531                if let ReprPacked(pack) = r
1532                    && let Some(repr_pack) = repr.pack
1533                    && pack != &repr_pack
1534                {
1535                    {
    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!(
1536                        tcx.dcx(),
1537                        sp,
1538                        E0634,
1539                        "type has conflicting packed representation hints"
1540                    )
1541                    .emit();
1542                }
1543            }
1544        }
1545        if repr.align.is_some() {
1546            {
    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!(
1547                tcx.dcx(),
1548                sp,
1549                E0587,
1550                "type has conflicting packed and align representation hints"
1551            )
1552            .emit();
1553        } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut ::alloc::vec::Vec::new()vec![]) {
1554            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!(
1555                tcx.dcx(),
1556                sp,
1557                E0588,
1558                "packed type cannot transitively contain a `#[repr(align)]` type"
1559            );
1560
1561            err.span_note(
1562                tcx.def_span(def_spans[0].0),
1563                ::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)),
1564            );
1565
1566            if def_spans.len() > 2 {
1567                let mut first = true;
1568                for (adt_def, span) in def_spans.iter().skip(1).rev() {
1569                    let ident = tcx.item_name(*adt_def);
1570                    err.span_note(
1571                        *span,
1572                        if first {
1573                            ::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!(
1574                                "`{}` contains a field of type `{}`",
1575                                tcx.type_of(def.did()).instantiate_identity(),
1576                                ident
1577                            )
1578                        } else {
1579                            ::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}`")
1580                        },
1581                    );
1582                    first = false;
1583                }
1584            }
1585
1586            err.emit();
1587        }
1588    }
1589}
1590
1591pub(super) fn check_packed_inner(
1592    tcx: TyCtxt<'_>,
1593    def_id: DefId,
1594    stack: &mut Vec<DefId>,
1595) -> Option<Vec<(DefId, Span)>> {
1596    if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().kind() {
1597        if def.is_struct() || def.is_union() {
1598            if def.repr().align.is_some() {
1599                return Some(<[_]>::into_vec(::alloc::boxed::box_new([(def.did(), DUMMY_SP)]))vec![(def.did(), DUMMY_SP)]);
1600            }
1601
1602            stack.push(def_id);
1603            for field in &def.non_enum_variant().fields {
1604                if let ty::Adt(def, _) = field.ty(tcx, args).kind()
1605                    && !stack.contains(&def.did())
1606                    && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1607                {
1608                    defs.push((def.did(), field.ident(tcx).span));
1609                    return Some(defs);
1610                }
1611            }
1612            stack.pop();
1613        }
1614    }
1615
1616    None
1617}
1618
1619pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1620    if !adt.repr().transparent() {
1621        return;
1622    }
1623
1624    if adt.is_union() && !tcx.features().transparent_unions() {
1625        feature_err(
1626            &tcx.sess,
1627            sym::transparent_unions,
1628            tcx.def_span(adt.did()),
1629            "transparent unions are unstable",
1630        )
1631        .emit();
1632    }
1633
1634    if adt.variants().len() != 1 {
1635        bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1636        // Don't bother checking the fields.
1637        return;
1638    }
1639
1640    let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
1641    // For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1642    struct FieldInfo<'tcx> {
1643        span: Span,
1644        trivial: bool,
1645        ty: Ty<'tcx>,
1646    }
1647
1648    let field_infos = adt.all_fields().map(|field| {
1649        let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did));
1650        let layout = tcx.layout_of(typing_env.as_query_input(ty));
1651        // We are currently checking the type this field came from, so it must be local
1652        let span = tcx.hir_span_if_local(field.did).unwrap();
1653        let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1654        FieldInfo { span, trivial, ty }
1655    });
1656
1657    let non_trivial_fields = field_infos
1658        .clone()
1659        .filter_map(|field| if !field.trivial { Some(field.span) } else { None });
1660    let non_trivial_count = non_trivial_fields.clone().count();
1661    if non_trivial_count >= 2 {
1662        bad_non_zero_sized_fields(
1663            tcx,
1664            adt,
1665            non_trivial_count,
1666            non_trivial_fields,
1667            tcx.def_span(adt.did()),
1668        );
1669        return;
1670    }
1671
1672    // Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1673    // fields or `repr(C)`. We call those fields "unsuited".
1674    struct UnsuitedInfo<'tcx> {
1675        /// The source of the problem, a type that is found somewhere within the field type.
1676        ty: Ty<'tcx>,
1677        reason: UnsuitedReason,
1678    }
1679    enum UnsuitedReason {
1680        NonExhaustive,
1681        PrivateField,
1682        ReprC,
1683    }
1684
1685    fn check_unsuited<'tcx>(
1686        tcx: TyCtxt<'tcx>,
1687        typing_env: ty::TypingEnv<'tcx>,
1688        ty: Ty<'tcx>,
1689    ) -> ControlFlow<UnsuitedInfo<'tcx>> {
1690        // We can encounter projections during traversal, so ensure the type is normalized.
1691        let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1692        match ty.kind() {
1693            ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1694            ty::Array(ty, _) => check_unsuited(tcx, typing_env, *ty),
1695            ty::Adt(def, args) => {
1696                if !def.did().is_local()
1697                    && !{
    {
            'done:
                {
                for i in tcx.get_all_attrs(def.did()) {
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AttributeKind::PubTransparent(_))
                            => {
                            break 'done Some(());
                        }
                        _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(tcx.get_all_attrs(def.did()), AttributeKind::PubTransparent(_))
1698                {
1699                    let non_exhaustive = def.is_variant_list_non_exhaustive()
1700                        || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1701                    let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1702                    if non_exhaustive || has_priv {
1703                        return ControlFlow::Break(UnsuitedInfo {
1704                            ty,
1705                            reason: if non_exhaustive {
1706                                UnsuitedReason::NonExhaustive
1707                            } else {
1708                                UnsuitedReason::PrivateField
1709                            },
1710                        });
1711                    }
1712                }
1713                if def.repr().c() {
1714                    return ControlFlow::Break(UnsuitedInfo { ty, reason: UnsuitedReason::ReprC });
1715                }
1716                def.all_fields()
1717                    .map(|field| field.ty(tcx, args))
1718                    .try_for_each(|t| check_unsuited(tcx, typing_env, t))
1719            }
1720            _ => ControlFlow::Continue(()),
1721        }
1722    }
1723
1724    let mut prev_unsuited_1zst = false;
1725    for field in field_infos {
1726        if field.trivial
1727            && let Some(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1728        {
1729            // If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
1730            // Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
1731            if non_trivial_count > 0 || prev_unsuited_1zst {
1732                tcx.node_span_lint(
1733                    REPR_TRANSPARENT_NON_ZST_FIELDS,
1734                    tcx.local_def_id_to_hir_id(adt.did().expect_local()),
1735                    field.span,
1736                    |lint| {
1737                        let title = match unsuited.reason {
1738                            UnsuitedReason::NonExhaustive => "external non-exhaustive types",
1739                            UnsuitedReason::PrivateField => "external types with private fields",
1740                            UnsuitedReason::ReprC => "`repr(C)` types",
1741                        };
1742                        lint.primary_message(
1743                            ::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}"),
1744                        );
1745                        let note = match unsuited.reason {
1746                            UnsuitedReason::NonExhaustive => "is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future.",
1747                            UnsuitedReason::PrivateField => "contains private fields, so it could become non-zero-sized in the future.",
1748                            UnsuitedReason::ReprC => "is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets.",
1749                        };
1750                        lint.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this field contains `{0}`, which {1}",
                unsuited.ty, note))
    })format!(
1751                            "this field contains `{field_ty}`, which {note}",
1752                            field_ty = unsuited.ty,
1753                        ));
1754                    },
1755                );
1756            } else {
1757                prev_unsuited_1zst = true;
1758            }
1759        }
1760    }
1761}
1762
1763#[allow(trivial_numeric_casts)]
1764fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1765    let def = tcx.adt_def(def_id);
1766    def.destructor(tcx); // force the destructor to be evaluated
1767
1768    if def.variants().is_empty() {
1769        {
    'done:
        {
        for i in tcx.get_all_attrs(def_id) {
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(attrs::AttributeKind::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();
                            });
                }
                _ => {}
            }
        }
        None
    }
};find_attr!(
1770            tcx.get_all_attrs(def_id),
1771            attrs::AttributeKind::Repr { reprs, first_span } => {
1772                struct_span_code_err!(
1773                    tcx.dcx(),
1774                    reprs.first().map(|repr| repr.1).unwrap_or(*first_span),
1775                    E0084,
1776                    "unsupported representation for zero-variant enum"
1777                )
1778                .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1779                .emit();
1780            }
1781        );
1782    }
1783
1784    for v in def.variants() {
1785        if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1786            tcx.ensure_ok().typeck(discr_def_id.expect_local());
1787        }
1788    }
1789
1790    if def.repr().int.is_none() {
1791        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));
1792        let get_disr = |var: &ty::VariantDef| match var.discr {
1793            ty::VariantDiscr::Explicit(disr) => Some(disr),
1794            ty::VariantDiscr::Relative(_) => None,
1795        };
1796
1797        let non_unit = def.variants().iter().find(|var| !is_unit(var));
1798        let disr_unit =
1799            def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var));
1800        let disr_non_unit =
1801            def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var));
1802
1803        if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) {
1804            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!(
1805                tcx.dcx(),
1806                tcx.def_span(def_id),
1807                E0732,
1808                "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"
1809            );
1810            if let Some(disr_non_unit) = disr_non_unit {
1811                err.span_label(
1812                    tcx.def_span(disr_non_unit),
1813                    "explicit discriminant on non-unit variant specified here",
1814                );
1815            } else {
1816                err.span_label(
1817                    tcx.def_span(disr_unit.unwrap()),
1818                    "explicit discriminant specified here",
1819                );
1820                err.span_label(
1821                    tcx.def_span(non_unit.unwrap().def_id),
1822                    "non-unit discriminant declared here",
1823                );
1824            }
1825            err.emit();
1826        }
1827    }
1828
1829    detect_discriminant_duplicate(tcx, def);
1830    check_transparent(tcx, def);
1831}
1832
1833/// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1834fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1835    // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1836    // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1837    let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1838        let var = adt.variant(idx); // HIR for the duplicate discriminant
1839        let (span, display_discr) = match var.discr {
1840            ty::VariantDiscr::Explicit(discr_def_id) => {
1841                // In the case the discriminant is both a duplicate and overflowed, let the user know
1842                if let hir::Node::AnonConst(expr) =
1843                    tcx.hir_node_by_def_id(discr_def_id.expect_local())
1844                    && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1845                    && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1846                    && *lit_value != dis.val
1847                {
1848                    (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}`)"))
1849                } else {
1850                    // Otherwise, format the value as-is
1851                    (tcx.def_span(discr_def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", dis))
    })format!("`{dis}`"))
1852                }
1853            }
1854            // This should not happen.
1855            ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", dis))
    })format!("`{dis}`")),
1856            ty::VariantDiscr::Relative(distance_to_explicit) => {
1857                // At this point we know this discriminant is a duplicate, and was not explicitly
1858                // assigned by the user. Here we iterate backwards to fetch the HIR for the last
1859                // explicitly assigned discriminant, and letting the user know that this was the
1860                // increment startpoint, and how many steps from there leading to the duplicate
1861                if let Some(explicit_idx) =
1862                    idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1863                {
1864                    let explicit_variant = adt.variant(explicit_idx);
1865                    let ve_ident = var.name;
1866                    let ex_ident = explicit_variant.name;
1867                    let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1868
1869                    err.span_label(
1870                        tcx.def_span(explicit_variant.def_id),
1871                        ::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!(
1872                            "discriminant for `{ve_ident}` incremented from this startpoint \
1873                            (`{ex_ident}` + {distance_to_explicit} {sp} later \
1874                             => `{ve_ident}` = {dis})"
1875                        ),
1876                    );
1877                }
1878
1879                (tcx.def_span(var.def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", dis))
    })format!("`{dis}`"))
1880            }
1881        };
1882
1883        err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} assigned here", display_discr))
    })format!("{display_discr} assigned here"));
1884    };
1885
1886    let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1887
1888    // Here we loop through the discriminants, comparing each discriminant to another.
1889    // When a duplicate is detected, we instantiate an error and point to both
1890    // initial and duplicate value. The duplicate discriminant is then discarded by swapping
1891    // it with the last element and decrementing the `vec.len` (which is why we have to evaluate
1892    // `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
1893    // style as we are mutating `discrs` on the fly).
1894    let mut i = 0;
1895    while i < discrs.len() {
1896        let var_i_idx = discrs[i].0;
1897        let mut error: Option<Diag<'_, _>> = None;
1898
1899        let mut o = i + 1;
1900        while o < discrs.len() {
1901            let var_o_idx = discrs[o].0;
1902
1903            if discrs[i].1.val == discrs[o].1.val {
1904                let err = error.get_or_insert_with(|| {
1905                    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!(
1906                        tcx.dcx(),
1907                        tcx.def_span(adt.did()),
1908                        E0081,
1909                        "discriminant value `{}` assigned more than once",
1910                        discrs[i].1,
1911                    );
1912
1913                    report(discrs[i].1, var_i_idx, &mut ret);
1914
1915                    ret
1916                });
1917
1918                report(discrs[o].1, var_o_idx, err);
1919
1920                // Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
1921                discrs[o] = *discrs.last().unwrap();
1922                discrs.pop();
1923            } else {
1924                o += 1;
1925            }
1926        }
1927
1928        if let Some(e) = error {
1929            e.emit();
1930        }
1931
1932        i += 1;
1933    }
1934}
1935
1936fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1937    if tcx.type_alias_is_lazy(def_id) {
1938        // Since we compute the variances for lazy type aliases and already reject bivariant
1939        // parameters as unused, we can and should skip this check for lazy type aliases.
1940        return;
1941    }
1942
1943    let generics = tcx.generics_of(def_id);
1944    if generics.own_counts().types == 0 {
1945        return;
1946    }
1947
1948    let ty = tcx.type_of(def_id).instantiate_identity();
1949    if ty.references_error() {
1950        // If there is already another error, do not emit an error for not using a type parameter.
1951        return;
1952    }
1953
1954    // Lazily calculated because it is only needed in case of an error.
1955    let bounded_params = LazyCell::new(|| {
1956        tcx.explicit_predicates_of(def_id)
1957            .predicates
1958            .iter()
1959            .filter_map(|(predicate, span)| {
1960                let bounded_ty = match predicate.kind().skip_binder() {
1961                    ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
1962                    ty::ClauseKind::TypeOutlives(pred) => pred.0,
1963                    _ => return None,
1964                };
1965                if let ty::Param(param) = bounded_ty.kind() {
1966                    Some((param.index, span))
1967                } else {
1968                    None
1969                }
1970            })
1971            // FIXME: This assumes that elaborated `Sized` bounds come first (which does hold at the
1972            // time of writing). This is a bit fragile since we later use the span to detect elaborated
1973            // `Sized` bounds. If they came last for example, this would break `Trait + /*elab*/Sized`
1974            // since it would overwrite the span of the user-written bound. This could be fixed by
1975            // folding the spans with `Span::to` which requires a bit of effort I think.
1976            .collect::<FxIndexMap<_, _>>()
1977    });
1978
1979    let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
1980    for leaf in ty.walk() {
1981        if let GenericArgKind::Type(leaf_ty) = leaf.kind()
1982            && let ty::Param(param) = leaf_ty.kind()
1983        {
1984            {
    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:1984",
                        "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(1984u32),
                        ::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);
1985            params_used.insert(param.index);
1986        }
1987    }
1988
1989    for param in &generics.own_params {
1990        if !params_used.contains(param.index)
1991            && let ty::GenericParamDefKind::Type { .. } = param.kind
1992        {
1993            let span = tcx.def_span(param.def_id);
1994            let param_name = Ident::new(param.name, span);
1995
1996            // The corresponding predicates are post-`Sized`-elaboration. Therefore we
1997            // * check for emptiness to detect lone user-written `?Sized` bounds
1998            // * compare the param span to the pred span to detect lone user-written `Sized` bounds
1999            let has_explicit_bounds = bounded_params.is_empty()
2000                || (*bounded_params).get(&param.index).is_some_and(|&&pred_sp| pred_sp != span);
2001            let const_param_help = !has_explicit_bounds;
2002
2003            let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2004                span,
2005                param_name,
2006                param_def_kind: tcx.def_descr(param.def_id),
2007                help: errors::UnusedGenericParameterHelp::TyAlias { param_name },
2008                usage_spans: ::alloc::vec::Vec::new()vec![],
2009                const_param_help,
2010            });
2011            diag.code(E0091);
2012            diag.emit();
2013        }
2014    }
2015}
2016
2017/// Emit an error for recursive opaque types.
2018///
2019/// If this is a return `impl Trait`, find the item's return expressions and point at them. For
2020/// direct recursion this is enough, but for indirect recursion also point at the last intermediary
2021/// `impl Trait`.
2022///
2023/// If all the return expressions evaluate to `!`, then we explain that the error will go away
2024/// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
2025fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
2026    let span = tcx.def_span(opaque_def_id);
2027    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");
2028
2029    let mut label = false;
2030    if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
2031        let typeck_results = tcx.typeck(def_id);
2032        if visitor
2033            .returns
2034            .iter()
2035            .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
2036            .all(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Never => true,
    _ => false,
}matches!(ty.kind(), ty::Never))
2037        {
2038            let spans = visitor
2039                .returns
2040                .iter()
2041                .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
2042                .map(|expr| expr.span)
2043                .collect::<Vec<Span>>();
2044            let span_len = spans.len();
2045            if span_len == 1 {
2046                err.span_label(spans[0], "this returned value is of `!` type");
2047            } else {
2048                let mut multispan: MultiSpan = spans.clone().into();
2049                for span in spans {
2050                    multispan.push_span_label(span, "this returned value is of `!` type");
2051                }
2052                err.span_note(multispan, "these returned values have a concrete \"never\" type");
2053            }
2054            err.help("this error will resolve once the item's body returns a concrete type");
2055        } else {
2056            let mut seen = FxHashSet::default();
2057            seen.insert(span);
2058            err.span_label(span, "recursive opaque type");
2059            label = true;
2060            for (sp, ty) in visitor
2061                .returns
2062                .iter()
2063                .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
2064                .filter(|(_, ty)| !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Never => true,
    _ => false,
}matches!(ty.kind(), ty::Never))
2065            {
2066                #[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)]
2067                struct OpaqueTypeCollector {
2068                    opaques: Vec<DefId>,
2069                    closures: Vec<DefId>,
2070                }
2071                impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
2072                    fn visit_ty(&mut self, t: Ty<'tcx>) {
2073                        match *t.kind() {
2074                            ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
2075                                self.opaques.push(def);
2076                            }
2077                            ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
2078                                self.closures.push(def_id);
2079                                t.super_visit_with(self);
2080                            }
2081                            _ => t.super_visit_with(self),
2082                        }
2083                    }
2084                }
2085
2086                let mut visitor = OpaqueTypeCollector::default();
2087                ty.visit_with(&mut visitor);
2088                for def_id in visitor.opaques {
2089                    let ty_span = tcx.def_span(def_id);
2090                    if !seen.contains(&ty_span) {
2091                        let descr = if ty.is_impl_trait() { "opaque " } else { "" };
2092                        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}`"));
2093                        seen.insert(ty_span);
2094                    }
2095                    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}`"));
2096                }
2097
2098                for closure_def_id in visitor.closures {
2099                    let Some(closure_local_did) = closure_def_id.as_local() else {
2100                        continue;
2101                    };
2102                    let typeck_results = tcx.typeck(closure_local_did);
2103
2104                    let mut label_match = |ty: Ty<'_>, span| {
2105                        for arg in ty.walk() {
2106                            if let ty::GenericArgKind::Type(ty) = arg.kind()
2107                                && let ty::Alias(
2108                                    ty::Opaque,
2109                                    ty::AliasTy { def_id: captured_def_id, .. },
2110                                ) = *ty.kind()
2111                                && captured_def_id == opaque_def_id.to_def_id()
2112                            {
2113                                err.span_label(
2114                                    span,
2115                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} captures itself here",
                tcx.def_descr(closure_def_id)))
    })format!(
2116                                        "{} captures itself here",
2117                                        tcx.def_descr(closure_def_id)
2118                                    ),
2119                                );
2120                            }
2121                        }
2122                    };
2123
2124                    // Label any closure upvars that capture the opaque
2125                    for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
2126                    {
2127                        label_match(capture.place.ty(), capture.get_path_span(tcx));
2128                    }
2129                    // Label any coroutine locals that capture the opaque
2130                    if tcx.is_coroutine(closure_def_id)
2131                        && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
2132                    {
2133                        for interior_ty in &coroutine_layout.field_tys {
2134                            label_match(interior_ty.ty, interior_ty.source_info.span);
2135                        }
2136                    }
2137                }
2138            }
2139        }
2140    }
2141    if !label {
2142        err.span_label(span, "cannot resolve opaque type");
2143    }
2144    err.emit()
2145}
2146
2147pub(super) fn check_coroutine_obligations(
2148    tcx: TyCtxt<'_>,
2149    def_id: LocalDefId,
2150) -> Result<(), ErrorGuaranteed> {
2151    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()));
2152
2153    let typeck_results = tcx.typeck(def_id);
2154    let param_env = tcx.param_env(def_id);
2155
2156    {
    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:2156",
                        "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(2156u32),
                        ::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);
2157
2158    let mode = if tcx.next_trait_solver_globally() {
2159        // This query is conceptually between HIR typeck and
2160        // MIR borrowck. We use the opaque types defined by HIR
2161        // and ignore region constraints.
2162        TypingMode::borrowck(tcx, def_id)
2163    } else {
2164        TypingMode::analysis_in_body(tcx, def_id)
2165    };
2166
2167    // Typeck writeback gives us predicates with their regions erased.
2168    // We only need to check the goals while ignoring lifetimes to give good
2169    // error message and to avoid breaking the assumption of `mir_borrowck`
2170    // that all obligations already hold modulo regions.
2171    let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
2172
2173    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2174    for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
2175        ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
2176    }
2177
2178    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2179    {
    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:2179",
                        "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(2179u32),
                        ::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);
2180    if !errors.is_empty() {
2181        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2182    }
2183
2184    if !tcx.next_trait_solver_globally() {
2185        // Check that any hidden types found when checking these stalled coroutine obligations
2186        // are valid.
2187        for (key, ty) in infcx.take_opaque_types() {
2188            let hidden_type = infcx.resolve_vars_if_possible(ty);
2189            let key = infcx.resolve_vars_if_possible(key);
2190            sanity_check_found_hidden_type(tcx, key, hidden_type)?;
2191        }
2192    } else {
2193        // We're not checking region constraints here, so we can simply drop the
2194        // added opaque type uses in `TypingMode::Borrowck`.
2195        let _ = infcx.take_opaque_types();
2196    }
2197
2198    Ok(())
2199}
2200
2201pub(super) fn check_potentially_region_dependent_goals<'tcx>(
2202    tcx: TyCtxt<'tcx>,
2203    def_id: LocalDefId,
2204) -> Result<(), ErrorGuaranteed> {
2205    if !tcx.next_trait_solver_globally() {
2206        return Ok(());
2207    }
2208    let typeck_results = tcx.typeck(def_id);
2209    let param_env = tcx.param_env(def_id);
2210
2211    // We use `TypingMode::Borrowck` as we want to use the opaque types computed by HIR typeck.
2212    let typing_mode = TypingMode::borrowck(tcx, def_id);
2213    let infcx = tcx.infer_ctxt().ignoring_regions().build(typing_mode);
2214    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2215    for (predicate, cause) in &typeck_results.potentially_region_dependent_goals {
2216        let predicate = fold_regions(tcx, *predicate, |_, _| {
2217            infcx.next_region_var(RegionVariableOrigin::Misc(cause.span))
2218        });
2219        ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate));
2220    }
2221
2222    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2223    {
    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:2223",
                        "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(2223u32),
                        ::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);
2224    if errors.is_empty() { Ok(()) } else { Err(infcx.err_ctxt().report_fulfillment_errors(errors)) }
2225}