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};
41
42fn add_abi_diag_help<T: EmissionGuarantee>(abi: ExternAbi, diag: &mut Diag<'_, T>) {
43    if let ExternAbi::Cdecl { unwind } = abi {
44        let c_abi = ExternAbi::C { unwind };
45        diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `extern {0}` instead", c_abi))
    })format!("use `extern {c_abi}` instead",));
46    } else if let ExternAbi::Stdcall { unwind } = abi {
47        let c_abi = ExternAbi::C { unwind };
48        let system_abi = ExternAbi::System { unwind };
49        diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you need `extern {0}` on win32 and `extern {1}` everywhere else, use `extern {2}`",
                abi, c_abi, system_abi))
    })format!(
50            "if you need `extern {abi}` on win32 and `extern {c_abi}` everywhere else, \
51                use `extern {system_abi}`"
52        ));
53    }
54}
55
56pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: ExternAbi) {
57    struct UnsupportedCallingConventions {
58        abi: ExternAbi,
59    }
60
61    impl<'a> Diagnostic<'a, ()> for UnsupportedCallingConventions {
62        fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
63            let Self { abi } = self;
64            let mut lint = Diag::new(
65                dcx,
66                level,
67                ::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"),
68            );
69            add_abi_diag_help(abi, &mut lint);
70            lint
71        }
72    }
73    // FIXME: This should be checked earlier, e.g. in `rustc_ast_lowering`, as this
74    // currently only guards function imports, function definitions, and function pointer types.
75    // Functions in trait declarations can still use "deprecated" ABIs without any warning.
76
77    match AbiMap::from_target(&tcx.sess.target).canonize_abi(abi, false) {
78        AbiMapping::Direct(..) => (),
79        // already erred in rustc_ast_lowering
80        AbiMapping::Invalid => {
81            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"));
82        }
83        AbiMapping::Deprecated(..) => {
84            tcx.emit_node_span_lint(
85                UNSUPPORTED_CALLING_CONVENTIONS,
86                hir_id,
87                span,
88                UnsupportedCallingConventions { abi },
89            );
90        }
91    }
92}
93
94pub fn check_custom_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, fn_sig: FnSig<'_>, fn_sig_span: Span) {
95    if fn_sig.abi() == ExternAbi::Custom {
96        // Function definitions that use `extern "custom"` must be naked functions.
97        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(_)) {
98            tcx.dcx().emit_err(crate::errors::AbiCustomClothedFunction {
99                span: fn_sig_span,
100                naked_span: tcx.def_span(def_id).shrink_to_lo(),
101            });
102        }
103    }
104}
105
106fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
107    let def = tcx.adt_def(def_id);
108    let span = tcx.def_span(def_id);
109    def.destructor(tcx); // force the destructor to be evaluated
110
111    if let Some(scalable) = def.repr().scalable {
112        check_scalable_vector(tcx, span, def_id, scalable);
113    } else if def.repr().simd() {
114        check_simd(tcx, span, def_id);
115    }
116
117    check_transparent(tcx, def);
118    check_packed(tcx, span, def);
119    check_type_defn(tcx, def_id, false)
120}
121
122fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
123    let def = tcx.adt_def(def_id);
124    let span = tcx.def_span(def_id);
125    def.destructor(tcx); // force the destructor to be evaluated
126    check_transparent(tcx, def);
127    check_union_fields(tcx, span, def_id);
128    check_packed(tcx, span, def);
129    check_type_defn(tcx, def_id, true)
130}
131
132fn allowed_union_or_unsafe_field<'tcx>(
133    tcx: TyCtxt<'tcx>,
134    ty: Ty<'tcx>,
135    typing_env: ty::TypingEnv<'tcx>,
136    span: Span,
137) -> bool {
138    // HACK (not that bad of a hack don't worry): Some codegen tests don't even define proper
139    // impls for `Copy`. Let's short-circuit here for this validity check, since a lot of them
140    // use unions. We should eventually fix all the tests to define that lang item or use
141    // minicore stubs.
142    if ty.is_trivially_pure_clone_copy() {
143        return true;
144    }
145    // If `BikeshedGuaranteedNoDrop` is not defined in a `#[no_core]` test, fall back to `Copy`.
146    // This is an underapproximation of `BikeshedGuaranteedNoDrop`,
147    let def_id = tcx
148        .lang_items()
149        .get(LangItem::BikeshedGuaranteedNoDrop)
150        .unwrap_or_else(|| tcx.require_lang_item(LangItem::Copy, span));
151    let Ok(ty) = tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)) else {
152        tcx.dcx().span_delayed_bug(span, "could not normalize field type");
153        return true;
154    };
155    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
156    infcx.predicate_must_hold_modulo_regions(&Obligation::new(
157        tcx,
158        ObligationCause::dummy_with_span(span),
159        param_env,
160        ty::TraitRef::new(tcx, def_id, [ty]),
161    ))
162}
163
164/// Check that the fields of the `union` do not need dropping.
165fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
166    let def = tcx.adt_def(item_def_id);
167    if !def.is_union() {
    ::core::panicking::panic("assertion failed: def.is_union()")
};assert!(def.is_union());
168
169    let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
170    let args = ty::GenericArgs::identity_for_item(tcx, item_def_id);
171
172    for field in &def.non_enum_variant().fields {
173        if !allowed_union_or_unsafe_field(
174            tcx,
175            field.ty(tcx, args).skip_norm_wip(),
176            typing_env,
177            span,
178        ) {
179            let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {
180                // We are currently checking the type this field came from, so it must be local.
181                Some(Node::Field(field)) => (field.span, field.ty.span),
182                _ => {
    ::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"),
183            };
184            tcx.dcx().emit_err(errors::InvalidUnionField {
185                field_span,
186                sugg: errors::InvalidUnionFieldSuggestion {
187                    lo: ty_span.shrink_to_lo(),
188                    hi: ty_span.shrink_to_hi(),
189                },
190                note: (),
191            });
192            return false;
193        }
194    }
195
196    true
197}
198
199/// Check that a `static` is inhabited.
200fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
201    #[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)]
202    #[diag("static of uninhabited type")]
203    #[note("uninhabited statics cannot be initialized, and any access would be an immediate error")]
204    struct StaticOfUninhabitedType;
205
206    // Make sure statics are inhabited.
207    // Other parts of the compiler assume that there are no uninhabited places. In principle it
208    // would be enough to check this for `extern` statics, as statics with an initializer will
209    // have UB during initialization if they are uninhabited, but there also seems to be no good
210    // reason to allow any statics to be uninhabited.
211    let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
212    let span = tcx.def_span(def_id);
213    let layout = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
214        Ok(l) => l,
215        // Foreign statics that overflow their allowed size should emit an error
216        Err(LayoutError::SizeOverflow(_))
217            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{ .. }
218                if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) =>
219        {
220            tcx.dcx().emit_err(errors::TooLargeStatic { span });
221            return;
222        }
223        // SIMD types with invalid layout (e.g., zero-length) should emit an error
224        Err(e @ LayoutError::InvalidSimd { .. }) => {
225            let ty_span = tcx.ty_span(def_id);
226            tcx.dcx().span_err(ty_span, e.to_string());
227            return;
228        }
229        // Generic statics are rejected, but we still reach this case.
230        Err(e) => {
231            tcx.dcx().span_delayed_bug(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", e))
    })format!("{e:?}"));
