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