Skip to main content

rustc_hir_analysis/check/
check.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (span, definition_def_id) =
                if let Some((span, def_id)) =
                        best_definition_site_of_opaque(tcx, def_id, origin) {
                    (span, Some(def_id))
                } else { (tcx.def_span(def_id), None) };
            let defining_use_anchor =
                match origin {
                    hir::OpaqueTyOrigin::FnReturn { parent, .. } |
                        hir::OpaqueTyOrigin::AsyncFn { parent, .. } |
                        hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
                };
            let param_env = tcx.param_env(defining_use_anchor);
            let infcx =
                tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
                        TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
                    } else {
                        TypingMode::analysis_in_body(tcx, defining_use_anchor)
                    });
            let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
            let args =
                match origin {
                    hir::OpaqueTyOrigin::FnReturn { parent, .. } |
                        hir::OpaqueTyOrigin::AsyncFn { parent, .. } |
                        hir::OpaqueTyOrigin::TyAlias { parent, .. } =>
                        GenericArgs::identity_for_item(tcx,
                                parent).extend_to(tcx, def_id.to_def_id(),
                            |param, _|
                                {
                                    tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
                                }),
                };
            let opaque_ty =
                Ty::new_opaque(tcx, ty::IsRigid::No, def_id.to_def_id(),
                    args);
            let hidden_ty =
                tcx.type_of(def_id.to_def_id()).instantiate(tcx,
                        args).skip_norm_wip();
            let hidden_ty =
                fold_regions(tcx, hidden_ty,
                    |re, _dbi|
                        match re.kind() {
                            ty::ReErased =>
                                infcx.next_region_var(RegionVariableOrigin::Misc(span)),
                            _ => re,
                        });
            for (predicate, pred_span) in
                tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx,
                        args).map(Unnormalized::skip_norm_wip) {
                let predicate =
                    predicate.fold_with(&mut BottomUpFolder {
                                tcx,
                                ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
                                lt_op: |lt| lt,
                                ct_op: |ct| ct,
                            });
                ocx.register_obligation(Obligation::new(tcx,
                        ObligationCause::new(span, def_id,
                            ObligationCauseCode::OpaqueTypeBound(pred_span,
                                definition_def_id)), param_env, predicate));
            }
            let misc_cause = ObligationCause::misc(span, def_id);
            match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
                Ok(()) => {}
                Err(ty_err) => {
                    let ty_err = ty_err.to_string(tcx);
                    let guar =
                        tcx.dcx().span_delayed_bug(span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("could not unify `{0}` with revealed type:\n{1}",
                                            hidden_ty, ty_err))
                                }));
                    return Err(guar);
                }
            }
            let predicate =
                ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
            ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(),
                    param_env, predicate));
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if let TraitErrors::HasErrors(errors) = errors {
                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.deeply_resolve_ignoring_regions(ty.ty);
                    key = infcx.deeply_resolve_ignoring_regions(key);
                    sanity_check_found_hidden_type(tcx, key, ty)?;
                }
                Ok(())
            }
        }
    }
}#[instrument(level = "debug", skip(tcx))]
294fn check_opaque_meets_bounds<'tcx>(
295    tcx: TyCtxt<'tcx>,
296    def_id: LocalDefId,
297    origin: hir::OpaqueTyOrigin<LocalDefId>,
298) -> Result<(), ErrorGuaranteed> {
299    let (span, definition_def_id) =
300        if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {
301            (span, Some(def_id))
302        } else {
303            (tcx.def_span(def_id), None)
304        };
305
306    let defining_use_anchor = match origin {
307        hir::OpaqueTyOrigin::FnReturn { parent, .. }
308        | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
309        | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
310    };
311    let param_env = tcx.param_env(defining_use_anchor);
312
313    // FIXME(#132279): Once `PostBorrowck` is supported in the old solver, this branch should be removed.
314    let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
315        TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
316    } else {
317        TypingMode::analysis_in_body(tcx, defining_use_anchor)
318    });
319    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
320
321    let args = match origin {
322        hir::OpaqueTyOrigin::FnReturn { parent, .. }
323        | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
324        | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(
325            tcx, parent,
326        )
327        .extend_to(tcx, def_id.to_def_id(), |param, _| {
328            tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
329        }),
330    };
331
332    let opaque_ty = Ty::new_opaque(tcx, ty::IsRigid::No, def_id.to_def_id(), args);
333
334    // `ReErased` regions appear in the "parent_args" of closures/coroutines.
335    // We're ignoring them here and replacing them with fresh region variables.
336    // See tests in ui/type-alias-impl-trait/closure_{parent_args,wf_outlives}.rs.
337    //
338    // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it
339    // here rather than using ReErased.
340    let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args).skip_norm_wip();
341    let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {
342        ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)),
343        _ => re,
344    });
345
346    // HACK: We eagerly instantiate some bounds to report better errors for them...
347    // This isn't necessary for correctness, since we register these bounds when
348    // equating the opaque below, but we should clean this up in the new solver.
349    for (predicate, pred_span) in tcx
350        .explicit_item_bounds(def_id)
351        .iter_instantiated_copied(tcx, args)
352        .map(Unnormalized::skip_norm_wip)
353    {
354        let predicate = predicate.fold_with(&mut BottomUpFolder {
355            tcx,
356            ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
357            lt_op: |lt| lt,
358            ct_op: |ct| ct,
359        });
360
361        ocx.register_obligation(Obligation::new(
362            tcx,
363            ObligationCause::new(
364                span,
365                def_id,
366                ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
367            ),
368            param_env,
369            predicate,
370        ));
371    }
372
373    let misc_cause = ObligationCause::misc(span, def_id);
374    // FIXME: We should just register the item bounds here, rather than equating.
375    // FIXME(const_trait_impl): When we do that, please make sure to also register
376    // the `[const]` bounds.
377    match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
378        Ok(()) => {}
379        Err(ty_err) => {
380            // Some types may be left "stranded" if they can't be reached
381            // from a lowered rustc_middle bound but they're mentioned in the HIR.
382            // This will happen, e.g., when a nested opaque is inside of a non-
383            // existent associated type, like `impl Trait<Missing = impl Trait>`.
384            // See <tests/ui/impl-trait/stranded-opaque.rs>.
385            let ty_err = ty_err.to_string(tcx);
386            let guar = tcx.dcx().span_delayed_bug(
387                span,
388                format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
389            );
390            return Err(guar);
391        }
392    }
393
394    // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
395    // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
396    // hidden type is well formed even without those bounds.
397    let predicate =
398        ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
399    ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
400
401    // Check that all obligations are satisfied by the implementation's
402    // version.
403    let errors = ocx.evaluate_obligations_error_on_ambiguity();
404    if let TraitErrors::HasErrors(errors) = errors {
405        let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
406        return Err(guar);
407    }
408
409    // FIXME(impl_trait_in_assoc_type): This computes the implied bounds
410    // while being able to normalize opaque types. This is unsound if checking that the
411    // opaque type is well-formed relies on an implied bound mentioning that opaque type.
412    // This should only affect TAIT as this function is not soundness critical for RPITs.
413    //
414    // cc trait-system-refactor-initiative#159
415    let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
416    ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
417
418    if infcx.next_trait_solver() {
419        Ok(())
420    } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
421        origin
422    {
423        // HACK: this should also fall through to the hidden type check below, but the original
424        // implementation had a bug where equivalent lifetimes are not identical. This caused us
425        // to reject existing stable code that is otherwise completely fine. The real fix is to
426        // compare the hidden types via our type equivalence/relation infra instead of doing an
427        // identity check.
428        let _ = infcx.take_opaque_types();
429        Ok(())
430    } else {
431        // Check that any hidden types found during wf checking match the hidden types that `type_of` sees.
432        for (mut key, mut ty) in infcx.take_opaque_types() {
433            ty.ty = infcx.deeply_resolve_ignoring_regions(ty.ty);
434            key = infcx.deeply_resolve_ignoring_regions(key);
435            sanity_check_found_hidden_type(tcx, key, ty)?;
436        }
437        Ok(())
438    }
439}
440
441fn best_definition_site_of_opaque<'tcx>(
442    tcx: TyCtxt<'tcx>,
443    opaque_def_id: LocalDefId,
444    origin: hir::OpaqueTyOrigin<LocalDefId>,
445) -> Option<(Span, LocalDefId)> {
446    struct TaitConstraintLocator<'tcx> {
447        opaque_def_id: LocalDefId,
448        tcx: TyCtxt<'tcx>,
449    }
450    impl<'tcx> TaitConstraintLocator<'tcx> {
451        fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
452            if !self.tcx.has_typeck_results(item_def_id) {
453                return ControlFlow::Continue(());
454            }
455
456            let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
457            // Don't try to check items that cannot possibly constrain the type.
458            if !opaque_types_defined_by.contains(&self.opaque_def_id) {
459                return ControlFlow::Continue(());
460            }
461
462            if let Some(hidden_ty) = self
463                .tcx
464                .mir_borrowck(item_def_id)
465                .ok()
466                .and_then(|opaque_types| opaque_types.get(&self.opaque_def_id))
467            {
468                ControlFlow::Break((hidden_ty.span, item_def_id))
469            } else {
470                ControlFlow::Continue(())
471            }
472        }
473    }
474    impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
475        type NestedFilter = nested_filter::All;
476        type Result = ControlFlow<(Span, LocalDefId)>;
477        fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
478            self.tcx
479        }
480        fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
481            intravisit::walk_expr(self, ex)
482        }
483        fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
484            self.check(it.owner_id.def_id)?;
485            intravisit::walk_item(self, it)
486        }
487        fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
488            self.check(it.owner_id.def_id)?;
489            intravisit::walk_impl_item(self, it)
490        }
491        fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
492            self.check(it.owner_id.def_id)?;
493            intravisit::walk_trait_item(self, it)
494        }
495        fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
496            intravisit::walk_foreign_item(self, it)
497        }
498    }
499
500    let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
501    match origin {
502        hir::OpaqueTyOrigin::FnReturn { parent, .. }
503        | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
504        hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
505            let impl_def_id = tcx.local_parent(parent);
506            for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
507                match assoc.kind {
508                    ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
509                        if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
510                        {
511                            return Some(span);
512                        }
513                    }
514                    ty::AssocKind::Type { .. } => {}
515                }
516            }
517
518            None
519        }
520        hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
521            tcx.hir_walk_toplevel_module(&mut locator).break_value()
522        }
523    }
524}
525
526fn sanity_check_found_hidden_type<'tcx>(
527    tcx: TyCtxt<'tcx>,
528    key: ty::OpaqueTypeKey<'tcx>,
529    mut ty: ty::ProvisionalHiddenType<'tcx>,
530) -> Result<(), ErrorGuaranteed> {
531    if ty.ty.is_ty_var() {
532        // Nothing was actually constrained.
533        return Ok(());
534    }
535    if let &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = ty.ty.kind() {
536        if def_id == key.def_id.to_def_id() && args == key.args {
537            // Nothing was actually constrained, this is an opaque usage that was
538            // only discovered to be opaque after inference vars resolved.
539            return Ok(());
540        }
541    }
542    let erase_re_vars = |ty: Ty<'tcx>| {
543        fold_regions(tcx, ty, |r, _| match r.kind() {
544            RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
545            _ => r,
546        })
547    };
548    // Closures frequently end up containing erased lifetimes in their final representation.
549    // These correspond to lifetime variables that never got resolved, so we patch this up here.
550    ty.ty = erase_re_vars(ty.ty);
551    // Get the hidden type.
552    let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args).skip_norm_wip();
553    let hidden_ty = erase_re_vars(hidden_ty);
554
555    // If the hidden types differ, emit a type mismatch diagnostic.
556    if hidden_ty == ty.ty {
557        Ok(())
558    } else {
559        let span = tcx.def_span(key.def_id);
560        let other = ty::ProvisionalHiddenType { ty: hidden_ty, span };
561        Err(ty.build_mismatch_error(&other, tcx)?.emit_err())
562    }
563}
564
565/// Check that the opaque's precise captures list is valid (if present).
566/// We check this for regular `impl Trait`s and also RPITITs, even though the latter
567/// are technically GATs.
568///
569/// This function is responsible for:
570/// 1. Checking that all type/const params are mention in the captures list.
571/// 2. Checking that all lifetimes that are implicitly captured are mentioned.
572/// 3. Asserting that all parameters mentioned in the captures list are invariant.
573fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
574    let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
575    let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
576        hir::GenericBound::Use(bounds, ..) => Some(bounds),
577        _ => None,
578    }) else {
579        // No precise capturing args; nothing to validate
580        return;
581    };
582
583    let mut expected_captures = UnordSet::default();
584    let mut shadowed_captures = UnordSet::default();
585    let mut seen_params = UnordMap::default();
586    let mut prev_non_lifetime_param = None;
587    for arg in precise_capturing_args {
588        let (hir_id, ident) = match *arg {
589            hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
590                hir_id,
591                ident,
592                ..
593            }) => {
594                if prev_non_lifetime_param.is_none() {
595                    prev_non_lifetime_param = Some(ident);
596                }
597                (hir_id, ident)
598            }
599            hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
600                if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
601                    tcx.dcx().emit_err(diagnostics::LifetimesMustBeFirst {
602                        lifetime_span: ident.span,
603                        name: ident.name,
604                        other_span: prev_non_lifetime_param.span,
605                    });
606                }
607                (hir_id, ident)
608            }
609        };
610
611        let ident = ident.normalize_to_macros_2_0();
612        if let Some(span) = seen_params.insert(ident, ident.span) {
613            tcx.dcx().emit_err(diagnostics::DuplicatePreciseCapture {
614                name: ident.name,
615                first_span: span,
616                second_span: ident.span,
617            });
618        }
619
620        match tcx.named_bound_var(hir_id) {
621            Some(ResolvedArg::EarlyBound(def_id)) => {
622                expected_captures.insert(def_id.to_def_id());
623
624                // Make sure we allow capturing these lifetimes through `Self` and
625                // `T::Assoc` projection syntax, too. These will occur when we only
626                // see lifetimes are captured after hir-lowering -- this aligns with
627                // the cases that were stabilized with the `impl_trait_projection`
628                // feature -- see <https://github.com/rust-lang/rust/pull/115659>.
629                if let DefKind::LifetimeParam = tcx.def_kind(def_id)
630                    && let Some(def_id) = tcx
631                        .map_opaque_lifetime_to_parent_lifetime(def_id)
632                        .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
633                {
634                    shadowed_captures.insert(def_id);
635                }
636            }
637            _ => {
638                tcx.dcx()
639                    .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
640            }
641        }
642    }
643
644    let variances = tcx.variances_of(opaque_def_id);
645    let mut def_id = Some(opaque_def_id.to_def_id());
646    while let Some(generics) = def_id {
647        let generics = tcx.generics_of(generics);
648        def_id = generics.parent;
649
650        for param in &generics.own_params {
651            if expected_captures.contains(&param.def_id) {
652                {
    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!(
653                    variances[param.index as usize],
654                    ty::Invariant,
655                    "precise captured param should be invariant"
656                );
657                continue;
658            }
659            // If a param is shadowed by a early-bound (duplicated) lifetime, then
660            // it may or may not be captured as invariant, depending on if it shows
661            // up through `Self` or `T::Assoc` syntax.
662            if shadowed_captures.contains(&param.def_id) {
663                continue;
664            }
665
666            match param.kind {
667                ty::GenericParamDefKind::Lifetime => {
668                    let use_span = tcx.def_span(param.def_id);
669                    let opaque_span = tcx.def_span(opaque_def_id);
670                    // Check if the lifetime param was captured but isn't named in the precise captures list.
671                    if variances[param.index as usize] == ty::Invariant {
672                        if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
673                            && let Some(def_id) = tcx
674                                .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
675                                .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
676                        {
677                            tcx.dcx().emit_err(diagnostics::LifetimeNotCaptured {
678                                opaque_span,
679                                use_span,
680                                param_span: tcx.def_span(def_id),
681                            });
682                        } else {
683                            if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
684                                tcx.dcx().emit_err(diagnostics::LifetimeImplicitlyCaptured {
685                                    opaque_span,
686                                    param_span: tcx.def_span(param.def_id),
687                                });
688                            } else {
689                                // If the `use_span` is actually just the param itself, then we must
690                                // have not duplicated the lifetime but captured the original.
691                                // The "effective" `use_span` will be the span of the opaque itself,
692                                // and the param span will be the def span of the param.
693                                tcx.dcx().emit_err(diagnostics::LifetimeNotCaptured {
694                                    opaque_span,
695                                    use_span: opaque_span,
696                                    param_span: use_span,
697                                });
698                            }
699                        }
700                        continue;
701                    }
702                }
703                ty::GenericParamDefKind::Type { .. } => {
704                    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) {
705                        // FIXME(precise_capturing): Structured suggestion for this would be useful
706                        tcx.dcx().emit_err(diagnostics::SelfTyNotCaptured {
707                            trait_span: tcx.def_span(param.def_id),
708                            opaque_span: tcx.def_span(opaque_def_id),
709                        });
710                    } else {
711                        // FIXME(precise_capturing): Structured suggestion for this would be useful
712                        tcx.dcx().emit_err(diagnostics::ParamNotCaptured {
713                            param_span: tcx.def_span(param.def_id),
714                            opaque_span: tcx.def_span(opaque_def_id),
715                            kind: "type",
716                        });
717                    }
718                }
719                ty::GenericParamDefKind::Const { .. } => {
720                    // FIXME(precise_capturing): Structured suggestion for this would be useful
721                    tcx.dcx().emit_err(diagnostics::ParamNotCaptured {
722                        param_span: tcx.def_span(param.def_id),
723                        opaque_span: tcx.def_span(opaque_def_id),
724                        kind: "const",
725                    });
726                }
727            }
728        }
729    }
730}
731
732fn is_enum_of_nonnullable_ptr<'tcx>(
733    tcx: TyCtxt<'tcx>,
734    adt_def: AdtDef<'tcx>,
735    args: GenericArgsRef<'tcx>,
736) -> bool {
737    if adt_def.repr().inhibit_enum_layout_opt() {
738        return false;
739    }
740
741    let [var_one, var_two] = &adt_def.variants().raw[..] else {
742        return false;
743    };
744    let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
745        return false;
746    };
747    #[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(..))
748}
749
750fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
751    if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
752        if match tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {
753            ty::RawPtr(_, _) => false,
754            ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
755            _ => true,
756        } {
757            tcx.dcx().emit_err(diagnostics::LinkageType { span: tcx.def_span(def_id) });
758        }
759    }
760}
761
762pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
763    let mut res = Ok(());
764    let generics = tcx.generics_of(def_id);
765
766    for param in &generics.own_params {
767        match param.kind {
768            ty::GenericParamDefKind::Lifetime { .. } => {}
769            ty::GenericParamDefKind::Type { has_default, .. } => {
770                if has_default {
771                    tcx.ensure_ok().type_of(param.def_id);
772                }
773            }
774            ty::GenericParamDefKind::Const { has_default, .. } => {
775                tcx.ensure_ok().type_of(param.def_id);
776                if has_default {
777                    // need to store default and type of default
778                    let ct = tcx.const_param_default(param.def_id).skip_binder();
779                    if let ty::ConstKind::Alias(_, alias_const) = ct.kind() {
780                        let def_id = match alias_const.kind {
781                            ty::AliasConstKind::Projection { def_id } => def_id,
782                            ty::AliasConstKind::InherentSelf { def_id } => {
783                                // NOTE: typically, InherentSelf is illegal to pass to type_of,
784                                // because the generic args are incorrect (type_of expects impl-form
785                                // arguments). However, we are just checking ensure_ok().type_of(),
786                                // we are not instantiating the result, so it's OK here.
787                                def_id
788                            }
789                            ty::AliasConstKind::InherentImpl { .. } => ::rustc_span::macros::bug_impl(Some(tcx.def_span(param.def_id)),
    format_args!("const_param_default should return an unnormalized constant, which should always be InherentSelf, not InherentImpl"),
    Location::caller())span_bug!(
790                                tcx.def_span(param.def_id),
791                                "const_param_default should return an unnormalized constant, which should always be InherentSelf, not InherentImpl"
792                            ),
793                            ty::AliasConstKind::Free { def_id } => def_id,
794                            ty::AliasConstKind::Anon { def_id } => def_id,
795                        };
796                        tcx.ensure_ok().type_of(def_id);
797                    }
798                }
799            }
800        }
801    }
802
803    match tcx.def_kind(def_id) {
804        DefKind::Static { .. } => {
805            tcx.ensure_ok().generics_of(def_id);
806            tcx.ensure_ok().type_of(def_id);
807            tcx.ensure_ok().clauses_of(def_id);
808
809            check_static_inhabited(tcx, def_id);
810            check_static_linkage(tcx, def_id);
811            let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
812            res = res.and(wfcheck::check_static_item(
813                tcx, def_id, ty, /* should_check_for_sync */ true,
814            ));
815
816            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
817            // checks. Returning early here does not miss any checks and
818            // avoids this query from having a direct dependency edge on the HIR
819            return res;
820        }
821        DefKind::Enum => {
822            tcx.ensure_ok().generics_of(def_id);
823            tcx.ensure_ok().type_of(def_id);
824            tcx.ensure_ok().clauses_of(def_id);
825            crate::collect::check_enum_variant_types(tcx, def_id);
826            check_enum(tcx, def_id);
827            check_variances_for_type_defn(tcx, def_id);
828            res = res.and(check_type_defn(tcx, def_id, true));
829            // enums are fully handled by the type based check and have no hir wfcheck logic
830            return res;
831        }
832        DefKind::Fn => {
833            tcx.ensure_ok().generics_of(def_id);
834            tcx.ensure_ok().type_of(def_id);
835            tcx.ensure_ok().clauses_of(def_id);
836            tcx.ensure_ok().fn_sig(def_id);
837            tcx.ensure_ok().codegen_fn_attrs(def_id);
838            if let Some(i) = tcx.intrinsic(def_id) {
839                intrinsic::check_intrinsic_type(
840                    tcx,
841                    def_id,
842                    tcx.def_ident_span(def_id).unwrap(),
843                    i.name,
844                )
845            }
846        }
847        DefKind::Impl { of_trait } => {
848            tcx.ensure_ok().generics_of(def_id);
849            tcx.ensure_ok().type_of(def_id);
850            tcx.ensure_ok().clauses_of(def_id);
851            tcx.ensure_ok().associated_items(def_id);
852            if of_trait {
853                let impl_trait_header = tcx.impl_trait_header(def_id);
854                res = res
855                    .and(tcx.ensure_result().coherent_trait(impl_trait_header.trait_ref.def_id()));
856
857                if res.is_ok() {
858                    // Checking this only makes sense if the all trait impls satisfy basic
859                    // requirements (see `coherent_trait` query), otherwise
860                    // we run into infinite recursions a lot.
861                    check_impl_items_against_trait(tcx, def_id, impl_trait_header);
862                }
863            }
864        }
865        DefKind::Trait => {
866            tcx.ensure_ok().generics_of(def_id);
867            tcx.ensure_ok().trait_def(def_id);
868            tcx.ensure_ok().explicit_super_clauses_of(def_id);
869            tcx.ensure_ok().clauses_of(def_id);
870            tcx.ensure_ok().associated_items(def_id);
871            let assoc_items = tcx.associated_items(def_id);
872
873            for &assoc_item in assoc_items.in_definition_order() {
874                match assoc_item.kind {
875                    ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {
876                        let trait_args = GenericArgs::identity_for_item(tcx, def_id);
877                        let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
878                            tcx,
879                            assoc_item,
880                            assoc_item,
881                            ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),
882                        );
883                    }
884                    ty::AssocKind::Const { .. } if assoc_item.defaultness(tcx).has_value() => {
885                        let _: Result<_, rustc_errors::ErrorGuaranteed> =
886                            super::compare_impl_item::compare_const_directness(
887                                tcx, assoc_item, assoc_item,
888                            );
889                    }
890                    _ => {}
891                }
892            }
893            res = res.and(wfcheck::check_trait(tcx, def_id));
894            wfcheck::check_gat_where_clauses(tcx, def_id);
895            // Trait aliases do not have hir checks anymore
896            return res;
897        }
898        DefKind::TraitAlias => {
899            tcx.ensure_ok().generics_of(def_id);
900            tcx.ensure_ok().explicit_implied_clauses_of(def_id);
901            tcx.ensure_ok().explicit_super_clauses_of(def_id);
902            tcx.ensure_ok().clauses_of(def_id);
903            res = res.and(wfcheck::check_trait(tcx, def_id));
904            // Trait aliases do not have hir checks anymore
905            return res;
906        }
907        def_kind @ (DefKind::Struct | DefKind::Union) => {
908            tcx.ensure_ok().generics_of(def_id);
909            tcx.ensure_ok().type_of(def_id);
910            tcx.ensure_ok().clauses_of(def_id);
911
912            let adt = tcx.adt_def(def_id).non_enum_variant();
913            for f in adt.fields.iter() {
914                tcx.ensure_ok().generics_of(f.did);
915                tcx.ensure_ok().type_of(f.did);
916                tcx.ensure_ok().clauses_of(f.did);
917            }
918
919            if let Some((_, ctor_def_id)) = adt.ctor {
920                crate::collect::check_ctor(tcx, ctor_def_id.expect_local());
921            }
922            check_variances_for_type_defn(tcx, def_id);
923            res = res.and(match def_kind {
924                DefKind::Struct => check_struct(tcx, def_id),
925                DefKind::Union => check_union(tcx, def_id),
926                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
927            });
928            // structs and enums are fully handled by the type based check and have no hir wfcheck logic
929            return res;
930        }
931        DefKind::OpaqueTy => {
932            check_opaque_precise_captures(tcx, def_id);
933
934            let origin = tcx.local_opaque_ty_origin(def_id);
935            if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
936            | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin
937                && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
938                && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
939            {
940                // Skip opaques from RPIT in traits with no default body.
941            } else {
942                check_opaque(tcx, def_id);
943            }
944
945            tcx.ensure_ok().clauses_of(def_id);
946            tcx.ensure_ok().explicit_item_bounds(def_id);
947            tcx.ensure_ok().explicit_item_self_bounds(def_id);
948            if tcx.is_conditionally_const(def_id) {
949                tcx.ensure_ok().explicit_implied_const_bounds(def_id);
950                tcx.ensure_ok().const_conditions(def_id);
951            }
952
953            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
954            // checks. Returning early here does not miss any checks and
955            // avoids this query from having a direct dependency edge on the HIR
956            return res;
957        }
958        DefKind::Const => {
959            tcx.ensure_ok().generics_of(def_id);
960            tcx.ensure_ok().type_of(def_id);
961            tcx.ensure_ok().clauses_of(def_id);
962
963            res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
964                let ty = tcx.type_of(def_id).instantiate_identity();
965                let ty_span = tcx.ty_span(def_id);
966                let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
967                wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
968                wfcx.register_bound(
969                    traits::ObligationCause::new(
970                        ty_span,
971                        def_id,
972                        ObligationCauseCode::SizedConstOrStatic,
973                    ),
974                    tcx.param_env(def_id),
975                    ty,
976                    tcx.require_lang_item(LangItem::Sized, ty_span),
977                );
978                check_where_clauses(wfcx, def_id);
979                wfcheck::check_const_item(wfcx, def_id, ty)
980            }));
981
982            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
983            // checks. Returning early here does not miss any checks and
984            // avoids this query from having a direct dependency edge on the HIR
985            return res;
986        }
987        DefKind::TyAlias => {
988            tcx.ensure_ok().generics_of(def_id);
989            tcx.ensure_ok().type_of(def_id);
990            tcx.ensure_ok().clauses_of(def_id);
991            let ty = tcx.type_of(def_id).instantiate_identity();
992            let span = tcx.def_span(def_id);
993            if tcx.type_alias_is_checked(def_id) {
994                res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
995                    let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
996                    wfcx.register_wf_obligation(
997                        span,
998                        Some(WellFormedLoc::Ty(def_id)),
999                        item_ty.into(),
1000                    );
1001                    check_where_clauses(wfcx, def_id);
1002                    Ok(())
1003                }));
1004            } else {
1005                check_type_alias_type_params_are_used(tcx, def_id);
1006                res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1007                    // HACK: We sometimes incidentally check that const arguments have the correct
1008                    // type as a side effect of the anon const desugaring. To make this "consistent"
1009                    // for users we explicitly check `ConstArgHasType` clauses so that const args
1010                    // that don't go through an anon const still have their types checked.
1011                    //
1012                    // We use the unnormalized type as this mirrors the behaviour that we previously
1013                    // would have had when all const arguments were anon consts.
1014                    //
1015                    // Changing this to normalized obligations is a breaking change:
1016                    // `type Bar = [(); panic!()];` would become an error
1017                    if let Some(unnormalized_obligations) = wfcx.unnormalized_obligations(span, ty.skip_norm_wip())
1018                    {
1019                        let filtered_obligations =
1020                            unnormalized_obligations.into_iter().filter(|o| {
1021                                #[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(),
1022                                    ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _))
1023                                    if matches!(ct.kind(), ty::ConstKind::Param(..)))
1024                            });
1025                        wfcx.ocx.register_obligations(filtered_obligations)
1026                    }
1027                    Ok(())
1028                }));
1029            }
1030
1031            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1032            // checks. Returning early here does not miss any checks and
1033            // avoids this query from having a direct dependency edge on the HIR
1034            return res;
1035        }
1036        DefKind::ForeignMod => {
1037            let it = tcx.hir_expect_item(def_id);
1038            let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
1039                return Ok(());
1040            };
1041
1042            check_abi(tcx, it.hir_id(), it.span, abi);
1043
1044            for &item in items {
1045                let def_id = item.owner_id.def_id;
1046
1047                let generics = tcx.generics_of(def_id);
1048                let own_counts = generics.own_counts();
1049                if generics.own_params.len() - own_counts.lifetimes != 0 {
1050                    let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
1051                        (_, 0) => ("type", "types", Some("u32")),
1052                        // We don't specify an example value, because we can't generate
1053                        // a valid value for any type.
1054                        (0, _) => ("const", "consts", None),
1055                        _ => ("type or const", "types or consts", None),
1056                    };
1057                    let name = if {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcEiiForeignItem) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcEiiForeignItem) {
1058                        "externally implementable items"
1059                    } else {
1060                        "foreign items"
1061                    };
1062
1063                    let span = tcx.def_span(def_id);
1064                    {
    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!(
1065                        tcx.dcx(),
1066                        span,
1067                        E0044,
1068                        "{name} may not have {kinds} parameters",
1069                    )
1070                    .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"))
1071                    .with_help(
1072                        // FIXME: once we start storing spans for type arguments, turn this
1073                        // into a suggestion.
1074                        ::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!(
1075                            "replace the {} parameters with concrete {}{}",
1076                            kinds,
1077                            kinds_pl,
1078                            egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
1079                        ),
1080                    )
1081                    .emit();
1082                }
1083
1084                tcx.ensure_ok().generics_of(def_id);
1085                tcx.ensure_ok().type_of(def_id);
1086                tcx.ensure_ok().clauses_of(def_id);
1087                if tcx.is_conditionally_const(def_id) {
1088                    tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1089                    tcx.ensure_ok().const_conditions(def_id);
1090                }
1091                match tcx.def_kind(def_id) {
1092                    DefKind::Fn => {
1093                        tcx.ensure_ok().codegen_fn_attrs(def_id);
1094                        tcx.ensure_ok().fn_sig(def_id);
1095                        let item = tcx.hir_foreign_item(item);
1096                        let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!() };
1097                        check_c_variadic_abi(tcx, sig.decl, abi, item.span);
1098                    }
1099                    DefKind::Static { .. } => {
1100                        tcx.ensure_ok().codegen_fn_attrs(def_id);
1101                    }
1102                    _ => (),
1103                }
1104            }
1105            // Doesn't have any hir based checks
1106            return res;
1107        }
1108        DefKind::Closure => {
1109            // This is guaranteed to be called by metadata encoding,
1110            // we still call it in wfcheck eagerly to ensure errors in codegen
1111            // attrs prevent lints from spamming the output.
1112            tcx.ensure_ok().codegen_fn_attrs(def_id);
1113            // We do not call `type_of` for closures here as that
1114            // depends on typecheck and would therefore hide
1115            // any further errors in case one typeck fails.
1116
1117            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1118            // checks. Returning early here does not miss any checks and
1119            // avoids this query from having a direct dependency edge on the HIR
1120            return res;
1121        }
1122        DefKind::AssocFn => {
1123            tcx.ensure_ok().codegen_fn_attrs(def_id);
1124            tcx.ensure_ok().type_of(def_id);
1125            tcx.ensure_ok().fn_sig(def_id);
1126            tcx.ensure_ok().clauses_of(def_id);
1127            res = res.and(check_associated_item(tcx, def_id));
1128            let assoc_item = tcx.associated_item(def_id);
1129            match assoc_item.container {
1130                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1131                ty::AssocContainer::Trait => {
1132                    res = res.and(check_trait_item(tcx, def_id));
1133                }
1134            }
1135
1136            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1137            // checks. Returning early here does not miss any checks and
1138            // avoids this query from having a direct dependency edge on the HIR
1139            return res;
1140        }
1141        DefKind::AssocConst => {
1142            tcx.ensure_ok().type_of(def_id);
1143            tcx.ensure_ok().clauses_of(def_id);
1144            res = res.and(check_associated_item(tcx, def_id));
1145            let assoc_item = tcx.associated_item(def_id);
1146            match assoc_item.container {
1147                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1148                ty::AssocContainer::Trait => {
1149                    res = res.and(check_trait_item(tcx, def_id));
1150                }
1151            }
1152
1153            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1154            // checks. Returning early here does not miss any checks and
1155            // avoids this query from having a direct dependency edge on the HIR
1156            return res;
1157        }
1158        DefKind::AssocTy => {
1159            tcx.ensure_ok().clauses_of(def_id);
1160            res = res.and(check_associated_item(tcx, def_id));
1161
1162            let assoc_item = tcx.associated_item(def_id);
1163            let has_type = match assoc_item.container {
1164                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1165                ty::AssocContainer::Trait => {
1166                    tcx.ensure_ok().explicit_item_bounds(def_id);
1167                    tcx.ensure_ok().explicit_item_self_bounds(def_id);
1168                    if tcx.is_conditionally_const(def_id) {
1169                        tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1170                        tcx.ensure_ok().const_conditions(def_id);
1171                    }
1172                    res = res.and(check_trait_item(tcx, def_id));
1173                    assoc_item.defaultness(tcx).has_value()
1174                }
1175            };
1176            if has_type {
1177                tcx.ensure_ok().type_of(def_id);
1178            }
1179
1180            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1181            // checks. Returning early here does not miss any checks and
1182            // avoids this query from having a direct dependency edge on the HIR
1183            return res;
1184        }
1185        DefKind::TestBinderConstraints => {
1186            tcx.ensure_ok().generics_of(def_id);
1187            tcx.ensure_ok().clauses_of(def_id);
1188            let (_, body) =
1189                tcx.hir_node_by_def_id(def_id).expect_item().expect_test_binder_constraints();
1190            let icx = ItemCtxt::new(tcx, def_id);
1191            let lowered = icx.lower_test_binder_body(body);
1192            res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1193                wfcx.check_test_binder_body(lowered);
1194                Ok(())
1195            }));
1196            return res;
1197        }
1198
1199        // These have no wf checks
1200        DefKind::AnonConst
1201        | DefKind::ExternCrate
1202        | DefKind::Macro(..)
1203        | DefKind::Use
1204        | DefKind::GlobalAsm
1205        | DefKind::Mod => return res,
1206
1207        DefKind::ForeignTy => {}
1208
1209        DefKind::Variant
1210        | DefKind::TyParam
1211        | DefKind::ConstParam
1212        | DefKind::Ctor(..)
1213        | DefKind::Field
1214        | DefKind::LifetimeParam
1215        | DefKind::SyntheticCoroutineBody => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{1:?}: {0:?}", tcx.def_kind(def_id), def_id)));
}unreachable!("{def_id:?}: {:?}", tcx.def_kind(def_id)),
1216    }
1217    let node = tcx.hir_node_by_def_id(def_id);
1218    res.and(match node {
1219        hir::Node::Crate(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("check_well_formed cannot be applied to the crate root"),
    Location::caller())bug!("check_well_formed cannot be applied to the crate root"),
1220        hir::Node::Item(item) => wfcheck::check_item(tcx, item),
1221        hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),
1222        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{0:?}", node)));
}unreachable!("{node:?}"),
1223    })
1224}
1225
1226fn check_specialization_validity<'tcx>(
1227    tcx: TyCtxt<'tcx>,
1228    trait_def: &ty::TraitDef,
1229    trait_item: ty::AssocItem,
1230    impl_id: DefId,
1231    impl_item: DefId,
1232) {
1233    let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
1234    let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
1235        if parent.is_from_trait() {
1236            None
1237        } else {
1238            Some((parent, parent.item(tcx, trait_item.def_id)))
1239        }
1240    });
1241
1242    let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1243        match parent_item {
1244            // Parent impl exists, and contains the parent item we're trying to specialize, but
1245            // doesn't mark it `default`.
1246            Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
1247                Some(Err(parent_impl.def_id()))
1248            }
1249
1250            // Parent impl contains item and makes it specializable.
1251            Some(_) => Some(Ok(())),
1252
1253            // Parent impl doesn't mention the item. This means it's inherited from the
1254            // grandparent. In that case, if parent is a `default impl`, inherited items use the
1255            // "defaultness" from the grandparent, else they are final.
1256            None => {
1257                if tcx.defaultness(parent_impl.def_id()).is_default() {
1258                    None
1259                } else {
1260                    Some(Err(parent_impl.def_id()))
1261                }
1262            }
1263        }
1264    });
1265
1266    // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
1267    // item. This is allowed, the item isn't actually getting specialized here.
1268    let result = opt_result.unwrap_or(Ok(()));
1269
1270    if let Err(parent_impl) = result {
1271        if !tcx.is_impl_trait_in_trait(impl_item) {
1272            let span = tcx.def_span(impl_item);
1273            let ident = tcx.item_ident(impl_item);
1274
1275            let err = match tcx.span_of_impl(parent_impl) {
1276                Ok(sp) => diagnostics::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp },
1277                Err(cname) => diagnostics::ImplNotMarkedDefault::Err { span, ident, cname },
1278            };
1279
1280            tcx.dcx().emit_err(err);
1281        } else {
1282            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"));
1283        }
1284    }
1285}
1286
1287fn check_overriding_final_trait_item<'tcx>(
1288    tcx: TyCtxt<'tcx>,
1289    trait_item: ty::AssocItem,
1290    impl_item: ty::AssocItem,
1291) {
1292    if trait_item.is_fn() && trait_item.defaultness(tcx).is_final() {
1293        tcx.dcx().emit_err(diagnostics::OverridingFinalTraitFunction {
1294            impl_span: tcx.def_span(impl_item.def_id),
1295            trait_span: tcx.def_span(trait_item.def_id),
1296            ident: tcx.item_ident(impl_item.def_id),
1297        });
1298    }
1299}
1300
1301fn check_impl_items_against_trait<'tcx>(
1302    tcx: TyCtxt<'tcx>,
1303    impl_id: LocalDefId,
1304    impl_trait_header: ty::ImplTraitHeader<'tcx>,
1305) {
1306    let trait_ref = impl_trait_header.trait_ref.instantiate_identity().skip_norm_wip();
1307    // If the trait reference itself is erroneous (so the compilation is going
1308    // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1309    // isn't populated for such impls.
1310    if trait_ref.references_error() {
1311        return;
1312    }
1313
1314    let impl_item_refs = tcx.associated_item_def_ids(impl_id);
1315
1316    // Negative impls are not expected to have any items
1317    match impl_trait_header.polarity {
1318        ty::ImplPolarity::Positive => {}
1319        ty::ImplPolarity::Negative => {
1320            if let [first_item_ref, ..] = *impl_item_refs {
1321                let first_item_span = tcx.def_span(first_item_ref);
1322                {
    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!(
1323                    tcx.dcx(),
1324                    first_item_span,
1325                    E0749,
1326                    "negative impls cannot have any items"
1327                )
1328                .emit();
1329            }
1330            return;
1331        }
1332    }
1333
1334    let trait_def = tcx.trait_def(trait_ref.def_id);
1335
1336    let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
1337
1338    for &impl_item in impl_item_refs {
1339        let ty_impl_item = tcx.associated_item(impl_item);
1340        let ty_trait_item = match ty_impl_item.expect_trait_impl() {
1341            Ok(trait_item_id) => tcx.associated_item(trait_item_id),
1342            Err(ErrorGuaranteed { .. }) => continue,
1343        };
1344
1345        let res = tcx.ensure_result().compare_impl_item(impl_item.expect_local());
1346        if res.is_ok() {
1347            match ty_impl_item.kind {
1348                ty::AssocKind::Fn { .. } => {
1349                    compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1350                        tcx,
1351                        ty_impl_item,
1352                        ty_trait_item,
1353                        tcx.impl_trait_ref(ty_impl_item.container_id(tcx))
1354                            .instantiate_identity()
1355                            .skip_norm_wip(),
1356                    );
1357                }
1358                ty::AssocKind::Const { .. } => {}
1359                ty::AssocKind::Type { .. } => {}
1360            }
1361        }
1362
1363        if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1364            tcx.emit_node_span_lint(
1365                DEAD_CODE,
1366                tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1367                tcx.def_span(ty_impl_item.def_id),
1368                diagnostics::UselessImplItem,
1369            )
1370        }
1371
1372        check_specialization_validity(
1373            tcx,
1374            trait_def,
1375            ty_trait_item,
1376            impl_id.to_def_id(),
1377            impl_item,
1378        );
1379
1380        check_overriding_final_trait_item(tcx, ty_trait_item, ty_impl_item);
1381    }
1382
1383    if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1384        // Check for missing items from trait
1385        let mut missing_items = Vec::new();
1386
1387        let mut must_implement_one_of: Option<&[Ident]> =
1388            trait_def.must_implement_one_of.as_deref();
1389
1390        for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1391            let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1392
1393            let is_implemented = leaf_def
1394                .as_ref()
1395                .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1396
1397            if !is_implemented
1398                && tcx.defaultness(impl_id).is_final()
1399                // unsized types don't need to implement methods that have `Self: Sized` bounds.
1400                && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1401            {
1402                missing_items.push(tcx.associated_item(trait_item_id));
1403            }
1404
1405            // true if this item is specifically implemented in this impl
1406            let is_implemented_here =
1407                leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1408
1409            if !is_implemented_here {
1410                let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1411                match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1412                    // When the feature `pin_ergonomics` is disabled, we report `Drop::drop` is missing,
1413                    // instead of `Drop::drop` is unstable that might be confusing.
1414                    EvalResult::Deny { .. }
1415                        if !tcx.features().pin_ergonomics()
1416                            && tcx.is_lang_item(trait_ref.def_id, LangItem::Drop)
1417                            && tcx.item_name(trait_item_id) == sym::drop =>
1418                    {
1419                        missing_items.push(tcx.associated_item(trait_item_id));
1420                    }
1421                    EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1422                        tcx,
1423                        full_impl_span,
1424                        trait_item_id,
1425                        feature,
1426                        reason,
1427                        issue,
1428                    ),
1429
1430                    // Unmarked default bodies are considered stable (at least for now).
1431                    EvalResult::Allow | EvalResult::Unmarked => {}
1432                }
1433            }
1434
1435            if let Some(required_items) = &must_implement_one_of {
1436                if is_implemented_here {
1437                    let trait_item = tcx.associated_item(trait_item_id);
1438                    if required_items.contains(&trait_item.ident(tcx)) {
1439                        must_implement_one_of = None;
1440                    }
1441                }
1442            }
1443
1444            if let Some(leaf_def) = &leaf_def
1445                && !leaf_def.is_final()
1446                && let def_id = leaf_def.item.def_id
1447                && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1448            {
1449                let def_kind = tcx.def_kind(def_id);
1450                let descr = tcx.def_kind_descr(def_kind, def_id);
1451                let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1452                    (
1453                        ::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"),
1454                        "async functions in traits",
1455                    )
1456                } else {
1457                    (
1458                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} with return-position `impl Trait` in trait cannot be specialized",
                descr))
    })format!(
1459                            "{descr} with return-position `impl Trait` in trait cannot be specialized"
1460                        ),
1461                        "return position `impl Trait` in traits",
1462                    )
1463                };
1464                tcx.dcx()
1465                    .struct_span_err(tcx.def_span(def_id), msg)
1466                    .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!(
1467                        "specialization behaves in inconsistent and surprising ways with \
1468                        {feature}, and for now is disallowed"
1469                    ))
1470                    .emit();
1471            }
1472        }
1473
1474        if !missing_items.is_empty() {
1475            missing_items_err(tcx, impl_id, &missing_items);
1476        }
1477
1478        if let Some(missing_items) = must_implement_one_of {
1479            let attr_span = {
    {
        'done:
            {
            for i in
                ::rustc_attr_ir::HasAttrs::get_attrs(trait_ref.def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(RustcMustImplementOneOf {
                        attr_span, .. }) => {
                        break 'done Some(*attr_span);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, trait_ref.def_id, RustcMustImplementOneOf {attr_span, ..} => *attr_span);
1480            let missing_items = missing_items.into_iter().map(|i| i.name);
1481            missing_items_must_implement_one_of_err(tcx, impl_id, missing_items, attr_span);
1482        }
1483    }
1484}
1485
1486fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1487    let t = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1488    if let ty::Adt(def, args) = t.kind()
1489        && def.is_struct()
1490    {
1491        let fields = &def.non_enum_variant().fields;
1492        if fields.is_empty() {
1493            {
    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();
1494            return;
1495        }
1496
1497        let array_field = &fields[FieldIdx::ZERO];
1498        let array_ty = array_field.ty(tcx, args).skip_norm_wip();
1499        let ty::Array(element_ty, len_const) = array_ty.kind() else {
1500            {
    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!(
1501                tcx.dcx(),
1502                sp,
1503                E0076,
1504                "SIMD vector's only field must be an array"
1505            )
1506            .with_span_label(tcx.def_span(array_field.did), "not an array")
1507            .emit();
1508            return;
1509        };
1510
1511        if let Some(second_field) = fields.get(FieldIdx::ONE) {
1512            {
    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")
1513                .with_span_label(tcx.def_span(second_field.did), "excess field")
1514                .emit();
1515            return;
1516        }
1517
1518        // FIXME(repr_simd): This check is nice, but perhaps unnecessary due to the fact
1519        // we do not expect users to implement their own `repr(simd)` types. If they could,
1520        // this check is easily side-steppable by hiding the const behind normalization.
1521        // The consequence is that the error is, in general, only observable post-mono.
1522        if let Some(len) = len_const.try_to_target_usize(tcx) {
1523            if len == 0 {
1524                {
    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();
1525                return;
1526            } else if len > MAX_SIMD_LANES.into() {
1527                {
    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!(
1528                    tcx.dcx(),
1529                    sp,
1530                    E0075,
1531                    "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1532                )
1533                .emit();
1534                return;
1535            }
1536        }
1537
1538        // Check that we use types valid for use in the lanes of a SIMD "vector register"
1539        // These are scalar types which directly match a "machine" type
1540        // Yes: Integers, floats, "thin" pointers
1541        // No: char, "wide" pointers, compound types
1542        match element_ty.kind() {
1543            ty::Param(_) => (), // pass struct<T>([T; 4]) through, let monomorphization catch errors
1544            ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), // struct([u8; 4]) is ok
1545            _ => {
1546                {
    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!(
1547                    tcx.dcx(),
1548                    sp,
1549                    E0077,
1550                    "SIMD vector element type should be a \
1551                        primitive scalar (integer/float/pointer) type"
1552                )
1553                .emit();
1554                return;
1555            }
1556        }
1557    }
1558}
1559
1560{}
#[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("/rustc-dev/7bbda45cb1ec0a378d91959646a8fa904be3192a/compiler/rustc_hir_analysis/src/check/check.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1560u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("scalable")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("scalable");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalable)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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