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