Skip to main content

rustc_hir_analysis/check/
check.rs

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