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