rustc_hir_analysis/check/
check.rs

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