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