232            return;
233        }
234    };
235    if layout.is_uninhabited() {
236        tcx.emit_node_span_lint(
237            UNINHABITED_STATIC,
238            tcx.local_def_id_to_hir_id(def_id),
239            span,
240            StaticOfUninhabitedType,
241        );
242    }
243}
244
245/// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
246/// projections that would result in "inheriting lifetimes".
247fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
248    let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);
249
250    // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
251    // `async-std` (and `pub async fn` in general).
252    // Since rustdoc doesn't care about the hidden type behind `impl Trait`, just don't look at it!
253    // See https://github.com/rust-lang/rust/issues/75100
254    if tcx.sess.opts.actually_rustdoc {
255        return;
256    }
257
258    if tcx.type_of(def_id).instantiate_identity().skip_norm_wip().references_error() {
259        return;
260    }
261    if check_opaque_for_cycles(tcx, def_id).is_err() {
262        return;
263    }
264
265    let _ = check_opaque_meets_bounds(tcx, def_id, origin);
266}
267
268/// Checks that an opaque type does not contain cycles.
269pub(super) fn check_opaque_for_cycles<'tcx>(
270    tcx: TyCtxt<'tcx>,
271    def_id: LocalDefId,
272) -> Result<(), ErrorGuaranteed> {
273    let args = GenericArgs::identity_for_item(tcx, def_id);
274
275    // First, try to look at any opaque expansion cycles, considering coroutine fields
276    // (even though these aren't necessarily true errors).
277    if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() {
278        let reported = opaque_type_cycle_error(tcx, def_id);
279        return Err(reported);
280    }
281
282    Ok(())
283}
284
285/// Check that the hidden type behind `impl Trait` actually implements `Trait`.
286///
287/// This is mostly checked at the places that specify the opaque type, but we
288/// check those cases in the `param_env` of that function, which may have
289/// bounds not on this opaque type:
290///
291/// ```ignore (illustrative)
292/// type X<T> = impl Clone;
293/// fn f<T: Clone>(t: T) -> X<T> {
294///     t
295/// }
296/// ```
297///
298/// Without this check the above code is incorrectly accepted: we would ICE if
299/// some tried, for example, to clone an `Option<X<&mut ()>>`.
300#[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(300u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                                    ::tracing_core::field::FieldSet::new(&["def_id", "origin"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (span, definition_def_id) =
                if let Some((span, def_id)) =
                        best_definition_site_of_opaque(tcx, def_id, origin) {
                    (span, Some(def_id))
                } else { (tcx.def_span(def_id), None) };
            let defining_use_anchor =
                match origin {
                    hir::OpaqueTyOrigin::FnReturn { parent, .. } |
                        hir::OpaqueTyOrigin::AsyncFn { parent, .. } |
                        hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
                };
            let param_env = tcx.param_env(defining_use_anchor);
            let infcx =
                tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
                        TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
                    } else {
                        TypingMode::analysis_in_body(tcx, defining_use_anchor)
                    });
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            let args =
                match origin {
                    hir::OpaqueTyOrigin::FnReturn { parent, .. } |
                        hir::OpaqueTyOrigin::AsyncFn { parent, .. } |
                        hir::OpaqueTyOrigin::TyAlias { parent, .. } =>
                        GenericArgs::identity_for_item(tcx,
                                parent).extend_to(tcx, def_id.to_def_id(),
                            |param, _|
                                {
                                    tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
                                }),
                };
            let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
            let hidden_ty =
                tcx.type_of(def_id.to_def_id()).instantiate(tcx,
                        args).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))]
