rustc_hir_analysis/check/
check.rs

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