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