301fn check_opaque_meets_bounds<'tcx>(
302    tcx: TyCtxt<'tcx>,
303    def_id: LocalDefId,
304    origin: hir::OpaqueTyOrigin<LocalDefId>,
305) -> Result<(), ErrorGuaranteed> {
306    let (span, definition_def_id) =
307        if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {
308            (span, Some(def_id))
309        } else {
310            (tcx.def_span(def_id), None)
311        };
312
313    let defining_use_anchor = match origin {
314        hir::OpaqueTyOrigin::FnReturn { parent, .. }
315        | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
316        | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
317    };
318    let param_env = tcx.param_env(defining_use_anchor);
319
320    // FIXME(#132279): Once `PostBorrowck` is supported in the old solver, this branch should be removed.
321    let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
322        TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
323    } else {
324        TypingMode::analysis_in_body(tcx, defining_use_anchor)
325    });
326    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
327
328    let args = match origin {
329        hir::OpaqueTyOrigin::FnReturn { parent, .. }
330        | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
331        | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(
332            tcx, parent,
333        )
334        .extend_to(tcx, def_id.to_def_id(), |param, _| {
335            tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
336        }),
337    };
338
339    let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
340
341    // `ReErased` regions appear in the "parent_args" of closures/coroutines.
342    // We're ignoring them here and replacing them with fresh region variables.
343    // See tests in ui/type-alias-impl-trait/closure_{parent_args,wf_outlives}.rs.
344    //
345    // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it
346    // here rather than using ReErased.
347    let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args).skip_norm_wip();
348    let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {
349        ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)),
350        _ => re,
351    });
352
353    // HACK: We eagerly instantiate some bounds to report better errors for them...
354    // This isn't necessary for correctness, since we register these bounds when
355    // equating the opaque below, but we should clean this up in the new solver.
356    for (predicate, pred_span) in tcx
357        .explicit_item_bounds(def_id)
358        .iter_instantiated_copied(tcx, args)
359        .map(Unnormalized::skip_norm_wip)
360    {
361        let predicate = predicate.fold_with(&mut BottomUpFolder {
362            tcx,
363            ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
364            lt_op: |lt| lt,
365            ct_op: |ct| ct,
366        });
367
368        ocx.register_obligation(Obligation::new(
369            tcx,
370            ObligationCause::new(
371                span,
372                def_id,
373                ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
374            ),
375            param_env,
376            predicate,
377        ));
378    }
379
380    let misc_cause = ObligationCause::misc(span, def_id);
381    // FIXME: We should just register the item bounds here, rather than equating.
382    // FIXME(const_trait_impl): When we do that, please make sure to also register
383    // the `[const]` bounds.
384    match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
385        Ok(()) => {}
386        Err(ty_err) => {
387            // Some types may be left "stranded" if they can't be reached
388            // from a lowered rustc_middle bound but they're mentioned in the HIR.
389            // This will happen, e.g., when a nested opaque is inside of a non-
390            // existent associated type, like `impl Trait<Missing = impl Trait>`.
391            // See <tests/ui/impl-trait/stranded-opaque.rs>.
392            let ty_err = ty_err.to_string(tcx);
393            let guar = tcx.dcx().span_delayed_bug(
394                span,
395                format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
396            );
397            return Err(guar);
398        }
399    }
400
401    // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
402    // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
403    // hidden type is well formed even without those bounds.
404    let predicate =
405        ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
406    ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
407
408    // Check that all obligations are satisfied by the implementation's
409    // version.
410    let errors = ocx.evaluate_obligations_error_on_ambiguity();
411    if !errors.is_empty() {
412        let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
413        return Err(guar);
414    }
415
416    let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
417    ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
418
419    if infcx.next_trait_solver() {
420        Ok(())
421    } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
422        origin
423    {
424        // HACK: this should also fall through to the hidden type check below, but the original
425        // implementation had a bug where equivalent lifetimes are not identical. This caused us
426        // to reject existing stable code that is otherwise completely fine. The real fix is to
427        // compare the hidden types via our type equivalence/relation infra instead of doing an
428        // identity check.
429        let _ = infcx.take_opaque_types();
430        Ok(())
431    } else {
432        // Check that any hidden types found during wf checking match the hidden types that `type_of` sees.
433        for (mut key, mut ty) in infcx.take_opaque_types() {
434            ty.ty = infcx.resolve_vars_if_possible(ty.ty);
435            key = infcx.resolve_vars_if_possible(key);
436            sanity_check_found_hidden_type(tcx, key, ty)?;
437        }
438        Ok(())
439    }
440}
441
442fn best_definition_site_of_opaque<'tcx>(
443    tcx: TyCtxt<'tcx>,
444    opaque_def_id: LocalDefId,
445    origin: hir::OpaqueTyOrigin<LocalDefId>,
446) -> Option<(Span, LocalDefId)> {
447    struct TaitConstraintLocator<'tcx> {
448        opaque_def_id: LocalDefId,
449        tcx: TyCtxt<'tcx>,
450    }
451    impl<'tcx> TaitConstraintLocator<'tcx> {
452        fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
453            if !self.tcx.has_typeck_results(item_def_id) {
454                return ControlFlow::Continue(());
455            }
456
457            let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
458            // Don't try to check items that cannot possibly constrain the type.
459            if !opaque_types_defined_by.contains(&self.opaque_def_id) {
460                return ControlFlow::Continue(());
461            }
462
463            if let Some(hidden_ty) = self
464                .tcx
465                .mir_borrowck(item_def_id)
466                .ok()
467                .and_then(|opaque_types| opaque_types.get(&self.opaque_def_id))
468            {
469                ControlFlow::Break((hidden_ty.span, item_def_id))
470            } else {
471                ControlFlow::Continue(())
472            }
473        }
474    }
475    impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
476        type NestedFilter = nested_filter::All;
477        type Result = ControlFlow<(Span, LocalDefId)>;
478        fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
479            self.tcx
480        }
481        fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
482            intravisit::walk_expr(self, ex)
483        }
484        fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
485            self.check(it.owner_id.def_id)?;
486            intravisit::walk_item(self, it)
487        }
488        fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
489            self.check(it.owner_id.def_id)?;
490            intravisit::walk_impl_item(self, it)
491        }
492        fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
493            self.check(it.owner_id.def_id)?;
494            intravisit::walk_trait_item(self, it)
495        }
496        fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
497            intravisit::walk_foreign_item(self, it)
498        }
499    }
500
501    let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
502    match origin {
503        hir::OpaqueTyOrigin::FnReturn { parent, .. }
504        | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
505        hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
506            let impl_def_id = tcx.local_parent(parent);
507            for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
508                match assoc.kind {
509                    ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
510                        if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
511                        {
512                            return Some(span);
513                        }
514                    }
515                    ty::AssocKind::Type { .. } => {}
516                }
517            }
518
519            None
520        }
521        hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
522            tcx.hir_walk_toplevel_module(&mut locator).break_value()
523        }
524    }
525}
526
527fn sanity_check_found_hidden_type<'tcx>(
528    tcx: TyCtxt<'tcx>,
529    key: ty::OpaqueTypeKey<'tcx>,
530    mut ty: ty::ProvisionalHiddenType<'tcx>,
531) -> Result<(), ErrorGuaranteed> {
532    if ty.ty.is_ty_var() {
533        // Nothing was actually constrained.
534        return Ok(());
535    }
536    if let &ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = ty.ty.kind() {
537        if def_id == key.def_id.to_def_id() && args == key.args {
538            // Nothing was actually constrained, this is an opaque usage that was
539            // only discovered to be opaque after inference vars resolved.
540            return Ok(());
541        }
542    }
543    let erase_re_vars = |ty: Ty<'tcx>| {
544        fold_regions(tcx, ty, |r, _| match r.kind() {
545            RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
546            _ => r,
547        })
548    };
549    // Closures frequently end up containing erased lifetimes in their final representation.
550    // These correspond to lifetime variables that never got resolved, so we patch this up here.
551    ty.ty = erase_re_vars(ty.ty);
552    // Get the hidden type.
553    let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args).skip_norm_wip();
554    let hidden_ty = erase_re_vars(hidden_ty);
555
556    // If the hidden types differ, emit a type mismatch diagnostic.
557    if hidden_ty == ty.ty {
558        Ok(())
559    } else {
560        let span = tcx.def_span(key.def_id);
561        let other = ty::ProvisionalHiddenType { ty: hidden_ty, span };
562        Err(ty.build_mismatch_error(&other, tcx)?.emit())
563    }
564}
565
566/// Check that the opaque's precise captures list is valid (if present).
567/// We check this for regular `impl Trait`s and also RPITITs, even though the latter
568/// are technically GATs.
569///
570/// This function is responsible for:
571/// 1. Checking that all type/const params are mention in the captures list.
572/// 2. Checking that all lifetimes that are implicitly captured are mentioned.
573/// 3. Asserting that all parameters mentioned in the captures list are invariant.
574fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
575    let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
576    let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
577        hir::GenericBound::Use(bounds, ..) => Some(bounds),
578        _ => None,
579    }) else {
580        // No precise capturing args; nothing to validate
581        return;
582    };
583
584    let mut expected_captures = UnordSet::default();
585    let mut shadowed_captures = UnordSet::default();
586    let mut seen_params = UnordMap::default();
587    let mut prev_non_lifetime_param = None;
588    for arg in precise_capturing_args {
589        let (hir_id, ident) = match *arg {
590            hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
591                hir_id,
592                ident,
593                ..
594            }) => {
595                if prev_non_lifetime_param.is_none() {
596                    prev_non_lifetime_param = Some(ident);
597                }
598                (hir_id, ident)
599            }
600            hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
601                if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
602                    tcx.dcx().emit_err(errors::LifetimesMustBeFirst {
603                        lifetime_span: ident.span,
604                        name: ident.name,
605                        other_span: prev_non_lifetime_param.span,
606                    });
607                }
608                (hir_id, ident)
609            }
610        };
611
612        let ident = ident.normalize_to_macros_2_0();
613        if let Some(span) = seen_params.insert(ident, ident.span) {
614            tcx.dcx().emit_err(errors::DuplicatePreciseCapture {
615                name: ident.name,
616                first_span: span,
617                second_span: ident.span,
618            });
619        }
620
621        match tcx.named_bound_var(hir_id) {
622            Some(ResolvedArg::EarlyBound(def_id)) => {
623                expected_captures.insert(def_id.to_def_id());
624
625                // Make sure we allow capturing these lifetimes through `Self` and
626                // `T::Assoc` projection syntax, too. These will occur when we only
627                // see lifetimes are captured after hir-lowering -- this aligns with
628                // the cases that were stabilized with the `impl_trait_projection`
629                // feature -- see <https://github.com/rust-lang/rust/pull/115659>.
630                if let DefKind::LifetimeParam = tcx.def_kind(def_id)
631                    && let Some(def_id) = tcx
632                        .map_opaque_lifetime_to_parent_lifetime(def_id)
633                        .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
634                {
635                    shadowed_captures.insert(def_id);
636                }
637            }
638            _ => {
639                tcx.dcx()
640                    .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
641            }
642        }
643    }
644
645    let variances = tcx.variances_of(opaque_def_id);
646    let mut def_id = Some(opaque_def_id.to_def_id());
647    while let Some(generics) = def_id {
648        let generics = tcx.generics_of(generics);
649        def_id = generics.parent;
650
651        for param in &generics.own_params {
652            if expected_captures.contains(&param.def_id) {
653                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!(
654                    variances[param.index as usize],
655                    ty::Invariant,
656                    "precise captured param should be invariant"
657                );
658                continue;
659            }
660            // If a param is shadowed by a early-bound (duplicated) lifetime, then
661            // it may or may not be captured as invariant, depending on if it shows
662            // up through `Self` or `T::Assoc` syntax.
663            if shadowed_captures.contains(&param.def_id) {
664                continue;
665            }
666
667            match param.kind {
668                ty::GenericParamDefKind::Lifetime => {
669                    let use_span = tcx.def_span(param.def_id);
670                    let opaque_span = tcx.def_span(opaque_def_id);
671                    // Check if the lifetime param was captured but isn't named in the precise captures list.
672                    if variances[param.index as usize] == ty::Invariant {
673                        if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
674                            && let Some(def_id) = tcx
675                                .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
676                                .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
677                        {
678                            tcx.dcx().emit_err(errors::LifetimeNotCaptured {
679                                opaque_span,
680                                use_span,
681                                param_span: tcx.def_span(def_id),
682                            });
683                        } else {
684                            if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
685                                tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured {
686                                    opaque_span,
687                                    param_span: tcx.def_span(param.def_id),
688                                });
689                            } else {
690                                // If the `use_span` is actually just the param itself, then we must
691                                // have not duplicated the lifetime but captured the original.
692                                // The "effective" `use_span` will be the span of the opaque itself,
693                                // and the param span will be the def span of the param.
694                                tcx.dcx().emit_err(errors::LifetimeNotCaptured {
695                                    opaque_span,
696                                    use_span: opaque_span,
697                                    param_span: use_span,
698                                });
699                            }
700                        }
701                        continue;
702                    }
703                }
704                ty::GenericParamDefKind::Type { .. } => {
705                    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) {
706                        // FIXME(precise_capturing): Structured suggestion for this would be useful
707                        tcx.dcx().emit_err(errors::SelfTyNotCaptured {
708                            trait_span: tcx.def_span(param.def_id),
709                            opaque_span: tcx.def_span(opaque_def_id),
710                        });
711                    } else {
712                        // FIXME(precise_capturing): Structured suggestion for this would be useful
713                        tcx.dcx().emit_err(errors::ParamNotCaptured {
714                            param_span: tcx.def_span(param.def_id),
715                            opaque_span: tcx.def_span(opaque_def_id),
716                            kind: "type",
717                        });
718                    }
719                }
720                ty::GenericParamDefKind::Const { .. } => {
721                    // FIXME(precise_capturing): Structured suggestion for this would be useful
722                    tcx.dcx().emit_err(errors::ParamNotCaptured {
723                        param_span: tcx.def_span(param.def_id),
724                        opaque_span: tcx.def_span(opaque_def_id),
725                        kind: "const",
726                    });
727                }
728            }
729        }
730    }
731}
732
733fn is_enum_of_nonnullable_ptr<'tcx>(
734    tcx: TyCtxt<'tcx>,
735    adt_def: AdtDef<'tcx>,
736    args: GenericArgsRef<'tcx>,
737) -> bool {
738    if adt_def.repr().inhibit_enum_layout_opt() {
739        return false;
740    }
741
742    let [var_one, var_two] = &adt_def.variants().raw[..] else {
743        return false;
744    };
745    let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
746        return false;
747    };
748    #[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(..))
749}
750
751fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
752    if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
753        if match tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {
754            ty::RawPtr(_, _) => false,
755            ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
756            _ => true,
757        } {
758            tcx.dcx().emit_err(errors::LinkageType { span: tcx.def_span(def_id) });
759        }
760    }
761}
762
763pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
764    let mut res = Ok(());
765    let generics = tcx.generics_of(def_id);
766
767    for param in &generics.own_params {
768        match param.kind {
769            ty::GenericParamDefKind::Lifetime { .. } => {}
770            ty::GenericParamDefKind::Type { has_default, .. } => {
771                if has_default {
772                    tcx.ensure_ok().type_of(param.def_id);
773                }
774            }
775            ty::GenericParamDefKind::Const { has_default, .. } => {
776                tcx.ensure_ok().type_of(param.def_id);
777                if has_default {
778                    // need to store default and type of default
779                    let ct = tcx.const_param_default(param.def_id).skip_binder();
780                    if let ty::ConstKind::Unevaluated(uv) = ct.kind()
781                        && let Some(def_id) = uv.kind.opt_def_id()
782                    {
783                        tcx.ensure_ok().type_of(def_id);
784                    }
785                }
786            }
787        }
788    }
789
790    match tcx.def_kind(def_id) {
791        DefKind::Static { .. } => {
792            tcx.ensure_ok().generics_of(def_id);
793            tcx.ensure_ok().type_of(def_id);
794            tcx.ensure_ok().predicates_of(def_id);
795
796            check_static_inhabited(tcx, def_id);
797            check_static_linkage(tcx, def_id);
798            let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
799            res = res.and(wfcheck::check_static_item(
800                tcx, def_id, ty, /* should_check_for_sync */ true,
801            ));
802
803            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
804            // checks. Returning early here does not miss any checks and
805            // avoids this query from having a direct dependency edge on the HIR
806            return res;
807        }
808        DefKind::Enum => {
809            tcx.ensure_ok().generics_of(def_id);
810            tcx.ensure_ok().type_of(def_id);
811            tcx.ensure_ok().predicates_of(def_id);
812            crate::collect::check_enum_variant_types(tcx, def_id);
813            check_enum(tcx, def_id);
814            check_variances_for_type_defn(tcx, def_id);
815            res = res.and(check_type_defn(tcx, def_id, true));
816            // enums are fully handled by the type based check and have no hir wfcheck logic
817            return res;
818        }
819        DefKind::Fn => {
820            tcx.ensure_ok().generics_of(def_id);
821            tcx.ensure_ok().type_of(def_id);
822            tcx.ensure_ok().predicates_of(def_id);
823            tcx.ensure_ok().fn_sig(def_id);
824            tcx.ensure_ok().codegen_fn_attrs(def_id);
825            if let Some(i) = tcx.intrinsic(def_id) {
826                intrinsic::check_intrinsic_type(
827                    tcx,
828                    def_id,
829                    tcx.def_ident_span(def_id).unwrap(),
830                    i.name,
831                )
832            }
833        }
834        DefKind::Impl { of_trait } => {
835            tcx.ensure_ok().generics_of(def_id);
836            tcx.ensure_ok().type_of(def_id);
837            tcx.ensure_ok().predicates_of(def_id);
838            tcx.ensure_ok().associated_items(def_id);
839            if of_trait {
840                let impl_trait_header = tcx.impl_trait_header(def_id);
841                res = res.and(tcx.ensure_result().coherent_trait(
842                    impl_trait_header.trait_ref.instantiate_identity().skip_norm_wip().def_id,
843                ));
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_lazy(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::InlineConst
1175        | DefKind::ExternCrate
1176        | DefKind::Macro(..)
1177        | DefKind::Use
1178        | DefKind::GlobalAsm
1179        | DefKind::Mod => return res,
1180        _ => {}
1181    }
1182    let node = tcx.hir_node_by_def_id(def_id);
1183    res.and(match node {
1184        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"),
1185        hir::Node::Item(item) => wfcheck::check_item(tcx, item),
1186        hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),
1187        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{0:?}", node)));
}unreachable!("{node:?}"),
1188    })
1189}
1190
1191pub(super) fn check_specialization_validity<'tcx>(
1192    tcx: TyCtxt<'tcx>,
1193    trait_def: &ty::TraitDef,
1194    trait_item: ty::AssocItem,
1195    impl_id: DefId,
1196    impl_item: DefId,
1197) {
1198    let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
1199    let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
1200        if parent.is_from_trait() {
1201            None
1202        } else {
1203            Some((parent, parent.item(tcx, trait_item.def_id)))
1204        }
1205    });
1206
1207    let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1208        match parent_item {
1209            // Parent impl exists, and contains the parent item we're trying to specialize, but
1210            // doesn't mark it `default`.
1211            Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
1212                Some(Err(parent_impl.def_id()))
1213            }
1214
1215            // Parent impl contains item and makes it specializable.
1216            Some(_) => Some(Ok(())),
1217
1218            // Parent impl doesn't mention the item. This means it's inherited from the
1219            // grandparent. In that case, if parent is a `default impl`, inherited items use the
1220            // "defaultness" from the grandparent, else they are final.
1221            None => {
1222                if tcx.defaultness(parent_impl.def_id()).is_default() {
1223                    None
1224                } else {
1225                    Some(Err(parent_impl.def_id()))
1226                }
1227            }
1228        }
1229    });
1230
1231    // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
1232    // item. This is allowed, the item isn't actually getting specialized here.
1233    let result = opt_result.unwrap_or(Ok(()));
1234
1235    if let Err(parent_impl) = result {
1236        if !tcx.is_impl_trait_in_trait(impl_item) {
1237            let span = tcx.def_span(impl_item);
1238            let ident = tcx.item_ident(impl_item);
1239
1240            let err = match tcx.span_of_impl(parent_impl) {
1241                Ok(sp) => errors::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp },
1242                Err(cname) => errors::ImplNotMarkedDefault::Err { span, ident, cname },
1243            };
1244
1245            tcx.dcx().emit_err(err);
1246        } else {
1247            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"));
1248        }
1249    }
1250}
1251
1252fn check_overriding_final_trait_item<'tcx>(
1253    tcx: TyCtxt<'tcx>,
1254    trait_item: ty::AssocItem,
1255    impl_item: ty::AssocItem,
1256) {
1257    if trait_item.defaultness(tcx).is_final() {
1258        tcx.dcx().emit_err(errors::OverridingFinalTraitFunction {
1259            impl_span: tcx.def_span(impl_item.def_id),
1260            trait_span: tcx.def_span(trait_item.def_id),
1261            ident: tcx.item_ident(impl_item.def_id),
1262        });
1263    }
1264}
1265
1266fn check_impl_items_against_trait<'tcx>(
1267    tcx: TyCtxt<'tcx>,
1268    impl_id: LocalDefId,
1269    impl_trait_header: ty::ImplTraitHeader<'tcx>,
1270) {
1271    let trait_ref = impl_trait_header.trait_ref.instantiate_identity().skip_norm_wip();
1272    // If the trait reference itself is erroneous (so the compilation is going
1273    // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1274    // isn't populated for such impls.
1275    if trait_ref.references_error() {
1276        return;
1277    }
1278
1279    let impl_item_refs = tcx.associated_item_def_ids(impl_id);
1280
1281    // Negative impls are not expected to have any items
1282    match impl_trait_header.polarity {
1283        ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
1284        ty::ImplPolarity::Negative => {
1285            if let [first_item_ref, ..] = *impl_item_refs {
1286                let first_item_span = tcx.def_span(first_item_ref);
1287                {
    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!(
1288                    tcx.dcx(),
1289                    first_item_span,
1290                    E0749,
1291                    "negative impls cannot have any items"
1292                )
1293                .emit();
1294            }
1295            return;
1296        }
1297    }
1298
1299    let trait_def = tcx.trait_def(trait_ref.def_id);
1300
1301    let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
1302
1303    for &impl_item in impl_item_refs {
1304        let ty_impl_item = tcx.associated_item(impl_item);
1305        let ty_trait_item = match ty_impl_item.expect_trait_impl() {
1306            Ok(trait_item_id) => tcx.associated_item(trait_item_id),
1307            Err(ErrorGuaranteed { .. }) => continue,
1308        };
1309
1310        let res = tcx.ensure_result().compare_impl_item(impl_item.expect_local());
1311        if res.is_ok() {
1312            match ty_impl_item.kind {
1313                ty::AssocKind::Fn { .. } => {
1314                    compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1315                        tcx,
1316                        ty_impl_item,
1317                        ty_trait_item,
1318                        tcx.impl_trait_ref(ty_impl_item.container_id(tcx))
1319                            .instantiate_identity()
1320                            .skip_norm_wip(),
1321                    );
1322                }
1323                ty::AssocKind::Const { .. } => {}
1324                ty::AssocKind::Type { .. } => {}
1325            }
1326        }
1327
1328        if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1329            tcx.emit_node_span_lint(
1330                rustc_lint_defs::builtin::DEAD_CODE,
1331                tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1332                tcx.def_span(ty_impl_item.def_id),
1333                errors::UselessImplItem,
1334            )
1335        }
1336
1337        check_specialization_validity(
1338            tcx,
1339            trait_def,
1340            ty_trait_item,
1341            impl_id.to_def_id(),
1342            impl_item,
1343        );
1344
1345        check_overriding_final_trait_item(tcx, ty_trait_item, ty_impl_item);
1346    }
1347
1348    if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1349        // Check for missing items from trait
1350        let mut missing_items = Vec::new();
1351
1352        let mut must_implement_one_of: Option<&[Ident]> =
1353            trait_def.must_implement_one_of.as_deref();
1354
1355        for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1356            let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1357
1358            let is_implemented = leaf_def
1359                .as_ref()
1360                .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1361
1362            if !is_implemented
1363                && tcx.defaultness(impl_id).is_final()
1364                // unsized types don't need to implement methods that have `Self: Sized` bounds.
1365                && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1366            {
1367                missing_items.push(tcx.associated_item(trait_item_id));
1368            }
1369
1370            // true if this item is specifically implemented in this impl
1371            let is_implemented_here =
1372                leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1373
1374            if !is_implemented_here {
1375                let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1376                match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1377                    // When the feature `pin_ergonomics` is disabled, we report `Drop::drop` is missing,
1378                    // instead of `Drop::drop` is unstable that might be confusing.
1379                    EvalResult::Deny { .. }
1380                        if !tcx.features().pin_ergonomics()
1381                            && tcx.is_lang_item(trait_ref.def_id, hir::LangItem::Drop)
1382                            && tcx.item_name(trait_item_id) == sym::drop =>
1383                    {
1384                        missing_items.push(tcx.associated_item(trait_item_id));
1385                    }
1386                    EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1387                        tcx,
1388                        full_impl_span,
1389                        trait_item_id,
1390                        feature,
1391                        reason,
1392                        issue,
1393                    ),
1394
1395                    // Unmarked default bodies are considered stable (at least for now).
1396                    EvalResult::Allow | EvalResult::Unmarked => {}
1397                }
1398            }
1399
1400            if let Some(required_items) = &must_implement_one_of {
1401                if is_implemented_here {
1402                    let trait_item = tcx.associated_item(trait_item_id);
1403                    if required_items.contains(&trait_item.ident(tcx)) {
1404                        must_implement_one_of = None;
1405                    }
1406                }
1407            }
1408
1409            if let Some(leaf_def) = &leaf_def
1410                && !leaf_def.is_final()
1411                && let def_id = leaf_def.item.def_id
1412                && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1413            {
1414                let def_kind = tcx.def_kind(def_id);
1415                let descr = tcx.def_kind_descr(def_kind, def_id);
1416                let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1417                    (
1418                        ::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"),
1419                        "async functions in traits",
1420                    )
1421                } else {
1422                    (
1423                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} with return-position `impl Trait` in trait cannot be specialized",
                descr))
    })format!(
1424                            "{descr} with return-position `impl Trait` in trait cannot be specialized"
1425                        ),
1426                        "return position `impl Trait` in traits",
1427                    )
1428                };
1429                tcx.dcx()
1430                    .struct_span_err(tcx.def_span(def_id), msg)
1431                    .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!(
1432                        "specialization behaves in inconsistent and surprising ways with \
1433                        {feature}, and for now is disallowed"
1434                    ))
1435                    .emit();
1436            }
1437        }
1438
1439        if !missing_items.is_empty() {
1440            let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1441            missing_items_err(tcx, impl_id, &missing_items, full_impl_span);
1442        }
1443
1444        if let Some(missing_items) = must_implement_one_of {
1445            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);
1446
1447            missing_items_must_implement_one_of_err(
1448                tcx,
1449                tcx.def_span(impl_id),
1450                missing_items,
1451                attr_span,
1452            );
1453        }
1454    }
1455}
1456
1457fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1458    let t = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1459    if let ty::Adt(def, args) = t.kind()
1460        && def.is_struct()
1461    {
1462        let fields = &def.non_enum_variant().fields;
1463        if fields.is_empty() {
1464            {
    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();
1465            return;
1466        }
1467
1468        let array_field = &fields[FieldIdx::ZERO];
1469        let array_ty = array_field.ty(tcx, args).skip_norm_wip();
1470        let ty::Array(element_ty, len_const) = array_ty.kind() else {
1471            {
    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!(
1472                tcx.dcx(),
1473                sp,
1474                E0076,
1475                "SIMD vector's only field must be an array"
1476            )
1477            .with_span_label(tcx.def_span(array_field.did), "not an array")
1478            .emit();
1479            return;
1480        };
1481
1482        if let Some(second_field) = fields.get(FieldIdx::ONE) {
1483            {
    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")
1484                .with_span_label(tcx.def_span(second_field.did), "excess field")
1485                .emit();
1486            return;
1487        }
1488
1489        // FIXME(repr_simd): This check is nice, but perhaps unnecessary due to the fact
1490        // we do not expect users to implement their own `repr(simd)` types. If they could,
1491        // this check is easily side-steppable by hiding the const behind normalization.
1492        // The consequence is that the error is, in general, only observable post-mono.
1493        if let Some(len) = len_const.try_to_target_usize(tcx) {
1494            if len == 0 {
1495                {
    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();
1496                return;
1497            } else if len > MAX_SIMD_LANES {
1498                {
    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!(
1499                    tcx.dcx(),
1500                    sp,
1501                    E0075,
1502                    "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1503                )
1504                .emit();
1505                return;
1506            }
1507        }
1508
1509        // Check that we use types valid for use in the lanes of a SIMD "vector register"
1510        // These are scalar types which directly match a "machine" type
1511        // Yes: Integers, floats, "thin" pointers
1512        // No: char, "wide" pointers, compound types
1513        match element_ty.kind() {
1514            ty::Param(_) => (), // pass struct<T>([T; 4]) through, let monomorphization catch errors
1515            ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), // struct([u8; 4]) is ok
1516            _ => {
1517                {
    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!(
1518                    tcx.dcx(),
1519                    sp,
1520                    E0077,
1521                    "SIMD vector element type should be a \
1522                        primitive scalar (integer/float/pointer) type"
1523                )
1524                .emit();
1525                return;
1526            }
1527        }
1528    }
1529}
1530
1531#[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(1531u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                                    ::tracing_core::field::FieldSet::new(&["span", "def_id",
                                                    "scalable"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalable)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty =
                tcx.type_of(def_id).instantiate_identity().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")]
1532fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalable: ScalableElt) {
1533    let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1534    let ty::Adt(def, args) = ty.kind() else { return };
1535    if !def.is_struct() {
1536        tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");
1537        return;
1538    }
1539
1540    let fields = &def.non_enum_variant().fields;
1541    match scalable {
1542        ScalableElt::ElementCount(..) if fields.is_empty() => {
1543            let mut err =
1544                tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");
1545            err.help("scalable vector types' only field must be a primitive scalar type");
1546            err.emit();
1547            return;
1548        }
1549        ScalableElt::ElementCount(..) if fields.len() >= 2 => {
1550            tcx.dcx().struct_span_err(span, "scalable vectors cannot have multiple fields").emit();
1551            return;
1552        }
1553        ScalableElt::Container if fields.is_empty() => {
1554            let mut err = tcx
1555                .dcx()
1556                .struct_span_err(span, "scalable vector tuples must have at least one field");
1557            err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1558            err.emit();
1559            return;
1560        }
1561        ScalableElt::Container if fields.len() > 8 => {
1562            let mut err = tcx
1563                .dcx()
1564                .struct_span_err(span, "scalable vector tuples can have at most eight fields");
1565            err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1566            err.emit();
1567            return;
1568        }
1569        _ => {}
1570    }
1571
1572    match scalable {
1573        ScalableElt::ElementCount(..) => {
1574            let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args).skip_norm_wip();
1575
1576            // Check that `element_ty` only uses types valid in the lanes of a scalable vector
1577            // register: scalar types which directly match a "machine" type - integers, floats and
1578            // bools
1579            match element_ty.kind() {
1580                ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Bool => (),
1581                _ => {
1582                    let mut err = tcx.dcx().struct_span_err(
1583                        span,
1584                        "element type of a scalable vector must be a primitive scalar",
1585                    );
1586                    err.help("only `u*`, `i*`, `f*` and `bool` types are accepted");
1587                    err.emit();
1588                }
1589            }
1590        }
1591        ScalableElt::Container => {
1592            let mut prev_field_ty = None;
1593            for field in fields.iter() {
1594                let element_ty = field.ty(tcx, args).skip_norm_wip();
1595                if let ty::Adt(def, _) = element_ty.kind()
1596                    && def.repr().scalable()
1597                {
1598                    match def
1599                        .repr()
1600                        .scalable
1601                        .expect("`repr().scalable.is_some()` != `repr().scalable()`")
1602                    {
1603                        ScalableElt::ElementCount(_) => { /* expected field */ }
1604                        ScalableElt::Container => {
1605                            tcx.dcx().span_err(
1606                                tcx.def_span(field.did),
1607                                "scalable vector structs cannot contain other scalable vector structs",
1608                            );
1609                            break;
1610                        }
1611                    }
1612                } else {
1613                    tcx.dcx().span_err(
1614                        tcx.def_span(field.did),
1615                        "scalable vector structs can only have scalable vector fields",
1616                    );
1617                    break;
1618                }
1619
1620                if let Some(prev_ty) = prev_field_ty.replace(element_ty)
1621                    && prev_ty != element_ty
1622                {
1623                    tcx.dcx().span_err(
1624                        tcx.def_span(field.did),
1625                        "all fields in a scalable vector struct must be the same type",
1626                    );
1627                    break;
1628                }
1629            }
1630        }
1631    }
1632}
1633
1634pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1635    let repr = def.repr();
1636    if repr.packed() {
1637        // `#[pin_v2]` on a packed type is unsound: drop glue for a packed type moves an
1638        // over-aligned field to an aligned location before running its destructor, which would
1639        // move a structurally pinned field out from under a `Pin<&mut _>` that was handed out.
1640        if def.is_pin_project() {
1641            tcx.dcx().emit_err(errors::PinV2OnPacked {
1642                span: sp,
1643                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),
1644                adt_name: tcx.item_name(def.did()),
1645            });
1646        }
1647        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) {
1648            for (r, _) in reprs {
1649                if let ReprPacked(pack) = r
1650                    && let Some(repr_pack) = repr.pack
1651                    && pack != &repr_pack
1652                {
1653                    {
    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!(
1654                        tcx.dcx(),
1655                        sp,
1656                        E0634,
1657                        "type has conflicting packed representation hints"
1658                    )
1659                    .emit();
1660                }
1661            }
1662        }
1663        if repr.align.is_some() {
1664            {
    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!(
1665                tcx.dcx(),
1666                sp,
1667                E0587,
1668                "type has conflicting packed and align representation hints"
1669            )
1670            .emit();
1671        } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut ::alloc::vec::Vec::new()vec![]) {
1672            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!(
1673                tcx.dcx(),
1674                sp,
1675                E0588,
1676                "packed type cannot transitively contain a `#[repr(align)]` type"
1677            );
1678
1679            err.span_note(
1680                tcx.def_span(def_spans[0].0),
1681                ::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)),
1682            );
1683
1684            if def_spans.len() > 2 {
1685                let mut first = true;
1686                for (adt_def, span) in def_spans.iter().skip(1).rev() {
1687                    let ident = tcx.item_name(*adt_def);
1688                    err.span_note(
1689                        *span,
1690                        if first {
1691                            ::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!(
1692                                "`{}` contains a field of type `{}`",
1693                                tcx.type_of(def.did()).instantiate_identity().skip_norm_wip(),
1694                                ident
1695                            )
1696                        } else {
1697                            ::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}`")
1698                        },
1699                    );
1700                    first = false;
1701                }
1702            }
1703
1704            err.emit();
1705        }
1706    }
1707}
1708
1709pub(super) fn check_packed_inner(
1710    tcx: TyCtxt<'_>,
1711    def_id: DefId,
1712    stack: &mut Vec<DefId>,
1713) -> Option<Vec<(DefId, Span)>> {
1714    if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {
1715        if def.is_struct() || def.is_union() {
1716            if def.repr().align.is_some() {
1717                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)]);
1718            }
1719
1720            stack.push(def_id);
1721            for field in &def.non_enum_variant().fields {
1722                if let ty::Adt(def, _) = field.ty(tcx, args).skip_norm_wip().kind()
1723                    && !stack.contains(&def.did())
1724                    && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1725                {
1726                    defs.push((def.did(), field.ident(tcx).span));
1727                    return Some(defs);
1728                }
1729            }
1730            stack.pop();
1731        }
1732    }
1733
1734    None
1735}
1736
1737pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1738    if !adt.repr().transparent() {
1739        return;
1740    }
1741
1742    if adt.is_union() && !tcx.features().transparent_unions() {
1743        feature_err(
1744            &tcx.sess,
1745            sym::transparent_unions,
1746            tcx.def_span(adt.did()),
1747            "transparent unions are unstable",
1748        )
1749        .emit();
1750    }
1751
1752    if adt.variants().len() != 1 {
1753        bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1754        // Don't bother checking the fields.
1755        return;
1756    }
1757    let variant = adt.variant(VariantIdx::ZERO);
1758
1759    if variant.fields.len() <= 1 {
1760        // No need to check when there's at most one field.
1761        return;
1762    }
1763
1764    let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
1765
1766    /// We call a field "trivial" for `repr(transparent)` purposes if it can be ignored.
1767    /// IOW, `repr(transparent)` is allowed if there is at most one non-trivial field.
1768    /// This enum captures all the reasons why a field might not be "trivial".
1769    enum NonTrivialReason<'tcx> {
1770        UnknownLayout,
1771        NonZeroSized,
1772        NonTrivialAlignment,
1773        PrivateField { inside: Ty<'tcx> },
1774        NonExhaustive { ty: Ty<'tcx> },
1775        ReprC { ty: Ty<'tcx> },
1776    }
1777    struct NonTrivialFieldInfo<'tcx> {
1778        span: Span,
1779        reason: NonTrivialReason<'tcx>,
1780    }
1781
1782    /// Check if this type is "trivial" for `repr(transparent)`. If not, return the reason why
1783    /// and the problematic type.
1784    fn is_trivial<'tcx>(
1785        tcx: TyCtxt<'tcx>,
1786        typing_env: ty::TypingEnv<'tcx>,
1787        ty: Ty<'tcx>,
1788    ) -> ControlFlow<NonTrivialReason<'tcx>> {
1789        // We can encounter projections during traversal, so ensure the type is normalized.
1790        let ty =
1791            tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);
1792        match ty.kind() {
1793            ty::Tuple(list) => list.iter().try_for_each(|t| is_trivial(tcx, typing_env, t)),
1794            ty::Array(ty, _) => is_trivial(tcx, typing_env, *ty),
1795            ty::Adt(def, args) => {
1796                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(_)) {
1797                    let non_exhaustive = def.is_variant_list_non_exhaustive()
1798                        || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1799                    if non_exhaustive {
1800                        return ControlFlow::Break(NonTrivialReason::NonExhaustive { ty });
1801                    }
1802                    let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1803                    if has_priv {
1804                        return ControlFlow::Break(NonTrivialReason::PrivateField { inside: ty });
1805                    }
1806                }
1807                if def.repr().c() {
1808                    return ControlFlow::Break(NonTrivialReason::ReprC { ty });
1809                }
1810                def.all_fields()
1811                    .map(|field| field.ty(tcx, args).skip_norm_wip())
1812                    .try_for_each(|t| is_trivial(tcx, typing_env, t))
1813            }
1814            _ => ControlFlow::Continue(()),
1815        }
1816    }
1817
1818    let non_trivial_fields = variant
1819        .fields
1820        .iter()
1821        .filter_map(|field| {
1822            let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did)).skip_norm_wip();
1823            let layout = tcx.layout_of(typing_env.as_query_input(ty));
1824            // We are currently checking the type this field came from, so it must be local
1825            let span = tcx.hir_span_if_local(field.did).unwrap();
1826            // Rule out non-1ZST
1827            if !layout.is_ok_and(|layout| layout.is_1zst()) {
1828                let reason = match layout {
1829                    Err(_) => NonTrivialReason::UnknownLayout,
1830                    Ok(layout) => {
1831                        if !(layout.is_sized() && layout.size.bytes() == 0) {
1832                            NonTrivialReason::NonZeroSized
1833                        } else {
1834                            NonTrivialReason::NonTrivialAlignment
1835                        }
1836                    }
1837                };
1838                return Some(NonTrivialFieldInfo { span, reason });
1839            }
1840            // Recursively check for other things that have to be ruled out.
1841            if let Some(reason) = is_trivial(tcx, typing_env, ty).break_value() {
1842                return Some(NonTrivialFieldInfo { span, reason });
1843            }
1844            // Otherwise,
1845            None
1846        })
1847        .collect::<Vec<_>>();
1848
1849    if non_trivial_fields.len() > 1 {
1850        let count = non_trivial_fields.len();
1851        let desc = if adt.is_enum() {
1852            format_args!("the variant of a transparent {0}", adt.descr())format_args!("the variant of a transparent {}", adt.descr())
1853        } else {
1854            format_args!("transparent {0}", adt.descr())format_args!("transparent {}", adt.descr())
1855        };
1856        let ty_span = tcx.def_span(adt.did());
1857        let mut diag = tcx.dcx().struct_span_err(
1858            ty_span,
1859            ::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}"),
1860        );
1861        diag.code(E0690);
1862
1863        // Label for the type.
1864        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}"));
1865        // Label for each non-trivial field.
1866        for field in non_trivial_fields {
1867            let msg = match field.reason {
1868                NonTrivialReason::UnknownLayout => {
1869                    ::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")
1870                }
1871                NonTrivialReason::NonZeroSized => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this field has non-zero size"))
    })format!("this field has non-zero size"),
1872                NonTrivialReason::NonTrivialAlignment => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this field requires alignment"))
    })format!("this field requires alignment"),
1873                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!(
1874                    "this field contains `{inside}`, which has private fields, so it could become non-zero-sized in the future"
1875                ),
1876                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!(
1877                    "this field contains `{ty}`, which is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future"
1878                ),
1879                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!(
1880                    "this field contains `{ty}`, which is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets"
1881                ),
1882            };
1883            diag.span_label(field.span, msg);
1884        }
1885
1886        diag.emit();
1887        return;
1888    }
1889}
1890
1891#[allow(trivial_numeric_casts)]
1892fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1893    let def = tcx.adt_def(def_id);
1894    def.destructor(tcx); // force the destructor to be evaluated
1895
1896    if def.variants().is_empty() {
1897        {
    {
        '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 } => {
1898            struct_span_code_err!(
1899                tcx.dcx(),
1900                reprs.first().map(|repr| repr.1).unwrap_or(*first_span),
1901                E0084,
1902                "unsupported representation for zero-variant enum"
1903            )
1904            .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1905            .emit();
1906        });
1907    }
1908
1909    for v in def.variants() {
1910        if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1911            tcx.ensure_ok().typeck(discr_def_id.expect_local());
1912        }
1913    }
1914
1915    if def.repr().int.is_none() {
1916        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));
1917        let get_disr = |var: &ty::VariantDef| match var.discr {
1918            ty::VariantDiscr::Explicit(disr) => Some(disr),
1919            ty::VariantDiscr::Relative(_) => None,
1920        };
1921
1922        let non_unit = def.variants().iter().find(|var| !is_unit(var));
1923        let disr_unit =
1924            def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var));
1925        let disr_non_unit =
1926            def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var));
1927
1928        if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) {
1929            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!(
1930                tcx.dcx(),
1931                tcx.def_span(def_id),
1932                E0732,
1933                "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"
1934            );
1935            if let Some(disr_non_unit) = disr_non_unit {
1936                err.span_label(
1937                    tcx.def_span(disr_non_unit),
1938                    "explicit discriminant on non-unit variant specified here",
1939                );
1940            } else {
1941                err.span_label(
1942                    tcx.def_span(disr_unit.unwrap()),
1943                    "explicit discriminant specified here",
1944                );
1945                err.span_label(
1946                    tcx.def_span(non_unit.unwrap().def_id),
1947                    "non-unit discriminant declared here",
1948                );
1949            }
1950            err.emit();
1951        }
1952    }
1953
1954    detect_discriminant_duplicate(tcx, def);
1955    check_transparent(tcx, def);
1956}
1957
1958/// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1959fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1960    // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1961    // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1962    let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1963        let var = adt.variant(idx); // HIR for the duplicate discriminant
1964        let (span, display_discr) = match var.discr {
1965            ty::VariantDiscr::Explicit(discr_def_id) => {
1966                // In the case the discriminant is both a duplicate and overflowed, let the user know
1967                if let hir::Node::AnonConst(expr) =
1968                    tcx.hir_node_by_def_id(discr_def_id.expect_local())
1969                    && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1970                    && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1971                    && *lit_value != dis.val
1972                {
1973                    (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}`)"))
1974                } else {
1975                    // Otherwise, format the value as-is
1976                    (tcx.def_span(discr_def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", dis))
    })format!("`{dis}`"))
1977                }
1978            }
1979            // This should not happen.
1980            ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", dis))
    })format!("`{dis}`")),
