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