rustc_hir_typeck/
coercion.rs

1//! # Type Coercion
2//!
3//! Under certain circumstances we will coerce from one type to another,
4//! for example by auto-borrowing. This occurs in situations where the
5//! compiler has a firm 'expected type' that was supplied from the user,
6//! and where the actual type is similar to that expected type in purpose
7//! but not in representation (so actual subtyping is inappropriate).
8//!
9//! ## Reborrowing
10//!
11//! Note that if we are expecting a reference, we will *reborrow*
12//! even if the argument provided was already a reference. This is
13//! useful for freezing mut things (that is, when the expected type is &T
14//! but you have &mut T) and also for avoiding the linearity
15//! of mut things (when the expected is &mut T and you have &mut T). See
16//! the various `tests/ui/coerce/*.rs` tests for
17//! examples of where this is useful.
18//!
19//! ## Subtle note
20//!
21//! When inferring the generic arguments of functions, the argument
22//! order is relevant, which can lead to the following edge case:
23//!
24//! ```ignore (illustrative)
25//! fn foo<T>(a: T, b: T) {
26//!     // ...
27//! }
28//!
29//! foo(&7i32, &mut 7i32);
30//! // This compiles, as we first infer `T` to be `&i32`,
31//! // and then coerce `&mut 7i32` to `&7i32`.
32//!
33//! foo(&mut 7i32, &7i32);
34//! // This does not compile, as we first infer `T` to be `&mut i32`
35//! // and are then unable to coerce `&7i32` to `&mut i32`.
36//! ```
37
38use std::ops::Deref;
39
40use rustc_attr_parsing::InlineAttr;
41use rustc_errors::codes::*;
42use rustc_errors::{Applicability, Diag, struct_span_code_err};
43use rustc_hir as hir;
44use rustc_hir::def_id::{DefId, LocalDefId};
45use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
46use rustc_infer::infer::relate::RelateResult;
47use rustc_infer::infer::{Coercion, DefineOpaqueTypes, InferOk, InferResult};
48use rustc_infer::traits::{
49    IfExpressionCause, MatchExpressionArmCause, Obligation, PredicateObligation,
50    PredicateObligations,
51};
52use rustc_middle::span_bug;
53use rustc_middle::ty::adjustment::{
54    Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCoercion,
55};
56use rustc_middle::ty::error::TypeError;
57use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt};
58use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Span};
59use rustc_trait_selection::infer::InferCtxtExt as _;
60use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
61use rustc_trait_selection::traits::{
62    self, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
63};
64use smallvec::{SmallVec, smallvec};
65use tracing::{debug, instrument};
66
67use crate::FnCtxt;
68use crate::errors::SuggestBoxingForReturnImplTrait;
69
70struct Coerce<'a, 'tcx> {
71    fcx: &'a FnCtxt<'a, 'tcx>,
72    cause: ObligationCause<'tcx>,
73    use_lub: bool,
74    /// Determines whether or not allow_two_phase_borrow is set on any
75    /// autoref adjustments we create while coercing. We don't want to
76    /// allow deref coercions to create two-phase borrows, at least initially,
77    /// but we do need two-phase borrows for function argument reborrows.
78    /// See #47489 and #48598
79    /// See docs on the "AllowTwoPhase" type for a more detailed discussion
80    allow_two_phase: AllowTwoPhase,
81    /// Whether we allow `NeverToAny` coercions. This is unsound if we're
82    /// coercing a place expression without it counting as a read in the MIR.
83    /// This is a side-effect of HIR not really having a great distinction
84    /// between places and values.
85    coerce_never: bool,
86}
87
88impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
89    type Target = FnCtxt<'a, 'tcx>;
90    fn deref(&self) -> &Self::Target {
91        self.fcx
92    }
93}
94
95type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
96
97/// Coercing a mutable reference to an immutable works, while
98/// coercing `&T` to `&mut T` should be forbidden.
99fn coerce_mutbls<'tcx>(
100    from_mutbl: hir::Mutability,
101    to_mutbl: hir::Mutability,
102) -> RelateResult<'tcx, ()> {
103    if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
104}
105
106/// This always returns `Ok(...)`.
107fn success<'tcx>(
108    adj: Vec<Adjustment<'tcx>>,
109    target: Ty<'tcx>,
110    obligations: PredicateObligations<'tcx>,
111) -> CoerceResult<'tcx> {
112    Ok(InferOk { value: (adj, target), obligations })
113}
114
115impl<'f, 'tcx> Coerce<'f, 'tcx> {
116    fn new(
117        fcx: &'f FnCtxt<'f, 'tcx>,
118        cause: ObligationCause<'tcx>,
119        allow_two_phase: AllowTwoPhase,
120        coerce_never: bool,
121    ) -> Self {
122        Coerce { fcx, cause, allow_two_phase, use_lub: false, coerce_never }
123    }
124
125    fn unify_raw(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
126        debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
127        self.commit_if_ok(|_| {
128            let at = self.at(&self.cause, self.fcx.param_env);
129
130            let res = if self.use_lub {
131                at.lub(b, a)
132            } else {
133                at.sup(DefineOpaqueTypes::Yes, b, a)
134                    .map(|InferOk { value: (), obligations }| InferOk { value: b, obligations })
135            };
136
137            // In the new solver, lazy norm may allow us to shallowly equate
138            // more types, but we emit possibly impossible-to-satisfy obligations.
139            // Filter these cases out to make sure our coercion is more accurate.
140            match res {
141                Ok(InferOk { value, obligations }) if self.next_trait_solver() => {
142                    let ocx = ObligationCtxt::new(self);
143                    ocx.register_obligations(obligations);
144                    if ocx.select_where_possible().is_empty() {
145                        Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
146                    } else {
147                        Err(TypeError::Mismatch)
148                    }
149                }
150                res => res,
151            }
152        })
153    }
154
155    /// Unify two types (using sub or lub).
156    fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
157        self.unify_raw(a, b)
158            .and_then(|InferOk { value: ty, obligations }| success(vec![], ty, obligations))
159    }
160
161    /// Unify two types (using sub or lub) and produce a specific coercion.
162    fn unify_and(
163        &self,
164        a: Ty<'tcx>,
165        b: Ty<'tcx>,
166        adjustments: impl IntoIterator<Item = Adjustment<'tcx>>,
167        final_adjustment: Adjust,
168    ) -> CoerceResult<'tcx> {
169        self.unify_raw(a, b).and_then(|InferOk { value: ty, obligations }| {
170            success(
171                adjustments
172                    .into_iter()
173                    .chain(std::iter::once(Adjustment { target: ty, kind: final_adjustment }))
174                    .collect(),
175                ty,
176                obligations,
177            )
178        })
179    }
180
181    #[instrument(skip(self))]
182    fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
183        // First, remove any resolved type variables (at the top level, at least):
184        let a = self.shallow_resolve(a);
185        let b = self.shallow_resolve(b);
186        debug!("Coerce.tys({:?} => {:?})", a, b);
187
188        // Coercing from `!` to any type is allowed:
189        if a.is_never() {
190            if self.coerce_never {
191                return success(
192                    vec![Adjustment { kind: Adjust::NeverToAny, target: b }],
193                    b,
194                    PredicateObligations::new(),
195                );
196            } else {
197                // Otherwise the only coercion we can do is unification.
198                return self.unify(a, b);
199            }
200        }
201
202        // Coercing *from* an unresolved inference variable means that
203        // we have no information about the source type. This will always
204        // ultimately fall back to some form of subtyping.
205        if a.is_ty_var() {
206            return self.coerce_from_inference_variable(a, b);
207        }
208
209        // Consider coercing the subtype to a DST
210        //
211        // NOTE: this is wrapped in a `commit_if_ok` because it creates
212        // a "spurious" type variable, and we don't want to have that
213        // type variable in memory if the coercion fails.
214        let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
215        match unsize {
216            Ok(_) => {
217                debug!("coerce: unsize successful");
218                return unsize;
219            }
220            Err(error) => {
221                debug!(?error, "coerce: unsize failed");
222            }
223        }
224
225        // Examine the supertype and consider type-specific coercions, such
226        // as auto-borrowing, coercing pointer mutability, a `dyn*` coercion,
227        // or pin-ergonomics.
228        match *b.kind() {
229            ty::RawPtr(_, b_mutbl) => {
230                return self.coerce_raw_ptr(a, b, b_mutbl);
231            }
232            ty::Ref(r_b, _, mutbl_b) => {
233                return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
234            }
235            ty::Dynamic(predicates, region, ty::DynStar) if self.tcx.features().dyn_star() => {
236                return self.coerce_dyn_star(a, b, predicates, region);
237            }
238            ty::Adt(pin, _)
239                if self.tcx.features().pin_ergonomics()
240                    && self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) =>
241            {
242                let pin_coerce = self.commit_if_ok(|_| self.coerce_pin_ref(a, b));
243                if pin_coerce.is_ok() {
244                    return pin_coerce;
245                }
246            }
247            _ => {}
248        }
249
250        match *a.kind() {
251            ty::FnDef(..) => {
252                // Function items are coercible to any closure
253                // type; function pointers are not (that would
254                // require double indirection).
255                // Additionally, we permit coercion of function
256                // items to drop the unsafe qualifier.
257                self.coerce_from_fn_item(a, b)
258            }
259            ty::FnPtr(a_sig_tys, a_hdr) => {
260                // We permit coercion of fn pointers to drop the
261                // unsafe qualifier.
262                self.coerce_from_fn_pointer(a_sig_tys.with(a_hdr), b)
263            }
264            ty::Closure(closure_def_id_a, args_a) => {
265                // Non-capturing closures are coercible to
266                // function pointers or unsafe function pointers.
267                // It cannot convert closures that require unsafe.
268                self.coerce_closure_to_fn(a, closure_def_id_a, args_a, b)
269            }
270            _ => {
271                // Otherwise, just use unification rules.
272                self.unify(a, b)
273            }
274        }
275    }
276
277    /// Coercing *from* an inference variable. In this case, we have no information
278    /// about the source type, so we can't really do a true coercion and we always
279    /// fall back to subtyping (`unify_and`).
280    fn coerce_from_inference_variable(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
281        debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
282        assert!(a.is_ty_var() && self.shallow_resolve(a) == a);
283        assert!(self.shallow_resolve(b) == b);
284
285        if b.is_ty_var() {
286            // Two unresolved type variables: create a `Coerce` predicate.
287            let target_ty = if self.use_lub { self.next_ty_var(self.cause.span) } else { b };
288
289            let mut obligations = PredicateObligations::with_capacity(2);
290            for &source_ty in &[a, b] {
291                if source_ty != target_ty {
292                    obligations.push(Obligation::new(
293                        self.tcx(),
294                        self.cause.clone(),
295                        self.param_env,
296                        ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate {
297                            a: source_ty,
298                            b: target_ty,
299                        })),
300                    ));
301                }
302            }
303
304            debug!(
305                "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
306                target_ty, obligations
307            );
308            success(vec![], target_ty, obligations)
309        } else {
310            // One unresolved type variable: just apply subtyping, we may be able
311            // to do something useful.
312            self.unify(a, b)
313        }
314    }
315
316    /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
317    /// To match `A` with `B`, autoderef will be performed,
318    /// calling `deref`/`deref_mut` where necessary.
319    fn coerce_borrowed_pointer(
320        &self,
321        a: Ty<'tcx>,
322        b: Ty<'tcx>,
323        r_b: ty::Region<'tcx>,
324        mutbl_b: hir::Mutability,
325    ) -> CoerceResult<'tcx> {
326        debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
327
328        // If we have a parameter of type `&M T_a` and the value
329        // provided is `expr`, we will be adding an implicit borrow,
330        // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
331        // to type check, we will construct the type that `&M*expr` would
332        // yield.
333
334        let (r_a, mt_a) = match *a.kind() {
335            ty::Ref(r_a, ty, mutbl) => {
336                let mt_a = ty::TypeAndMut { ty, mutbl };
337                coerce_mutbls(mt_a.mutbl, mutbl_b)?;
338                (r_a, mt_a)
339            }
340            _ => return self.unify(a, b),
341        };
342
343        let span = self.cause.span;
344
345        let mut first_error = None;
346        let mut r_borrow_var = None;
347        let mut autoderef = self.autoderef(span, a);
348        let mut found = None;
349
350        for (referent_ty, autoderefs) in autoderef.by_ref() {
351            if autoderefs == 0 {
352                // Don't let this pass, otherwise it would cause
353                // &T to autoref to &&T.
354                continue;
355            }
356
357            // At this point, we have deref'd `a` to `referent_ty`. So
358            // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
359            // In the autoderef loop for `&'a mut Vec<T>`, we would get
360            // three callbacks:
361            //
362            // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
363            // - `Vec<T>` -- 1 deref
364            // - `[T]` -- 2 deref
365            //
366            // At each point after the first callback, we want to
367            // check to see whether this would match out target type
368            // (`&'b mut [T]`) if we autoref'd it. We can't just
369            // compare the referent types, though, because we still
370            // have to consider the mutability. E.g., in the case
371            // we've been considering, we have an `&mut` reference, so
372            // the `T` in `[T]` needs to be unified with equality.
373            //
374            // Therefore, we construct reference types reflecting what
375            // the types will be after we do the final auto-ref and
376            // compare those. Note that this means we use the target
377            // mutability [1], since it may be that we are coercing
378            // from `&mut T` to `&U`.
379            //
380            // One fine point concerns the region that we use. We
381            // choose the region such that the region of the final
382            // type that results from `unify` will be the region we
383            // want for the autoref:
384            //
385            // - if in sub mode, that means we want to use `'b` (the
386            //   region from the target reference) for both
387            //   pointers [2]. This is because sub mode (somewhat
388            //   arbitrarily) returns the subtype region. In the case
389            //   where we are coercing to a target type, we know we
390            //   want to use that target type region (`'b`) because --
391            //   for the program to type-check -- it must be the
392            //   smaller of the two.
393            //   - One fine point. It may be surprising that we can
394            //     use `'b` without relating `'a` and `'b`. The reason
395            //     that this is ok is that what we produce is
396            //     effectively a `&'b *x` expression (if you could
397            //     annotate the region of a borrow), and regionck has
398            //     code that adds edges from the region of a borrow
399            //     (`'b`, here) into the regions in the borrowed
400            //     expression (`*x`, here). (Search for "link".)
401            // - if in lub mode, things can get fairly complicated. The
402            //   easiest thing is just to make a fresh
403            //   region variable [4], which effectively means we defer
404            //   the decision to region inference (and regionck, which will add
405            //   some more edges to this variable). However, this can wind up
406            //   creating a crippling number of variables in some cases --
407            //   e.g., #32278 -- so we optimize one particular case [3].
408            //   Let me try to explain with some examples:
409            //   - The "running example" above represents the simple case,
410            //     where we have one `&` reference at the outer level and
411            //     ownership all the rest of the way down. In this case,
412            //     we want `LUB('a, 'b)` as the resulting region.
413            //   - However, if there are nested borrows, that region is
414            //     too strong. Consider a coercion from `&'a &'x Rc<T>` to
415            //     `&'b T`. In this case, `'a` is actually irrelevant.
416            //     The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
417            //     we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
418            //     (The errors actually show up in borrowck, typically, because
419            //     this extra edge causes the region `'a` to be inferred to something
420            //     too big, which then results in borrowck errors.)
421            //   - We could track the innermost shared reference, but there is already
422            //     code in regionck that has the job of creating links between
423            //     the region of a borrow and the regions in the thing being
424            //     borrowed (here, `'a` and `'x`), and it knows how to handle
425            //     all the various cases. So instead we just make a region variable
426            //     and let regionck figure it out.
427            let r = if !self.use_lub {
428                r_b // [2] above
429            } else if autoderefs == 1 {
430                r_a // [3] above
431            } else {
432                if r_borrow_var.is_none() {
433                    // create var lazily, at most once
434                    let coercion = Coercion(span);
435                    let r = self.next_region_var(coercion);
436                    r_borrow_var = Some(r); // [4] above
437                }
438                r_borrow_var.unwrap()
439            };
440            let derefd_ty_a = Ty::new_ref(
441                self.tcx,
442                r,
443                referent_ty,
444                mutbl_b, // [1] above
445            );
446            match self.unify_raw(derefd_ty_a, b) {
447                Ok(ok) => {
448                    found = Some(ok);
449                    break;
450                }
451                Err(err) => {
452                    if first_error.is_none() {
453                        first_error = Some(err);
454                    }
455                }
456            }
457        }
458
459        // Extract type or return an error. We return the first error
460        // we got, which should be from relating the "base" type
461        // (e.g., in example above, the failure from relating `Vec<T>`
462        // to the target type), since that should be the least
463        // confusing.
464        let Some(InferOk { value: ty, mut obligations }) = found else {
465            if let Some(first_error) = first_error {
466                debug!("coerce_borrowed_pointer: failed with err = {:?}", first_error);
467                return Err(first_error);
468            } else {
469                // This may happen in the new trait solver since autoderef requires
470                // the pointee to be structurally normalizable, or else it'll just bail.
471                // So when we have a type like `&<not well formed>`, then we get no
472                // autoderef steps (even though there should be at least one). That means
473                // we get no type mismatches, since the loop above just exits early.
474                return Err(TypeError::Mismatch);
475            }
476        };
477
478        if ty == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
479            // As a special case, if we would produce `&'a *x`, that's
480            // a total no-op. We end up with the type `&'a T` just as
481            // we started with. In that case, just skip it
482            // altogether. This is just an optimization.
483            //
484            // Note that for `&mut`, we DO want to reborrow --
485            // otherwise, this would be a move, which might be an
486            // error. For example `foo(self.x)` where `self` and
487            // `self.x` both have `&mut `type would be a move of
488            // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
489            // which is a borrow.
490            assert!(mutbl_b.is_not()); // can only coerce &T -> &U
491            return success(vec![], ty, obligations);
492        }
493
494        let InferOk { value: mut adjustments, obligations: o } =
495            self.adjust_steps_as_infer_ok(&autoderef);
496        obligations.extend(o);
497        obligations.extend(autoderef.into_obligations());
498
499        // Now apply the autoref. We have to extract the region out of
500        // the final ref type we got.
501        let ty::Ref(..) = ty.kind() else {
502            span_bug!(span, "expected a ref type, got {:?}", ty);
503        };
504        let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
505        adjustments.push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target: ty });
506
507        debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
508
509        success(adjustments, ty, obligations)
510    }
511
512    /// Performs [unsized coercion] by emulating a fulfillment loop on a
513    /// `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals
514    /// are successfully selected.
515    ///
516    /// [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions)
517    #[instrument(skip(self), level = "debug")]
518    fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> {
519        source = self.shallow_resolve(source);
520        target = self.shallow_resolve(target);
521        debug!(?source, ?target);
522
523        // We don't apply any coercions incase either the source or target
524        // aren't sufficiently well known but tend to instead just equate
525        // them both.
526        if source.is_ty_var() {
527            debug!("coerce_unsized: source is a TyVar, bailing out");
528            return Err(TypeError::Mismatch);
529        }
530        if target.is_ty_var() {
531            debug!("coerce_unsized: target is a TyVar, bailing out");
532            return Err(TypeError::Mismatch);
533        }
534
535        let traits =
536            (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
537        let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
538            debug!("missing Unsize or CoerceUnsized traits");
539            return Err(TypeError::Mismatch);
540        };
541
542        // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
543        // a DST unless we have to. This currently comes out in the wash since
544        // we can't unify [T] with U. But to properly support DST, we need to allow
545        // that, at which point we will need extra checks on the target here.
546
547        // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
548        let reborrow = match (source.kind(), target.kind()) {
549            (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
550                coerce_mutbls(mutbl_a, mutbl_b)?;
551
552                let coercion = Coercion(self.cause.span);
553                let r_borrow = self.next_region_var(coercion);
554
555                // We don't allow two-phase borrows here, at least for initial
556                // implementation. If it happens that this coercion is a function argument,
557                // the reborrow in coerce_borrowed_ptr will pick it up.
558                let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
559
560                Some((
561                    Adjustment { kind: Adjust::Deref(None), target: ty_a },
562                    Adjustment {
563                        kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
564                        target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
565                    },
566                ))
567            }
568            (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
569                coerce_mutbls(mt_a, mt_b)?;
570
571                Some((
572                    Adjustment { kind: Adjust::Deref(None), target: ty_a },
573                    Adjustment {
574                        kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
575                        target: Ty::new_ptr(self.tcx, ty_a, mt_b),
576                    },
577                ))
578            }
579            _ => None,
580        };
581        let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
582
583        // Setup either a subtyping or a LUB relationship between
584        // the `CoerceUnsized` target type and the expected type.
585        // We only have the latter, so we use an inference variable
586        // for the former and let type inference do the rest.
587        let coerce_target = self.next_ty_var(self.cause.span);
588
589        let mut coercion = self.unify_and(
590            coerce_target,
591            target,
592            reborrow.into_iter().flat_map(|(deref, autoref)| [deref, autoref]),
593            Adjust::Pointer(PointerCoercion::Unsize),
594        )?;
595
596        let mut selcx = traits::SelectionContext::new(self);
597
598        // Create an obligation for `Source: CoerceUnsized<Target>`.
599        let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
600
601        // Use a FIFO queue for this custom fulfillment procedure.
602        //
603        // A Vec (or SmallVec) is not a natural choice for a queue. However,
604        // this code path is hot, and this queue usually has a max length of 1
605        // and almost never more than 3. By using a SmallVec we avoid an
606        // allocation, at the (very small) cost of (occasionally) having to
607        // shift subsequent elements down when removing the front element.
608        let mut queue: SmallVec<[PredicateObligation<'tcx>; 4]> = smallvec![Obligation::new(
609            self.tcx,
610            cause,
611            self.fcx.param_env,
612            ty::TraitRef::new(self.tcx, coerce_unsized_did, [coerce_source, coerce_target])
613        )];
614
615        // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
616        // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
617        // inference might unify those two inner type variables later.
618        let traits = [coerce_unsized_did, unsize_did];
619        while !queue.is_empty() {
620            let obligation = queue.remove(0);
621            let trait_pred = match obligation.predicate.kind().no_bound_vars() {
622                Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)))
623                    if traits.contains(&trait_pred.def_id()) =>
624                {
625                    self.resolve_vars_if_possible(trait_pred)
626                }
627                // Eagerly process alias-relate obligations in new trait solver,
628                // since these can be emitted in the process of solving trait goals,
629                // but we need to constrain vars before processing goals mentioning
630                // them.
631                Some(ty::PredicateKind::AliasRelate(..)) => {
632                    let ocx = ObligationCtxt::new(self);
633                    ocx.register_obligation(obligation);
634                    if !ocx.select_where_possible().is_empty() {
635                        return Err(TypeError::Mismatch);
636                    }
637                    coercion.obligations.extend(ocx.into_pending_obligations());
638                    continue;
639                }
640                _ => {
641                    coercion.obligations.push(obligation);
642                    continue;
643                }
644            };
645            debug!("coerce_unsized resolve step: {:?}", trait_pred);
646            match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
647                // Uncertain or unimplemented.
648                Ok(None) => {
649                    if trait_pred.def_id() == unsize_did {
650                        let self_ty = trait_pred.self_ty();
651                        let unsize_ty = trait_pred.trait_ref.args[1].expect_ty();
652                        debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
653                        match (self_ty.kind(), unsize_ty.kind()) {
654                            (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
655                                if self.type_var_is_sized(v) =>
656                            {
657                                debug!("coerce_unsized: have sized infer {:?}", v);
658                                coercion.obligations.push(obligation);
659                                // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
660                                // for unsizing.
661                            }
662                            _ => {
663                                // Some other case for `$0: Unsize<Something>`. Note that we
664                                // hit this case even if `Something` is a sized type, so just
665                                // don't do the coercion.
666                                debug!("coerce_unsized: ambiguous unsize");
667                                return Err(TypeError::Mismatch);
668                            }
669                        }
670                    } else {
671                        debug!("coerce_unsized: early return - ambiguous");
672                        return Err(TypeError::Mismatch);
673                    }
674                }
675                Err(traits::Unimplemented) => {
676                    debug!("coerce_unsized: early return - can't prove obligation");
677                    return Err(TypeError::Mismatch);
678                }
679
680                // Dyn-compatibility violations or miscellaneous.
681                Err(err) => {
682                    let guar = self.err_ctxt().report_selection_error(
683                        obligation.clone(),
684                        &obligation,
685                        &err,
686                    );
687                    self.fcx.set_tainted_by_errors(guar);
688                    // Treat this like an obligation and follow through
689                    // with the unsizing - the lack of a coercion should
690                    // be silent, as it causes a type mismatch later.
691                }
692
693                Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
694            }
695        }
696
697        Ok(coercion)
698    }
699
700    fn coerce_dyn_star(
701        &self,
702        a: Ty<'tcx>,
703        b: Ty<'tcx>,
704        predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
705        b_region: ty::Region<'tcx>,
706    ) -> CoerceResult<'tcx> {
707        if !self.tcx.features().dyn_star() {
708            return Err(TypeError::Mismatch);
709        }
710
711        // FIXME(dyn_star): We should probably allow things like casting from
712        // `dyn* Foo + Send` to `dyn* Foo`.
713        if let ty::Dynamic(a_data, _, ty::DynStar) = a.kind()
714            && let ty::Dynamic(b_data, _, ty::DynStar) = b.kind()
715            && a_data.principal_def_id() == b_data.principal_def_id()
716        {
717            return self.unify(a, b);
718        }
719
720        // Check the obligations of the cast -- for example, when casting
721        // `usize` to `dyn* Clone + 'static`:
722        let obligations = predicates
723            .iter()
724            .map(|predicate| {
725                // For each existential predicate (e.g., `?Self: Clone`) instantiate
726                // the type of the expression (e.g., `usize` in our example above)
727                // and then require that the resulting predicate (e.g., `usize: Clone`)
728                // holds (it does).
729                let predicate = predicate.with_self_ty(self.tcx, a);
730                Obligation::new(self.tcx, self.cause.clone(), self.param_env, predicate)
731            })
732            .chain([
733                // Enforce the region bound (e.g., `usize: 'static`, in our example).
734                Obligation::new(
735                    self.tcx,
736                    self.cause.clone(),
737                    self.param_env,
738                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
739                        ty::OutlivesPredicate(a, b_region),
740                    ))),
741                ),
742                // Enforce that the type is `usize`/pointer-sized.
743                Obligation::new(
744                    self.tcx,
745                    self.cause.clone(),
746                    self.param_env,
747                    ty::TraitRef::new(
748                        self.tcx,
749                        self.tcx
750                            .require_lang_item(hir::LangItem::PointerLike, Some(self.cause.span)),
751                        [a],
752                    ),
753                ),
754            ])
755            .collect();
756
757        Ok(InferOk {
758            value: (
759                vec![Adjustment { kind: Adjust::Pointer(PointerCoercion::DynStar), target: b }],
760                b,
761            ),
762            obligations,
763        })
764    }
765
766    /// Applies reborrowing for `Pin`
767    ///
768    /// We currently only support reborrowing `Pin<&mut T>` as `Pin<&mut T>`. This is accomplished
769    /// by inserting a call to `Pin::as_mut` during MIR building.
770    ///
771    /// In the future we might want to support other reborrowing coercions, such as:
772    /// - `Pin<&mut T>` as `Pin<&T>`
773    /// - `Pin<&T>` as `Pin<&T>`
774    /// - `Pin<Box<T>>` as `Pin<&T>`
775    /// - `Pin<Box<T>>` as `Pin<&mut T>`
776    #[instrument(skip(self), level = "trace")]
777    fn coerce_pin_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
778        // We need to make sure the two types are compatible for coercion.
779        // Then we will build a ReborrowPin adjustment and return that as an InferOk.
780
781        // Right now we can only reborrow if this is a `Pin<&mut T>`.
782        let extract_pin_mut = |ty: Ty<'tcx>| {
783            // Get the T out of Pin<T>
784            let (pin, ty) = match ty.kind() {
785                ty::Adt(pin, args) if self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) => {
786                    (*pin, args[0].expect_ty())
787                }
788                _ => {
789                    debug!("can't reborrow {:?} as pinned", ty);
790                    return Err(TypeError::Mismatch);
791                }
792            };
793            // Make sure the T is something we understand (just `&mut U` for now)
794            match ty.kind() {
795                ty::Ref(region, ty, mutbl) => Ok((pin, *region, *ty, *mutbl)),
796                _ => {
797                    debug!("can't reborrow pin of inner type {:?}", ty);
798                    Err(TypeError::Mismatch)
799                }
800            }
801        };
802
803        let (pin, a_region, a_ty, mut_a) = extract_pin_mut(a)?;
804        let (_, _, _b_ty, mut_b) = extract_pin_mut(b)?;
805
806        coerce_mutbls(mut_a, mut_b)?;
807
808        // update a with b's mutability since we'll be coercing mutability
809        let a = Ty::new_adt(
810            self.tcx,
811            pin,
812            self.tcx.mk_args(&[Ty::new_ref(self.tcx, a_region, a_ty, mut_b).into()]),
813        );
814
815        // To complete the reborrow, we need to make sure we can unify the inner types, and if so we
816        // add the adjustments.
817        self.unify_and(a, b, [], Adjust::ReborrowPin(mut_b))
818    }
819
820    fn coerce_from_safe_fn(
821        &self,
822        fn_ty_a: ty::PolyFnSig<'tcx>,
823        b: Ty<'tcx>,
824        adjustment: Option<Adjust>,
825    ) -> CoerceResult<'tcx> {
826        self.commit_if_ok(|snapshot| {
827            let outer_universe = self.infcx.universe();
828
829            let result = if let ty::FnPtr(_, hdr_b) = b.kind()
830                && fn_ty_a.safety().is_safe()
831                && hdr_b.safety.is_unsafe()
832            {
833                let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
834                self.unify_and(
835                    unsafe_a,
836                    b,
837                    adjustment
838                        .map(|kind| Adjustment { kind, target: Ty::new_fn_ptr(self.tcx, fn_ty_a) }),
839                    Adjust::Pointer(PointerCoercion::UnsafeFnPointer),
840                )
841            } else {
842                let a = Ty::new_fn_ptr(self.tcx, fn_ty_a);
843                match adjustment {
844                    Some(adjust) => self.unify_and(a, b, [], adjust),
845                    None => self.unify(a, b),
846                }
847            };
848
849            // FIXME(#73154): This is a hack. Currently LUB can generate
850            // unsolvable constraints. Additionally, it returns `a`
851            // unconditionally, even when the "LUB" is `b`. In the future, we
852            // want the coerced type to be the actual supertype of these two,
853            // but for now, we want to just error to ensure we don't lock
854            // ourselves into a specific behavior with NLL.
855            self.leak_check(outer_universe, Some(snapshot))?;
856
857            result
858        })
859    }
860
861    fn coerce_from_fn_pointer(
862        &self,
863        fn_ty_a: ty::PolyFnSig<'tcx>,
864        b: Ty<'tcx>,
865    ) -> CoerceResult<'tcx> {
866        //! Attempts to coerce from the type of a Rust function item
867        //! into a closure or a `proc`.
868        //!
869
870        let b = self.shallow_resolve(b);
871        debug!(?fn_ty_a, ?b, "coerce_from_fn_pointer");
872
873        self.coerce_from_safe_fn(fn_ty_a, b, None)
874    }
875
876    fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
877        //! Attempts to coerce from the type of a Rust function item
878        //! into a closure or a `proc`.
879
880        let b = self.shallow_resolve(b);
881        let InferOk { value: b, mut obligations } =
882            self.at(&self.cause, self.param_env).normalize(b);
883        debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
884
885        match b.kind() {
886            ty::FnPtr(_, b_hdr) => {
887                let mut a_sig = a.fn_sig(self.tcx);
888                if let ty::FnDef(def_id, _) = *a.kind() {
889                    // Intrinsics are not coercible to function pointers
890                    if self.tcx.intrinsic(def_id).is_some() {
891                        return Err(TypeError::IntrinsicCast);
892                    }
893
894                    let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
895                    if matches!(fn_attrs.inline, InlineAttr::Force { .. }) {
896                        return Err(TypeError::ForceInlineCast);
897                    }
898
899                    if b_hdr.safety.is_safe()
900                        && self.tcx.codegen_fn_attrs(def_id).safe_target_features
901                    {
902                        // Allow the coercion if the current function has all the features that would be
903                        // needed to call the coercee safely.
904                        if let Some(safe_sig) = self.tcx.adjust_target_feature_sig(
905                            def_id,
906                            a_sig,
907                            self.fcx.body_id.into(),
908                        ) {
909                            a_sig = safe_sig;
910                        } else {
911                            return Err(TypeError::TargetFeatureCast(def_id));
912                        }
913                    }
914                }
915
916                let InferOk { value: a_sig, obligations: o1 } =
917                    self.at(&self.cause, self.param_env).normalize(a_sig);
918                obligations.extend(o1);
919
920                let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
921                    a_sig,
922                    b,
923                    Some(Adjust::Pointer(PointerCoercion::ReifyFnPointer)),
924                )?;
925
926                obligations.extend(o2);
927                Ok(InferOk { value, obligations })
928            }
929            _ => self.unify(a, b),
930        }
931    }
932
933    fn coerce_closure_to_fn(
934        &self,
935        a: Ty<'tcx>,
936        closure_def_id_a: DefId,
937        args_a: GenericArgsRef<'tcx>,
938        b: Ty<'tcx>,
939    ) -> CoerceResult<'tcx> {
940        //! Attempts to coerce from the type of a non-capturing closure
941        //! into a function pointer.
942        //!
943
944        let b = self.shallow_resolve(b);
945
946        match b.kind() {
947            // At this point we haven't done capture analysis, which means
948            // that the ClosureArgs just contains an inference variable instead
949            // of tuple of captured types.
950            //
951            // All we care here is if any variable is being captured and not the exact paths,
952            // so we check `upvars_mentioned` for root variables being captured.
953            ty::FnPtr(_, hdr)
954                if self
955                    .tcx
956                    .upvars_mentioned(closure_def_id_a.expect_local())
957                    .is_none_or(|u| u.is_empty()) =>
958            {
959                // We coerce the closure, which has fn type
960                //     `extern "rust-call" fn((arg0,arg1,...)) -> _`
961                // to
962                //     `fn(arg0,arg1,...) -> _`
963                // or
964                //     `unsafe fn(arg0,arg1,...) -> _`
965                let closure_sig = args_a.as_closure().sig();
966                let safety = hdr.safety;
967                let pointer_ty =
968                    Ty::new_fn_ptr(self.tcx, self.tcx.signature_unclosure(closure_sig, safety));
969                debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
970                self.unify_and(
971                    pointer_ty,
972                    b,
973                    [],
974                    Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety)),
975                )
976            }
977            _ => self.unify(a, b),
978        }
979    }
980
981    fn coerce_raw_ptr(
982        &self,
983        a: Ty<'tcx>,
984        b: Ty<'tcx>,
985        mutbl_b: hir::Mutability,
986    ) -> CoerceResult<'tcx> {
987        debug!("coerce_raw_ptr(a={:?}, b={:?})", a, b);
988
989        let (is_ref, mt_a) = match *a.kind() {
990            ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
991            ty::RawPtr(ty, mutbl) => (false, ty::TypeAndMut { ty, mutbl }),
992            _ => return self.unify(a, b),
993        };
994        coerce_mutbls(mt_a.mutbl, mutbl_b)?;
995
996        // Check that the types which they point at are compatible.
997        let a_raw = Ty::new_ptr(self.tcx, mt_a.ty, mutbl_b);
998        // Although references and raw ptrs have the same
999        // representation, we still register an Adjust::DerefRef so that
1000        // regionck knows that the region for `a` must be valid here.
1001        if is_ref {
1002            self.unify_and(
1003                a_raw,
1004                b,
1005                [Adjustment { kind: Adjust::Deref(None), target: mt_a.ty }],
1006                Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
1007            )
1008        } else if mt_a.mutbl != mutbl_b {
1009            self.unify_and(a_raw, b, [], Adjust::Pointer(PointerCoercion::MutToConstPointer))
1010        } else {
1011            self.unify(a_raw, b)
1012        }
1013    }
1014}
1015
1016impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1017    /// Attempt to coerce an expression to a type, and return the
1018    /// adjusted type of the expression, if successful.
1019    /// Adjustments are only recorded if the coercion succeeded.
1020    /// The expressions *must not* have any preexisting adjustments.
1021    pub(crate) fn coerce(
1022        &self,
1023        expr: &'tcx hir::Expr<'tcx>,
1024        expr_ty: Ty<'tcx>,
1025        mut target: Ty<'tcx>,
1026        allow_two_phase: AllowTwoPhase,
1027        cause: Option<ObligationCause<'tcx>>,
1028    ) -> RelateResult<'tcx, Ty<'tcx>> {
1029        let source = self.try_structurally_resolve_type(expr.span, expr_ty);
1030        if self.next_trait_solver() {
1031            target = self.try_structurally_resolve_type(
1032                cause.as_ref().map_or(expr.span, |cause| cause.span),
1033                target,
1034            );
1035        }
1036        debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
1037
1038        let cause =
1039            cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
1040        let coerce = Coerce::new(
1041            self,
1042            cause,
1043            allow_two_phase,
1044            self.expr_guaranteed_to_constitute_read_for_never(expr),
1045        );
1046        let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
1047
1048        let (adjustments, _) = self.register_infer_ok_obligations(ok);
1049        self.apply_adjustments(expr, adjustments);
1050        Ok(if let Err(guar) = expr_ty.error_reported() {
1051            Ty::new_error(self.tcx, guar)
1052        } else {
1053            target
1054        })
1055    }
1056
1057    /// Probe whether `expr_ty` can be coerced to `target_ty`. This has no side-effects,
1058    /// and may return false positives if types are not yet fully constrained by inference.
1059    ///
1060    /// Returns false if the coercion is not possible, or if the coercion creates any
1061    /// sub-obligations that result in errors.
1062    ///
1063    /// This should only be used for diagnostics.
1064    pub(crate) fn may_coerce(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1065        let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1066        // We don't ever need two-phase here since we throw out the result of the coercion.
1067        // We also just always set `coerce_never` to true, since this is a heuristic.
1068        let coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1069        self.probe(|_| {
1070            // Make sure to structurally resolve the types, since we use
1071            // the `TyKind`s heavily in coercion.
1072            let ocx = ObligationCtxt::new(self);
1073            let structurally_resolve = |ty| {
1074                let ty = self.shallow_resolve(ty);
1075                if self.next_trait_solver()
1076                    && let ty::Alias(..) = ty.kind()
1077                {
1078                    ocx.structurally_normalize_ty(&cause, self.param_env, ty)
1079                } else {
1080                    Ok(ty)
1081                }
1082            };
1083            let Ok(expr_ty) = structurally_resolve(expr_ty) else {
1084                return false;
1085            };
1086            let Ok(target_ty) = structurally_resolve(target_ty) else {
1087                return false;
1088            };
1089
1090            let Ok(ok) = coerce.coerce(expr_ty, target_ty) else {
1091                return false;
1092            };
1093            ocx.register_obligations(ok.obligations);
1094            ocx.select_where_possible().is_empty()
1095        })
1096    }
1097
1098    /// Given a type and a target type, this function will calculate and return
1099    /// how many dereference steps needed to coerce `expr_ty` to `target`. If
1100    /// it's not possible, return `None`.
1101    pub(crate) fn deref_steps_for_suggestion(
1102        &self,
1103        expr_ty: Ty<'tcx>,
1104        target: Ty<'tcx>,
1105    ) -> Option<usize> {
1106        let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1107        // We don't ever need two-phase here since we throw out the result of the coercion.
1108        let coerce = Coerce::new(self, cause, AllowTwoPhase::No, true);
1109        coerce.autoderef(DUMMY_SP, expr_ty).find_map(|(ty, steps)| {
1110            self.probe(|_| coerce.unify_raw(ty, target)).ok().map(|_| steps)
1111        })
1112    }
1113
1114    /// Given a type, this function will calculate and return the type given
1115    /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1116    ///
1117    /// This function is for diagnostics only, since it does not register
1118    /// trait or region sub-obligations. (presumably we could, but it's not
1119    /// particularly important for diagnostics...)
1120    pub(crate) fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1121        self.autoderef(DUMMY_SP, expr_ty).silence_errors().nth(1).and_then(|(deref_ty, _)| {
1122            self.infcx
1123                .type_implements_trait(
1124                    self.tcx.lang_items().deref_mut_trait()?,
1125                    [expr_ty],
1126                    self.param_env,
1127                )
1128                .may_apply()
1129                .then_some(deref_ty)
1130        })
1131    }
1132
1133    /// Given some expressions, their known unified type and another expression,
1134    /// tries to unify the types, potentially inserting coercions on any of the
1135    /// provided expressions and returns their LUB (aka "common supertype").
1136    ///
1137    /// This is really an internal helper. From outside the coercion
1138    /// module, you should instantiate a `CoerceMany` instance.
1139    fn try_find_coercion_lub<E>(
1140        &self,
1141        cause: &ObligationCause<'tcx>,
1142        exprs: &[E],
1143        prev_ty: Ty<'tcx>,
1144        new: &hir::Expr<'_>,
1145        new_ty: Ty<'tcx>,
1146    ) -> RelateResult<'tcx, Ty<'tcx>>
1147    where
1148        E: AsCoercionSite,
1149    {
1150        let prev_ty = self.try_structurally_resolve_type(cause.span, prev_ty);
1151        let new_ty = self.try_structurally_resolve_type(new.span, new_ty);
1152        debug!(
1153            "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1154            prev_ty,
1155            new_ty,
1156            exprs.len()
1157        );
1158
1159        // The following check fixes #88097, where the compiler erroneously
1160        // attempted to coerce a closure type to itself via a function pointer.
1161        if prev_ty == new_ty {
1162            return Ok(prev_ty);
1163        }
1164
1165        let is_force_inline = |ty: Ty<'tcx>| {
1166            if let ty::FnDef(did, _) = ty.kind() {
1167                matches!(self.tcx.codegen_fn_attrs(did).inline, InlineAttr::Force { .. })
1168            } else {
1169                false
1170            }
1171        };
1172        if is_force_inline(prev_ty) || is_force_inline(new_ty) {
1173            return Err(TypeError::ForceInlineCast);
1174        }
1175
1176        // Special-case that coercion alone cannot handle:
1177        // Function items or non-capturing closures of differing IDs or GenericArgs.
1178        let (a_sig, b_sig) = {
1179            let is_capturing_closure = |ty: Ty<'tcx>| {
1180                if let &ty::Closure(closure_def_id, _args) = ty.kind() {
1181                    self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
1182                } else {
1183                    false
1184                }
1185            };
1186            if is_capturing_closure(prev_ty) || is_capturing_closure(new_ty) {
1187                (None, None)
1188            } else {
1189                match (prev_ty.kind(), new_ty.kind()) {
1190                    (ty::FnDef(..), ty::FnDef(..)) => {
1191                        // Don't reify if the function types have a LUB, i.e., they
1192                        // are the same function and their parameters have a LUB.
1193                        match self
1194                            .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1195                        {
1196                            // We have a LUB of prev_ty and new_ty, just return it.
1197                            Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1198                            Err(_) => {
1199                                (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
1200                            }
1201                        }
1202                    }
1203                    (ty::Closure(_, args), ty::FnDef(..)) => {
1204                        let b_sig = new_ty.fn_sig(self.tcx);
1205                        let a_sig =
1206                            self.tcx.signature_unclosure(args.as_closure().sig(), b_sig.safety());
1207                        (Some(a_sig), Some(b_sig))
1208                    }
1209                    (ty::FnDef(..), ty::Closure(_, args)) => {
1210                        let a_sig = prev_ty.fn_sig(self.tcx);
1211                        let b_sig =
1212                            self.tcx.signature_unclosure(args.as_closure().sig(), a_sig.safety());
1213                        (Some(a_sig), Some(b_sig))
1214                    }
1215                    (ty::Closure(_, args_a), ty::Closure(_, args_b)) => (
1216                        Some(
1217                            self.tcx
1218                                .signature_unclosure(args_a.as_closure().sig(), hir::Safety::Safe),
1219                        ),
1220                        Some(
1221                            self.tcx
1222                                .signature_unclosure(args_b.as_closure().sig(), hir::Safety::Safe),
1223                        ),
1224                    ),
1225                    _ => (None, None),
1226                }
1227            }
1228        };
1229        if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
1230            // The signature must match.
1231            let (a_sig, b_sig) = self.normalize(new.span, (a_sig, b_sig));
1232            let sig = self
1233                .at(cause, self.param_env)
1234                .lub(a_sig, b_sig)
1235                .map(|ok| self.register_infer_ok_obligations(ok))?;
1236
1237            // Reify both sides and return the reified fn pointer type.
1238            let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
1239            let prev_adjustment = match prev_ty.kind() {
1240                ty::Closure(..) => {
1241                    Adjust::Pointer(PointerCoercion::ClosureFnPointer(a_sig.safety()))
1242                }
1243                ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer),
1244                _ => span_bug!(cause.span, "should not try to coerce a {prev_ty} to a fn pointer"),
1245            };
1246            let next_adjustment = match new_ty.kind() {
1247                ty::Closure(..) => {
1248                    Adjust::Pointer(PointerCoercion::ClosureFnPointer(b_sig.safety()))
1249                }
1250                ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer),
1251                _ => span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"),
1252            };
1253            for expr in exprs.iter().map(|e| e.as_coercion_site()) {
1254                self.apply_adjustments(
1255                    expr,
1256                    vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1257                );
1258            }
1259            self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1260            return Ok(fn_ptr);
1261        }
1262
1263        // Configure a Coerce instance to compute the LUB.
1264        // We don't allow two-phase borrows on any autorefs this creates since we
1265        // probably aren't processing function arguments here and even if we were,
1266        // they're going to get autorefed again anyway and we can apply 2-phase borrows
1267        // at that time.
1268        //
1269        // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1270        // operate on values and not places, so a never coercion is valid.
1271        let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1272        coerce.use_lub = true;
1273
1274        // First try to coerce the new expression to the type of the previous ones,
1275        // but only if the new expression has no coercion already applied to it.
1276        let mut first_error = None;
1277        if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1278            let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1279            match result {
1280                Ok(ok) => {
1281                    let (adjustments, target) = self.register_infer_ok_obligations(ok);
1282                    self.apply_adjustments(new, adjustments);
1283                    debug!(
1284                        "coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1285                        new_ty, prev_ty, target
1286                    );
1287                    return Ok(target);
1288                }
1289                Err(e) => first_error = Some(e),
1290            }
1291        }
1292
1293        match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1294            Err(_) => {
1295                // Avoid giving strange errors on failed attempts.
1296                if let Some(e) = first_error {
1297                    Err(e)
1298                } else {
1299                    Err(self
1300                        .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1301                        .unwrap_err())
1302                }
1303            }
1304            Ok(ok) => {
1305                let (adjustments, target) = self.register_infer_ok_obligations(ok);
1306                for expr in exprs {
1307                    let expr = expr.as_coercion_site();
1308                    self.apply_adjustments(expr, adjustments.clone());
1309                }
1310                debug!(
1311                    "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1312                    prev_ty, new_ty, target
1313                );
1314                Ok(target)
1315            }
1316        }
1317    }
1318}
1319
1320/// Check whether `ty` can be coerced to `output_ty`.
1321/// Used from clippy.
1322pub fn can_coerce<'tcx>(
1323    tcx: TyCtxt<'tcx>,
1324    param_env: ty::ParamEnv<'tcx>,
1325    body_id: LocalDefId,
1326    ty: Ty<'tcx>,
1327    output_ty: Ty<'tcx>,
1328) -> bool {
1329    let root_ctxt = crate::typeck_root_ctxt::TypeckRootCtxt::new(tcx, body_id);
1330    let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, body_id);
1331    fn_ctxt.may_coerce(ty, output_ty)
1332}
1333
1334/// CoerceMany encapsulates the pattern you should use when you have
1335/// many expressions that are all getting coerced to a common
1336/// type. This arises, for example, when you have a match (the result
1337/// of each arm is coerced to a common type). It also arises in less
1338/// obvious places, such as when you have many `break foo` expressions
1339/// that target the same loop, or the various `return` expressions in
1340/// a function.
1341///
1342/// The basic protocol is as follows:
1343///
1344/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1345///   This will also serve as the "starting LUB". The expectation is
1346///   that this type is something which all of the expressions *must*
1347///   be coercible to. Use a fresh type variable if needed.
1348/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1349///   - In some cases we wish to coerce "non-expressions" whose types are implicitly
1350///     unit. This happens for example if you have a `break` with no expression,
1351///     or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1352///   - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1353///     from you so that you don't have to worry your pretty head about it.
1354///     But if an error is reported, the final type will be `err`.
1355///   - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1356///     previously coerced expressions.
1357/// - When all done, invoke `complete()`. This will return the LUB of
1358///   all your expressions.
1359///   - WARNING: I don't believe this final type is guaranteed to be
1360///     related to your initial `expected_ty` in any particular way,
1361///     although it will typically be a subtype, so you should check it.
1362///   - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1363///     previously coerced expressions.
1364///
1365/// Example:
1366///
1367/// ```ignore (illustrative)
1368/// let mut coerce = CoerceMany::new(expected_ty);
1369/// for expr in exprs {
1370///     let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1371///     coerce.coerce(fcx, &cause, expr, expr_ty);
1372/// }
1373/// let final_ty = coerce.complete(fcx);
1374/// ```
1375pub(crate) struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1376    expected_ty: Ty<'tcx>,
1377    final_ty: Option<Ty<'tcx>>,
1378    expressions: Expressions<'tcx, 'exprs, E>,
1379    pushed: usize,
1380}
1381
1382/// The type of a `CoerceMany` that is storing up the expressions into
1383/// a buffer. We use this in `check/mod.rs` for things like `break`.
1384pub(crate) type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1385
1386enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1387    Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1388    UpFront(&'exprs [E]),
1389}
1390
1391impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1392    /// The usual case; collect the set of expressions dynamically.
1393    /// If the full set of coercion sites is known before hand,
1394    /// consider `with_coercion_sites()` instead to avoid allocation.
1395    pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self {
1396        Self::make(expected_ty, Expressions::Dynamic(vec![]))
1397    }
1398
1399    /// As an optimization, you can create a `CoerceMany` with a
1400    /// preexisting slice of expressions. In this case, you are
1401    /// expected to pass each element in the slice to `coerce(...)` in
1402    /// order. This is used with arrays in particular to avoid
1403    /// needlessly cloning the slice.
1404    pub(crate) fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1405        Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1406    }
1407
1408    fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1409        CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1410    }
1411
1412    /// Returns the "expected type" with which this coercion was
1413    /// constructed. This represents the "downward propagated" type
1414    /// that was given to us at the start of typing whatever construct
1415    /// we are typing (e.g., the match expression).
1416    ///
1417    /// Typically, this is used as the expected type when
1418    /// type-checking each of the alternative expressions whose types
1419    /// we are trying to merge.
1420    pub(crate) fn expected_ty(&self) -> Ty<'tcx> {
1421        self.expected_ty
1422    }
1423
1424    /// Returns the current "merged type", representing our best-guess
1425    /// at the LUB of the expressions we've seen so far (if any). This
1426    /// isn't *final* until you call `self.complete()`, which will return
1427    /// the merged type.
1428    pub(crate) fn merged_ty(&self) -> Ty<'tcx> {
1429        self.final_ty.unwrap_or(self.expected_ty)
1430    }
1431
1432    /// Indicates that the value generated by `expression`, which is
1433    /// of type `expression_ty`, is one of the possibilities that we
1434    /// could coerce from. This will record `expression`, and later
1435    /// calls to `coerce` may come back and add adjustments and things
1436    /// if necessary.
1437    pub(crate) fn coerce<'a>(
1438        &mut self,
1439        fcx: &FnCtxt<'a, 'tcx>,
1440        cause: &ObligationCause<'tcx>,
1441        expression: &'tcx hir::Expr<'tcx>,
1442        expression_ty: Ty<'tcx>,
1443    ) {
1444        self.coerce_inner(fcx, cause, Some(expression), expression_ty, |_| {}, false)
1445    }
1446
1447    /// Indicates that one of the inputs is a "forced unit". This
1448    /// occurs in a case like `if foo { ... };`, where the missing else
1449    /// generates a "forced unit". Another example is a `loop { break;
1450    /// }`, where the `break` has no argument expression. We treat
1451    /// these cases slightly differently for error-reporting
1452    /// purposes. Note that these tend to correspond to cases where
1453    /// the `()` expression is implicit in the source, and hence we do
1454    /// not take an expression argument.
1455    ///
1456    /// The `augment_error` gives you a chance to extend the error
1457    /// message, in case any results (e.g., we use this to suggest
1458    /// removing a `;`).
1459    pub(crate) fn coerce_forced_unit<'a>(
1460        &mut self,
1461        fcx: &FnCtxt<'a, 'tcx>,
1462        cause: &ObligationCause<'tcx>,
1463        augment_error: impl FnOnce(&mut Diag<'_>),
1464        label_unit_as_expected: bool,
1465    ) {
1466        self.coerce_inner(
1467            fcx,
1468            cause,
1469            None,
1470            fcx.tcx.types.unit,
1471            augment_error,
1472            label_unit_as_expected,
1473        )
1474    }
1475
1476    /// The inner coercion "engine". If `expression` is `None`, this
1477    /// is a forced-unit case, and hence `expression_ty` must be
1478    /// `Nil`.
1479    #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1480    pub(crate) fn coerce_inner<'a>(
1481        &mut self,
1482        fcx: &FnCtxt<'a, 'tcx>,
1483        cause: &ObligationCause<'tcx>,
1484        expression: Option<&'tcx hir::Expr<'tcx>>,
1485        mut expression_ty: Ty<'tcx>,
1486        augment_error: impl FnOnce(&mut Diag<'_>),
1487        label_expression_as_expected: bool,
1488    ) {
1489        // Incorporate whatever type inference information we have
1490        // until now; in principle we might also want to process
1491        // pending obligations, but doing so should only improve
1492        // compatibility (hopefully that is true) by helping us
1493        // uncover never types better.
1494        if expression_ty.is_ty_var() {
1495            expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1496        }
1497
1498        // If we see any error types, just propagate that error
1499        // upwards.
1500        if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1501            self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1502            return;
1503        }
1504
1505        let (expected, found) = if label_expression_as_expected {
1506            // In the case where this is a "forced unit", like
1507            // `break`, we want to call the `()` "expected"
1508            // since it is implied by the syntax.
1509            // (Note: not all force-units work this way.)"
1510            (expression_ty, self.merged_ty())
1511        } else {
1512            // Otherwise, the "expected" type for error
1513            // reporting is the current unification type,
1514            // which is basically the LUB of the expressions
1515            // we've seen so far (combined with the expected
1516            // type)
1517            (self.merged_ty(), expression_ty)
1518        };
1519
1520        // Handle the actual type unification etc.
1521        let result = if let Some(expression) = expression {
1522            if self.pushed == 0 {
1523                // Special-case the first expression we are coercing.
1524                // To be honest, I'm not entirely sure why we do this.
1525                // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1526                fcx.coerce(
1527                    expression,
1528                    expression_ty,
1529                    self.expected_ty,
1530                    AllowTwoPhase::No,
1531                    Some(cause.clone()),
1532                )
1533            } else {
1534                match self.expressions {
1535                    Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1536                        cause,
1537                        exprs,
1538                        self.merged_ty(),
1539                        expression,
1540                        expression_ty,
1541                    ),
1542                    Expressions::UpFront(coercion_sites) => fcx.try_find_coercion_lub(
1543                        cause,
1544                        &coercion_sites[0..self.pushed],
1545                        self.merged_ty(),
1546                        expression,
1547                        expression_ty,
1548                    ),
1549                }
1550            }
1551        } else {
1552            // this is a hack for cases where we default to `()` because
1553            // the expression etc has been omitted from the source. An
1554            // example is an `if let` without an else:
1555            //
1556            //     if let Some(x) = ... { }
1557            //
1558            // we wind up with a second match arm that is like `_ =>
1559            // ()`. That is the case we are considering here. We take
1560            // a different path to get the right "expected, found"
1561            // message and so forth (and because we know that
1562            // `expression_ty` will be unit).
1563            //
1564            // Another example is `break` with no argument expression.
1565            assert!(expression_ty.is_unit(), "if let hack without unit type");
1566            fcx.at(cause, fcx.param_env)
1567                .eq(
1568                    // needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1569                    DefineOpaqueTypes::Yes,
1570                    expected,
1571                    found,
1572                )
1573                .map(|infer_ok| {
1574                    fcx.register_infer_ok_obligations(infer_ok);
1575                    expression_ty
1576                })
1577        };
1578
1579        debug!(?result);
1580        match result {
1581            Ok(v) => {
1582                self.final_ty = Some(v);
1583                if let Some(e) = expression {
1584                    match self.expressions {
1585                        Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1586                        Expressions::UpFront(coercion_sites) => {
1587                            // if the user gave us an array to validate, check that we got
1588                            // the next expression in the list, as expected
1589                            assert_eq!(
1590                                coercion_sites[self.pushed].as_coercion_site().hir_id,
1591                                e.hir_id
1592                            );
1593                        }
1594                    }
1595                    self.pushed += 1;
1596                }
1597            }
1598            Err(coercion_error) => {
1599                // Mark that we've failed to coerce the types here to suppress
1600                // any superfluous errors we might encounter while trying to
1601                // emit or provide suggestions on how to fix the initial error.
1602                fcx.set_tainted_by_errors(
1603                    fcx.dcx().span_delayed_bug(cause.span, "coercion error but no error emitted"),
1604                );
1605                let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
1606
1607                let mut err;
1608                let mut unsized_return = false;
1609                match *cause.code() {
1610                    ObligationCauseCode::ReturnNoExpression => {
1611                        err = struct_span_code_err!(
1612                            fcx.dcx(),
1613                            cause.span,
1614                            E0069,
1615                            "`return;` in a function whose return type is not `()`"
1616                        );
1617                        if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1618                        {
1619                            err.span_suggestion_verbose(
1620                                cause.span.shrink_to_hi(),
1621                                "give the `return` a value of the expected type",
1622                                format!(" {value}"),
1623                                Applicability::HasPlaceholders,
1624                            );
1625                        }
1626                        err.span_label(cause.span, "return type is not `()`");
1627                    }
1628                    ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
1629                        err = self.report_return_mismatched_types(
1630                            cause,
1631                            expected,
1632                            found,
1633                            coercion_error,
1634                            fcx,
1635                            blk_id,
1636                            expression,
1637                        );
1638                        if !fcx.tcx.features().unsized_locals() {
1639                            unsized_return = self.is_return_ty_definitely_unsized(fcx);
1640                        }
1641                    }
1642                    ObligationCauseCode::ReturnValue(return_expr_id) => {
1643                        err = self.report_return_mismatched_types(
1644                            cause,
1645                            expected,
1646                            found,
1647                            coercion_error,
1648                            fcx,
1649                            return_expr_id,
1650                            expression,
1651                        );
1652                        if !fcx.tcx.features().unsized_locals() {
1653                            unsized_return = self.is_return_ty_definitely_unsized(fcx);
1654                        }
1655                    }
1656                    ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1657                        arm_span,
1658                        arm_ty,
1659                        prior_arm_ty,
1660                        ref prior_non_diverging_arms,
1661                        tail_defines_return_position_impl_trait: Some(rpit_def_id),
1662                        ..
1663                    }) => {
1664                        err = fcx.err_ctxt().report_mismatched_types(
1665                            cause,
1666                            fcx.param_env,
1667                            expected,
1668                            found,
1669                            coercion_error,
1670                        );
1671                        // Check that we're actually in the second or later arm
1672                        if prior_non_diverging_arms.len() > 0 {
1673                            self.suggest_boxing_tail_for_return_position_impl_trait(
1674                                fcx,
1675                                &mut err,
1676                                rpit_def_id,
1677                                arm_ty,
1678                                prior_arm_ty,
1679                                prior_non_diverging_arms
1680                                    .iter()
1681                                    .chain(std::iter::once(&arm_span))
1682                                    .copied(),
1683                            );
1684                        }
1685                    }
1686                    ObligationCauseCode::IfExpression(box IfExpressionCause {
1687                        then_id,
1688                        else_id,
1689                        then_ty,
1690                        else_ty,
1691                        tail_defines_return_position_impl_trait: Some(rpit_def_id),
1692                        ..
1693                    }) => {
1694                        err = fcx.err_ctxt().report_mismatched_types(
1695                            cause,
1696                            fcx.param_env,
1697                            expected,
1698                            found,
1699                            coercion_error,
1700                        );
1701                        let then_span = fcx.find_block_span_from_hir_id(then_id);
1702                        let else_span = fcx.find_block_span_from_hir_id(else_id);
1703                        // don't suggest wrapping either blocks in `if .. {} else {}`
1704                        let is_empty_arm = |id| {
1705                            let hir::Node::Block(blk) = fcx.tcx.hir_node(id) else {
1706                                return false;
1707                            };
1708                            if blk.expr.is_some() || !blk.stmts.is_empty() {
1709                                return false;
1710                            }
1711                            let Some((_, hir::Node::Expr(expr))) =
1712                                fcx.tcx.hir_parent_iter(id).nth(1)
1713                            else {
1714                                return false;
1715                            };
1716                            matches!(expr.kind, hir::ExprKind::If(..))
1717                        };
1718                        if !is_empty_arm(then_id) && !is_empty_arm(else_id) {
1719                            self.suggest_boxing_tail_for_return_position_impl_trait(
1720                                fcx,
1721                                &mut err,
1722                                rpit_def_id,
1723                                then_ty,
1724                                else_ty,
1725                                [then_span, else_span].into_iter(),
1726                            );
1727                        }
1728                    }
1729                    _ => {
1730                        err = fcx.err_ctxt().report_mismatched_types(
1731                            cause,
1732                            fcx.param_env,
1733                            expected,
1734                            found,
1735                            coercion_error,
1736                        );
1737                    }
1738                }
1739
1740                augment_error(&mut err);
1741
1742                if let Some(expr) = expression {
1743                    if let hir::ExprKind::Loop(
1744                        _,
1745                        _,
1746                        loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop),
1747                        _,
1748                    ) = expr.kind
1749                    {
1750                        let loop_type = if loop_src == hir::LoopSource::While {
1751                            "`while` loops"
1752                        } else {
1753                            "`for` loops"
1754                        };
1755
1756                        err.note(format!("{loop_type} evaluate to unit type `()`"));
1757                    }
1758
1759                    fcx.emit_coerce_suggestions(
1760                        &mut err,
1761                        expr,
1762                        found,
1763                        expected,
1764                        None,
1765                        Some(coercion_error),
1766                    );
1767                }
1768
1769                let reported = err.emit_unless(unsized_return);
1770
1771                self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
1772            }
1773        }
1774    }
1775
1776    fn suggest_boxing_tail_for_return_position_impl_trait(
1777        &self,
1778        fcx: &FnCtxt<'_, 'tcx>,
1779        err: &mut Diag<'_>,
1780        rpit_def_id: LocalDefId,
1781        a_ty: Ty<'tcx>,
1782        b_ty: Ty<'tcx>,
1783        arm_spans: impl Iterator<Item = Span>,
1784    ) {
1785        let compatible = |ty: Ty<'tcx>| {
1786            fcx.probe(|_| {
1787                let ocx = ObligationCtxt::new(fcx);
1788                ocx.register_obligations(
1789                    fcx.tcx.item_self_bounds(rpit_def_id).iter_identity().filter_map(|clause| {
1790                        let predicate = clause
1791                            .kind()
1792                            .map_bound(|clause| match clause {
1793                                ty::ClauseKind::Trait(trait_pred) => Some(ty::ClauseKind::Trait(
1794                                    trait_pred.with_self_ty(fcx.tcx, ty),
1795                                )),
1796                                ty::ClauseKind::Projection(proj_pred) => Some(
1797                                    ty::ClauseKind::Projection(proj_pred.with_self_ty(fcx.tcx, ty)),
1798                                ),
1799                                _ => None,
1800                            })
1801                            .transpose()?;
1802                        Some(Obligation::new(
1803                            fcx.tcx,
1804                            ObligationCause::dummy(),
1805                            fcx.param_env,
1806                            predicate,
1807                        ))
1808                    }),
1809                );
1810                ocx.select_where_possible().is_empty()
1811            })
1812        };
1813
1814        if !compatible(a_ty) || !compatible(b_ty) {
1815            return;
1816        }
1817
1818        let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
1819        err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1820            start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1821            end_sp: rpid_def_span.shrink_to_hi(),
1822        });
1823
1824        let (starts, ends) =
1825            arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
1826        err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
1827    }
1828
1829    fn report_return_mismatched_types<'infcx>(
1830        &self,
1831        cause: &ObligationCause<'tcx>,
1832        expected: Ty<'tcx>,
1833        found: Ty<'tcx>,
1834        ty_err: TypeError<'tcx>,
1835        fcx: &'infcx FnCtxt<'_, 'tcx>,
1836        block_or_return_id: hir::HirId,
1837        expression: Option<&'tcx hir::Expr<'tcx>>,
1838    ) -> Diag<'infcx> {
1839        let mut err =
1840            fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err);
1841
1842        let due_to_block = matches!(fcx.tcx.hir_node(block_or_return_id), hir::Node::Block(..));
1843
1844        let parent_id = fcx.tcx.parent_hir_id(block_or_return_id);
1845        let parent = fcx.tcx.hir_node(parent_id);
1846        if let Some(expr) = expression
1847            && let hir::Node::Expr(&hir::Expr {
1848                kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
1849                ..
1850            }) = parent
1851            && !matches!(fcx.tcx.hir_body(body).value.kind, hir::ExprKind::Block(..))
1852        {
1853            fcx.suggest_missing_semicolon(&mut err, expr, expected, true);
1854        }
1855        // Verify that this is a tail expression of a function, otherwise the
1856        // label pointing out the cause for the type coercion will be wrong
1857        // as prior return coercions would not be relevant (#57664).
1858        if let Some(expr) = expression
1859            && due_to_block
1860        {
1861            fcx.suggest_missing_semicolon(&mut err, expr, expected, false);
1862            let pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1863                &mut err,
1864                expr,
1865                expected,
1866                found,
1867                block_or_return_id,
1868            );
1869            if let Some(cond_expr) = fcx.tcx.hir_get_if_cause(expr.hir_id)
1870                && expected.is_unit()
1871                && !pointing_at_return_type
1872                // If the block is from an external macro or try (`?`) desugaring, then
1873                // do not suggest adding a semicolon, because there's nowhere to put it.
1874                // See issues #81943 and #87051.
1875                && matches!(
1876                    cond_expr.span.desugaring_kind(),
1877                    None | Some(DesugaringKind::WhileLoop)
1878                )
1879                && !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
1880                && !matches!(
1881                    cond_expr.kind,
1882                    hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))
1883                )
1884            {
1885                err.span_label(cond_expr.span, "expected this to be `()`");
1886                if expr.can_have_side_effects() {
1887                    fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1888                }
1889            }
1890        };
1891
1892        // If this is due to an explicit `return`, suggest adding a return type.
1893        if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
1894            && !due_to_block
1895        {
1896            fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
1897        }
1898
1899        // If this is due to a block, then maybe we forgot a `return`/`break`.
1900        if due_to_block
1901            && let Some(expr) = expression
1902            && let Some(parent_fn_decl) =
1903                fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_id))
1904        {
1905            fcx.suggest_missing_break_or_return_expr(
1906                &mut err,
1907                expr,
1908                parent_fn_decl,
1909                expected,
1910                found,
1911                block_or_return_id,
1912                fcx.body_id,
1913            );
1914        }
1915
1916        let ret_coercion_span = fcx.ret_coercion_span.get();
1917
1918        if let Some(sp) = ret_coercion_span
1919            // If the closure has an explicit return type annotation, or if
1920            // the closure's return type has been inferred from outside
1921            // requirements (such as an Fn* trait bound), then a type error
1922            // may occur at the first return expression we see in the closure
1923            // (if it conflicts with the declared return type). Skip adding a
1924            // note in this case, since it would be incorrect.
1925            && let Some(fn_sig) = fcx.body_fn_sig()
1926            && fn_sig.output().is_ty_var()
1927        {
1928            err.span_note(sp, format!("return type inferred to be `{expected}` here"));
1929        }
1930
1931        err
1932    }
1933
1934    /// Checks whether the return type is unsized via an obligation, which makes
1935    /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
1936    /// false but technically valid for typeck.
1937    fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
1938        if let Some(sig) = fcx.body_fn_sig() {
1939            !fcx.predicate_may_hold(&Obligation::new(
1940                fcx.tcx,
1941                ObligationCause::dummy(),
1942                fcx.param_env,
1943                ty::TraitRef::new(
1944                    fcx.tcx,
1945                    fcx.tcx.require_lang_item(hir::LangItem::Sized, None),
1946                    [sig.output()],
1947                ),
1948            ))
1949        } else {
1950            false
1951        }
1952    }
1953
1954    pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1955        if let Some(final_ty) = self.final_ty {
1956            final_ty
1957        } else {
1958            // If we only had inputs that were of type `!` (or no
1959            // inputs at all), then the final type is `!`.
1960            assert_eq!(self.pushed, 0);
1961            fcx.tcx.types.never
1962        }
1963    }
1964}
1965
1966/// Something that can be converted into an expression to which we can
1967/// apply a coercion.
1968pub(crate) trait AsCoercionSite {
1969    fn as_coercion_site(&self) -> &hir::Expr<'_>;
1970}
1971
1972impl AsCoercionSite for hir::Expr<'_> {
1973    fn as_coercion_site(&self) -> &hir::Expr<'_> {
1974        self
1975    }
1976}
1977
1978impl<'a, T> AsCoercionSite for &'a T
1979where
1980    T: AsCoercionSite,
1981{
1982    fn as_coercion_site(&self) -> &hir::Expr<'_> {
1983        (**self).as_coercion_site()
1984    }
1985}
1986
1987impl AsCoercionSite for ! {
1988    fn as_coercion_site(&self) -> &hir::Expr<'_> {
1989        *self
1990    }
1991}
1992
1993impl AsCoercionSite for hir::Arm<'_> {
1994    fn as_coercion_site(&self) -> &hir::Expr<'_> {
1995        self.body
1996    }
1997}