1981            ty::VariantDiscr::Relative(distance_to_explicit) => {
1982                // At this point we know this discriminant is a duplicate, and was not explicitly
1983                // assigned by the user. Here we iterate backwards to fetch the HIR for the last
1984                // explicitly assigned discriminant, and letting the user know that this was the
1985                // increment startpoint, and how many steps from there leading to the duplicate
1986                if let Some(explicit_idx) =
1987                    idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1988                {
1989                    let explicit_variant = adt.variant(explicit_idx);
1990                    let ve_ident = var.name;
1991                    let ex_ident = explicit_variant.name;
1992                    let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1993
1994                    err.span_label(
1995                        tcx.def_span(explicit_variant.def_id),
1996                        ::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!(
1997                            "discriminant for `{ve_ident}` incremented from this startpoint \
1998                            (`{ex_ident}` + {distance_to_explicit} {sp} later \
1999                             => `{ve_ident}` = {dis})"
2000                        ),
2001                    );
2002                }
2003
2004                (tcx.def_span(var.def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", dis))
    })format!("`{dis}`"))
2005            }
2006        };
2007
2008        err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} assigned here", display_discr))
    })format!("{display_discr} assigned here"));
2009    };
2010
2011    let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
2012
2013    // Here we loop through the discriminants, comparing each discriminant to another.
2014    // When a duplicate is detected, we instantiate an error and point to both
2015    // initial and duplicate value. The duplicate discriminant is then discarded by swapping
2016    // it with the last element and decrementing the `vec.len` (which is why we have to evaluate
2017    // `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
2018    // style as we are mutating `discrs` on the fly).
2019    let mut i = 0;
2020    while i < discrs.len() {
2021        let var_i_idx = discrs[i].0;
2022        let mut error: Option<Diag<'_, _>> = None;
2023
2024        let mut o = i + 1;
2025        while o < discrs.len() {
2026            let var_o_idx = discrs[o].0;
2027
2028            if discrs[i].1.val == discrs[o].1.val {
2029                let err = error.get_or_insert_with(|| {
2030                    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!(
2031                        tcx.dcx(),
2032                        tcx.def_span(adt.did()),
2033                        E0081,
2034                        "discriminant value `{}` assigned more than once",
2035                        discrs[i].1,
2036                    );
2037
2038                    report(discrs[i].1, var_i_idx, &mut ret);
2039
2040                    ret
2041                });
2042
2043                report(discrs[o].1, var_o_idx, err);
2044
2045                // Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
2046                discrs[o] = *discrs.last().unwrap();
2047                discrs.pop();
2048            } else {
2049                o += 1;
2050            }
2051        }
2052
2053        if let Some(e) = error {
2054            e.emit();
2055        }
2056
2057        i += 1;
2058    }
2059}
2060
2061fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2062    let generics = tcx.generics_of(def_id);
2063    if generics.own_counts().types == 0 {
2064        return;
2065    }
2066
2067    let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
2068    if ty.references_error() {
2069        // If there is already another error, do not emit an error for not using a type parameter.
2070        return;
2071    }
2072
2073    // Lazily calculated because it is only needed in case of an error.
2074    let bounded_params = LazyCell::new(|| {
2075        tcx.explicit_predicates_of(def_id)
2076            .predicates
2077            .iter()
2078            .filter_map(|(predicate, span)| {
2079                let bounded_ty = match predicate.kind().skip_binder() {
2080                    ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
2081                    ty::ClauseKind::TypeOutlives(pred) => pred.0,
2082                    _ => return None,
2083                };
2084                if let ty::Param(param) = bounded_ty.kind() {
2085                    Some((param.index, span))
2086                } else {
2087                    None
2088                }
2089            })
2090            // FIXME: This assumes that elaborated `Sized` bounds come first (which does hold at the
2091            // time of writing). This is a bit fragile since we later use the span to detect elaborated
2092            // `Sized` bounds. If they came last for example, this would break `Trait + /*elab*/Sized`
2093            // since it would overwrite the span of the user-written bound. This could be fixed by
2094            // folding the spans with `Span::to` which requires a bit of effort I think.
2095            .collect::<FxIndexMap<_, _>>()
2096    });
2097
2098    let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
2099    for leaf in ty.walk() {
2100        if let GenericArgKind::Type(leaf_ty) = leaf.kind()
2101            && let ty::Param(param) = leaf_ty.kind()
2102        {
2103            {
    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:2103",
                        "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(2103u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("found use of ty param {0:?}",
                                                    param) as &dyn Value))])
            });
    } else { ; }
};debug!("found use of ty param {:?}", param);
2104            params_used.insert(param.index);
2105        }
2106    }
2107
2108    for param in &generics.own_params {
2109        if !params_used.contains(param.index)
2110            && let ty::GenericParamDefKind::Type { .. } = param.kind
2111        {
2112            let span = tcx.def_span(param.def_id);
2113            let param_name = Ident::new(param.name, span);
2114
2115            // The corresponding predicates are post-`Sized`-elaboration. Therefore we
2116            // * check for emptiness to detect lone user-written `?Sized` bounds
2117            // * compare the param span to the pred span to detect lone user-written `Sized` bounds
2118            let has_explicit_bounds = bounded_params.is_empty()
2119                || (*bounded_params).get(&param.index).is_some_and(|&&pred_sp| pred_sp != span);
2120            let const_param_help = !has_explicit_bounds;
2121
2122            let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2123                span,
2124                param_name,
2125                param_def_kind: tcx.def_descr(param.def_id),
2126                help: errors::UnusedGenericParameterHelp::TyAlias { param_name },
2127                usage_spans: ::alloc::vec::Vec::new()vec![],
2128                const_param_help,
2129            });
2130            diag.code(E0091);
2131            diag.emit();
2132        }
2133    }
2134}
2135
2136/// Emit an error for recursive opaque types.
2137///
2138/// If this is a return `impl Trait`, find the item's return expressions and point at them. For
2139/// direct recursion this is enough, but for indirect recursion also point at the last intermediary
2140/// `impl Trait`.
2141///
2142/// If all the return expressions evaluate to `!`, then we explain that the error will go away
2143/// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
2144fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
2145    let span = tcx.def_span(opaque_def_id);
2146    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");
2147
2148    let mut label = false;
2149    if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
2150        let typeck_results = tcx.typeck(def_id);
2151        if visitor
2152            .returns
2153            .iter()
2154            .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
2155            .all(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Never => true,
    _ => false,
}matches!(ty.kind(), ty::Never))
2156        {
2157            let spans = visitor
2158                .returns
2159                .iter()
2160                .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
2161                .map(|expr| expr.span)
2162                .collect::<Vec<Span>>();
2163            let span_len = spans.len();
2164            if span_len == 1 {
2165                err.span_label(spans[0], "this returned value is of `!` type");
2166            } else {
2167                let mut multispan: MultiSpan = spans.clone().into();
2168                for span in spans {
2169                    multispan.push_span_label(span, "this returned value is of `!` type");
2170                }
2171                err.span_note(multispan, "these returned values have a concrete \"never\" type");
2172            }
2173            err.help("this error will resolve once the item's body returns a concrete type");
2174        } else {
2175            let mut seen = FxHashSet::default();
2176            seen.insert(span);
2177            err.span_label(span, "recursive opaque type");
2178            label = true;
2179            for (sp, ty) in visitor
2180                .returns
2181                .iter()
2182                .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
2183                .filter(|(_, ty)| !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Never => true,
    _ => false,
}matches!(ty.kind(), ty::Never))
2184            {
2185                #[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)]
2186                struct OpaqueTypeCollector {
2187                    opaques: Vec<DefId>,
2188                    closures: Vec<DefId>,
2189                }
2190                impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
2191                    fn visit_ty(&mut self, t: Ty<'tcx>) {
2192                        match *t.kind() {
2193                            ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id: def }, .. }) => {
2194                                self.opaques.push(def);
2195                            }
2196                            ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
2197                                self.closures.push(def_id);
2198                                t.super_visit_with(self);
2199                            }
2200                            _ => t.super_visit_with(self),
2201                        }
2202                    }
2203                }
2204
2205                let mut visitor = OpaqueTypeCollector::default();
2206                ty.visit_with(&mut visitor);
2207                for def_id in visitor.opaques {
2208                    let ty_span = tcx.def_span(def_id);
2209                    if !seen.contains(&ty_span) {
2210                        let descr = if ty.is_opaque() { "opaque " } else { "" };
2211                        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}`"));
2212                        seen.insert(ty_span);
2213                    }
2214                    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}`"));
2215                }
2216
2217                for closure_def_id in visitor.closures {
2218                    let Some(closure_local_did) = closure_def_id.as_local() else {
2219                        continue;
2220                    };
2221                    let typeck_results = tcx.typeck(closure_local_did);
2222
2223                    let mut label_match = |ty: Ty<'_>, span| {
2224                        for arg in ty.walk() {
2225                            if let ty::GenericArgKind::Type(ty) = arg.kind()
2226                                && let ty::Alias(ty::AliasTy {
2227                                    kind: ty::Opaque { def_id: captured_def_id },
2228                                    ..
2229                                }) = *ty.kind()
2230                                && captured_def_id == opaque_def_id.to_def_id()
2231                            {
2232                                err.span_label(
2233                                    span,
2234                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} captures itself here",
                tcx.def_descr(closure_def_id)))
    })format!(
2235                                        "{} captures itself here",
2236                                        tcx.def_descr(closure_def_id)
2237                                    ),
2238                                );
2239                            }
2240                        }
2241                    };
2242
2243                    // Label any closure upvars that capture the opaque
2244                    for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
2245                    {
2246                        label_match(capture.place.ty(), capture.get_path_span(tcx));
2247                    }
2248                    // Label any coroutine locals that capture the opaque
2249                    if tcx.is_coroutine(closure_def_id)
2250                        && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
2251                    {
2252                        for interior_ty in &coroutine_layout.field_tys {
2253                            label_match(interior_ty.ty, interior_ty.source_info.span);
2254                        }
2255                    }
2256                }
2257            }
2258        }
2259    }
2260    if !label {
2261        err.span_label(span, "cannot resolve opaque type");
2262    }
2263    err.emit()
2264}
2265
2266pub(super) fn check_coroutine_obligations(
2267    tcx: TyCtxt<'_>,
2268    def_id: LocalDefId,
2269) -> Result<(), ErrorGuaranteed> {
2270    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()));
2271
2272    let typeck_results = tcx.typeck(def_id);
2273    let param_env = tcx.param_env(def_id);
2274
2275    {
    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:2275",
                        "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(2275u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                        ::tracing_core::field::FieldSet::new(&["typeck_results.coroutine_stalled_predicates"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&typeck_results.coroutine_stalled_predicates)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?typeck_results.coroutine_stalled_predicates);
2276
2277    let mode = if tcx.next_trait_solver_globally() {
2278        // This query is conceptually between HIR typeck and
2279        // MIR borrowck. We use the opaque types defined by HIR
2280        // and ignore region constraints.
2281        TypingMode::borrowck(tcx, def_id)
2282    } else {
2283        TypingMode::analysis_in_body(tcx, def_id)
2284    };
2285
2286    // Typeck writeback gives us predicates with their regions erased.
2287    // We only need to check the goals while ignoring lifetimes to give good
2288    // error message and to avoid breaking the assumption of `mir_borrowck`
2289    // that all obligations already hold modulo regions.
2290    let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
2291
2292    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2293    for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
2294        ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
2295    }
2296
2297    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2298    {
    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:2298",
                        "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(2298u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                        ::tracing_core::field::FieldSet::new(&["errors"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&errors) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?errors);
2299    if !errors.is_empty() {
2300        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2301    }
2302
2303    if !tcx.next_trait_solver_globally() {
2304        // Check that any hidden types found when checking these stalled coroutine obligations
2305        // are valid.
2306        for (key, ty) in infcx.take_opaque_types() {
2307            let hidden_type = infcx.resolve_vars_if_possible(ty);
2308            let key = infcx.resolve_vars_if_possible(key);
2309            sanity_check_found_hidden_type(tcx, key, hidden_type)?;
2310        }
2311    } else {
2312        // We're not checking region constraints here, so we can simply drop the
2313        // added opaque type uses in `TypingMode::PostTypeckUntilBorrowck`.
2314        let _ = infcx.take_opaque_types();
2315    }
2316
2317    Ok(())
2318}
2319
2320pub(super) fn check_potentially_region_dependent_goals<'tcx>(
2321    tcx: TyCtxt<'tcx>,
2322    def_id: LocalDefId,
2323) -> Result<(), ErrorGuaranteed> {
2324    if !tcx.next_trait_solver_globally() {
2325        return Ok(());
2326    }
2327    let typeck_results = tcx.typeck(def_id);
2328    let param_env = tcx.param_env(def_id);
2329
2330    // We use `TypingMode::PostTypeckUntilBorrowck` as we want to use the opaque types computed by HIR typeck.
2331    let typing_mode = TypingMode::borrowck(tcx, def_id);
2332    let infcx = tcx.infer_ctxt().ignoring_regions().build(typing_mode);
2333    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2334    for (predicate, cause) in &typeck_results.potentially_region_dependent_goals {
2335        let predicate = fold_regions(tcx, *predicate, |_, _| {
2336            infcx.next_region_var(RegionVariableOrigin::Misc(cause.span))
2337        });
2338        ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate));
2339    }
2340
2341    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2342    {
    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:2342",
                        "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(2342u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                        ::tracing_core::field::FieldSet::new(&["errors"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&errors) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?errors);
2343    if errors.is_empty() { Ok(()) } else { Err(infcx.err_ctxt().report_fulfillment_errors(errors)) }
2344}