]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/coercion.rs
Rollup merge of #88859 - RalfJung:size-helpers, r=oli-obk
[rust.git] / compiler / rustc_typeck / src / check / 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 infering the generic arguments of functions, the argument
22 //! order is relevant, which can lead to the following edge case:
23 //!
24 //! ```rust
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::astconv::AstConv;
39 use crate::check::FnCtxt;
40 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
41 use rustc_hir as hir;
42 use rustc_hir::def_id::DefId;
43 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
44 use rustc_infer::infer::{Coercion, InferOk, InferResult};
45 use rustc_infer::traits::Obligation;
46 use rustc_middle::lint::in_external_macro;
47 use rustc_middle::ty::adjustment::{
48     Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast,
49 };
50 use rustc_middle::ty::error::TypeError;
51 use rustc_middle::ty::fold::TypeFoldable;
52 use rustc_middle::ty::relate::RelateResult;
53 use rustc_middle::ty::subst::SubstsRef;
54 use rustc_middle::ty::{self, ToPredicate, Ty, TypeAndMut};
55 use rustc_session::parse::feature_err;
56 use rustc_span::symbol::sym;
57 use rustc_span::{self, BytePos, Span};
58 use rustc_target::spec::abi::Abi;
59 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
60 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode};
61
62 use smallvec::{smallvec, SmallVec};
63 use std::ops::Deref;
64
65 struct Coerce<'a, 'tcx> {
66     fcx: &'a FnCtxt<'a, 'tcx>,
67     cause: ObligationCause<'tcx>,
68     use_lub: bool,
69     /// Determines whether or not allow_two_phase_borrow is set on any
70     /// autoref adjustments we create while coercing. We don't want to
71     /// allow deref coercions to create two-phase borrows, at least initially,
72     /// but we do need two-phase borrows for function argument reborrows.
73     /// See #47489 and #48598
74     /// See docs on the "AllowTwoPhase" type for a more detailed discussion
75     allow_two_phase: AllowTwoPhase,
76 }
77
78 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
79     type Target = FnCtxt<'a, 'tcx>;
80     fn deref(&self) -> &Self::Target {
81         &self.fcx
82     }
83 }
84
85 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
86
87 /// Coercing a mutable reference to an immutable works, while
88 /// coercing `&T` to `&mut T` should be forbidden.
89 fn coerce_mutbls<'tcx>(
90     from_mutbl: hir::Mutability,
91     to_mutbl: hir::Mutability,
92 ) -> RelateResult<'tcx, ()> {
93     match (from_mutbl, to_mutbl) {
94         (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not)
95         | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()),
96         (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability),
97     }
98 }
99
100 /// Do not require any adjustments, i.e. coerce `x -> x`.
101 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> {
102     vec![]
103 }
104
105 fn simple(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
106     move |target| vec![Adjustment { kind, target }]
107 }
108
109 /// This always returns `Ok(...)`.
110 fn success<'tcx>(
111     adj: Vec<Adjustment<'tcx>>,
112     target: Ty<'tcx>,
113     obligations: traits::PredicateObligations<'tcx>,
114 ) -> CoerceResult<'tcx> {
115     Ok(InferOk { value: (adj, target), obligations })
116 }
117
118 impl<'f, 'tcx> Coerce<'f, 'tcx> {
119     fn new(
120         fcx: &'f FnCtxt<'f, 'tcx>,
121         cause: ObligationCause<'tcx>,
122         allow_two_phase: AllowTwoPhase,
123     ) -> Self {
124         Coerce { fcx, cause, allow_two_phase, use_lub: false }
125     }
126
127     fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
128         debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
129         self.commit_if_ok(|_| {
130             if self.use_lub {
131                 self.at(&self.cause, self.fcx.param_env).lub(b, a)
132             } else {
133                 self.at(&self.cause, self.fcx.param_env)
134                     .sup(b, a)
135                     .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
136             }
137         })
138     }
139
140     /// Unify two types (using sub or lub) and produce a specific coercion.
141     fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx>
142     where
143         F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
144     {
145         self.unify(&a, &b)
146             .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations))
147     }
148
149     fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
150         // First, remove any resolved type variables (at the top level, at least):
151         let a = self.shallow_resolve(a);
152         let b = self.shallow_resolve(b);
153         debug!("Coerce.tys({:?} => {:?})", a, b);
154
155         // Just ignore error types.
156         if a.references_error() || b.references_error() {
157             return success(vec![], self.fcx.tcx.ty_error(), vec![]);
158         }
159
160         // Coercing from `!` to any type is allowed:
161         if a.is_never() {
162             // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
163             // type variable, we want `?T` to fallback to `!` if not
164             // otherwise constrained. An example where this arises:
165             //
166             //     let _: Option<?T> = Some({ return; });
167             //
168             // here, we would coerce from `!` to `?T`.
169             return if b.is_ty_var() {
170                 // Micro-optimization: no need for this if `b` is
171                 // already resolved in some way.
172                 let diverging_ty = self.next_diverging_ty_var(TypeVariableOrigin {
173                     kind: TypeVariableOriginKind::AdjustmentType,
174                     span: self.cause.span,
175                 });
176                 self.coerce_from_inference_variable(diverging_ty, b, simple(Adjust::NeverToAny))
177             } else {
178                 success(simple(Adjust::NeverToAny)(b), b, vec![])
179             };
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(TypeError::ObjectUnsafeCoercion(did)) => {
201                 debug!("coerce: unsize not object safe");
202                 return Err(TypeError::ObjectUnsafeCoercion(did));
203             }
204             Err(_) => {}
205         }
206         debug!("coerce: unsize failed");
207
208         // Examine the supertype and consider auto-borrowing.
209         match *b.kind() {
210             ty::RawPtr(mt_b) => {
211                 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
212             }
213             ty::Ref(r_b, _, mutbl_b) => {
214                 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
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.infcx.shallow_resolve(a) == a);
257         assert!(self.infcx.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.infcx.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.cause.clone(),
275                         self.param_env,
276                         ty::PredicateKind::Coerce(ty::CoercePredicate {
277                             a: source_ty,
278                             b: target_ty,
279                         })
280                         .to_predicate(self.tcx()),
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 InferOk { value: ty, mut obligations } = match found {
448             Some(d) => d,
449             None => {
450                 let err = first_error.expect("coerce_borrowed_pointer had no error");
451                 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
452                 return Err(err);
453             }
454         };
455
456         if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 {
457             // As a special case, if we would produce `&'a *x`, that's
458             // a total no-op. We end up with the type `&'a T` just as
459             // we started with.  In that case, just skip it
460             // altogether. This is just an optimization.
461             //
462             // Note that for `&mut`, we DO want to reborrow --
463             // otherwise, this would be a move, which might be an
464             // error. For example `foo(self.x)` where `self` and
465             // `self.x` both have `&mut `type would be a move of
466             // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
467             // which is a borrow.
468             assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U
469             return success(vec![], ty, obligations);
470         }
471
472         let InferOk { value: mut adjustments, obligations: o } =
473             self.adjust_steps_as_infer_ok(&autoderef);
474         obligations.extend(o);
475         obligations.extend(autoderef.into_obligations());
476
477         // Now apply the autoref. We have to extract the region out of
478         // the final ref type we got.
479         let r_borrow = match ty.kind() {
480             ty::Ref(r_borrow, _, _) => r_borrow,
481             _ => span_bug!(span, "expected a ref type, got {:?}", ty),
482         };
483         let mutbl = match mutbl_b {
484             hir::Mutability::Not => AutoBorrowMutability::Not,
485             hir::Mutability::Mut => {
486                 AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase }
487             }
488         };
489         adjustments.push(Adjustment {
490             kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
491             target: ty,
492         });
493
494         debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
495
496         success(adjustments, ty, obligations)
497     }
498
499     // &[T; n] or &mut [T; n] -> &[T]
500     // or &mut [T; n] -> &mut [T]
501     // or &Concrete -> &Trait, etc.
502     fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> {
503         debug!("coerce_unsized(source={:?}, target={:?})", source, target);
504
505         source = self.shallow_resolve(source);
506         target = self.shallow_resolve(target);
507         debug!("coerce_unsized: resolved source={:?} target={:?}", source, target);
508
509         // These 'if' statements require some explanation.
510         // The `CoerceUnsized` trait is special - it is only
511         // possible to write `impl CoerceUnsized<B> for A` where
512         // A and B have 'matching' fields. This rules out the following
513         // two types of blanket impls:
514         //
515         // `impl<T> CoerceUnsized<T> for SomeType`
516         // `impl<T> CoerceUnsized<SomeType> for T`
517         //
518         // Both of these trigger a special `CoerceUnsized`-related error (E0376)
519         //
520         // We can take advantage of this fact to avoid performing unnecessary work.
521         // If either `source` or `target` is a type variable, then any applicable impl
522         // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
523         // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
524         // SomeType`).
525         //
526         // However, these are exactly the kinds of impls which are forbidden by
527         // the compiler! Therefore, we can be sure that coercion will always fail
528         // when either the source or target type is a type variable. This allows us
529         // to skip performing any trait selection, and immediately bail out.
530         if source.is_ty_var() {
531             debug!("coerce_unsized: source is a TyVar, bailing out");
532             return Err(TypeError::Mismatch);
533         }
534         if target.is_ty_var() {
535             debug!("coerce_unsized: target is a TyVar, bailing out");
536             return Err(TypeError::Mismatch);
537         }
538
539         let traits =
540             (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
541         let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
542             (u, cu)
543         } else {
544             debug!("missing Unsize or CoerceUnsized traits");
545             return Err(TypeError::Mismatch);
546         };
547
548         // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
549         // a DST unless we have to. This currently comes out in the wash since
550         // we can't unify [T] with U. But to properly support DST, we need to allow
551         // that, at which point we will need extra checks on the target here.
552
553         // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
554         let reborrow = match (source.kind(), target.kind()) {
555             (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
556                 coerce_mutbls(mutbl_a, mutbl_b)?;
557
558                 let coercion = Coercion(self.cause.span);
559                 let r_borrow = self.next_region_var(coercion);
560                 let mutbl = match mutbl_b {
561                     hir::Mutability::Not => AutoBorrowMutability::Not,
562                     hir::Mutability::Mut => AutoBorrowMutability::Mut {
563                         // We don't allow two-phase borrows here, at least for initial
564                         // implementation. If it happens that this coercion is a function argument,
565                         // the reborrow in coerce_borrowed_ptr will pick it up.
566                         allow_two_phase_borrow: AllowTwoPhase::No,
567                     },
568                 };
569                 Some((
570                     Adjustment { kind: Adjust::Deref(None), target: ty_a },
571                     Adjustment {
572                         kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
573                         target: self
574                             .tcx
575                             .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }),
576                     },
577                 ))
578             }
579             (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
580                 coerce_mutbls(mt_a, mt_b)?;
581
582                 Some((
583                     Adjustment { kind: Adjust::Deref(None), target: ty_a },
584                     Adjustment {
585                         kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
586                         target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
587                     },
588                 ))
589             }
590             _ => None,
591         };
592         let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
593
594         // Setup either a subtyping or a LUB relationship between
595         // the `CoerceUnsized` target type and the expected type.
596         // We only have the latter, so we use an inference variable
597         // for the former and let type inference do the rest.
598         let origin = TypeVariableOrigin {
599             kind: TypeVariableOriginKind::MiscVariable,
600             span: self.cause.span,
601         };
602         let coerce_target = self.next_ty_var(origin);
603         let mut coercion = self.unify_and(coerce_target, target, |target| {
604             let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target };
605             match reborrow {
606                 None => vec![unsize],
607                 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
608             }
609         })?;
610
611         let mut selcx = traits::SelectionContext::new(self);
612
613         // Create an obligation for `Source: CoerceUnsized<Target>`.
614         let cause = ObligationCause::new(
615             self.cause.span,
616             self.body_id,
617             ObligationCauseCode::Coercion { source, target },
618         );
619
620         // Use a FIFO queue for this custom fulfillment procedure.
621         //
622         // A Vec (or SmallVec) is not a natural choice for a queue. However,
623         // this code path is hot, and this queue usually has a max length of 1
624         // and almost never more than 3. By using a SmallVec we avoid an
625         // allocation, at the (very small) cost of (occasionally) having to
626         // shift subsequent elements down when removing the front element.
627         let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def(
628             self.tcx,
629             self.fcx.param_env,
630             cause,
631             coerce_unsized_did,
632             0,
633             coerce_source,
634             &[coerce_target.into()]
635         )];
636
637         let mut has_unsized_tuple_coercion = false;
638         let mut has_trait_upcasting_coercion = false;
639
640         // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
641         // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
642         // inference might unify those two inner type variables later.
643         let traits = [coerce_unsized_did, unsize_did];
644         while !queue.is_empty() {
645             let obligation = queue.remove(0);
646             debug!("coerce_unsized resolve step: {:?}", obligation);
647             let bound_predicate = obligation.predicate.kind();
648             let trait_pred = match bound_predicate.skip_binder() {
649                 ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => {
650                     if unsize_did == trait_pred.def_id() {
651                         let self_ty = trait_pred.self_ty();
652                         let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
653                         if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) =
654                             (self_ty.kind(), unsize_ty.kind())
655                         {
656                             if data_a.principal_def_id() != data_b.principal_def_id() {
657                                 debug!("coerce_unsized: found trait upcasting coercion");
658                                 has_trait_upcasting_coercion = true;
659                             }
660                         }
661                         if let ty::Tuple(..) = unsize_ty.kind() {
662                             debug!("coerce_unsized: found unsized tuple coercion");
663                             has_unsized_tuple_coercion = true;
664                         }
665                     }
666                     bound_predicate.rebind(trait_pred)
667                 }
668                 _ => {
669                     coercion.obligations.push(obligation);
670                     continue;
671                 }
672             };
673             match selcx.select(&obligation.with(trait_pred)) {
674                 // Uncertain or unimplemented.
675                 Ok(None) => {
676                     if trait_pred.def_id() == unsize_did {
677                         let trait_pred = self.resolve_vars_if_possible(trait_pred);
678                         let self_ty = trait_pred.skip_binder().self_ty();
679                         let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty();
680                         debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
681                         match (&self_ty.kind(), &unsize_ty.kind()) {
682                             (ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
683                                 if self.type_var_is_sized(*v) =>
684                             {
685                                 debug!("coerce_unsized: have sized infer {:?}", v);
686                                 coercion.obligations.push(obligation);
687                                 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
688                                 // for unsizing.
689                             }
690                             _ => {
691                                 // Some other case for `$0: Unsize<Something>`. Note that we
692                                 // hit this case even if `Something` is a sized type, so just
693                                 // don't do the coercion.
694                                 debug!("coerce_unsized: ambiguous unsize");
695                                 return Err(TypeError::Mismatch);
696                             }
697                         }
698                     } else {
699                         debug!("coerce_unsized: early return - ambiguous");
700                         return Err(TypeError::Mismatch);
701                     }
702                 }
703                 Err(traits::Unimplemented) => {
704                     debug!("coerce_unsized: early return - can't prove obligation");
705                     return Err(TypeError::Mismatch);
706                 }
707
708                 // Object safety violations or miscellaneous.
709                 Err(err) => {
710                     self.report_selection_error(
711                         obligation.clone(),
712                         &obligation,
713                         &err,
714                         false,
715                         false,
716                     );
717                     // Treat this like an obligation and follow through
718                     // with the unsizing - the lack of a coercion should
719                     // be silent, as it causes a type mismatch later.
720                 }
721
722                 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
723             }
724         }
725
726         if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
727             feature_err(
728                 &self.tcx.sess.parse_sess,
729                 sym::unsized_tuple_coercion,
730                 self.cause.span,
731                 "unsized tuple coercion is not stable enough for use and is subject to change",
732             )
733             .emit();
734         }
735
736         if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting {
737             feature_err(
738                 &self.tcx.sess.parse_sess,
739                 sym::trait_upcasting,
740                 self.cause.span,
741                 "trait upcasting coercion is experimental",
742             )
743             .emit();
744         }
745
746         Ok(coercion)
747     }
748
749     fn coerce_from_safe_fn<F, G>(
750         &self,
751         a: Ty<'tcx>,
752         fn_ty_a: ty::PolyFnSig<'tcx>,
753         b: Ty<'tcx>,
754         to_unsafe: F,
755         normal: G,
756     ) -> CoerceResult<'tcx>
757     where
758         F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
759         G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
760     {
761         if let ty::FnPtr(fn_ty_b) = b.kind() {
762             if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
763                 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
764             {
765                 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
766                 return self.unify_and(unsafe_a, b, to_unsafe);
767             }
768         }
769         self.unify_and(a, b, normal)
770     }
771
772     fn coerce_from_fn_pointer(
773         &self,
774         a: Ty<'tcx>,
775         fn_ty_a: ty::PolyFnSig<'tcx>,
776         b: Ty<'tcx>,
777     ) -> CoerceResult<'tcx> {
778         //! Attempts to coerce from the type of a Rust function item
779         //! into a closure or a `proc`.
780         //!
781
782         let b = self.shallow_resolve(b);
783         debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
784
785         self.coerce_from_safe_fn(
786             a,
787             fn_ty_a,
788             b,
789             simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
790             identity,
791         )
792     }
793
794     fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
795         //! Attempts to coerce from the type of a Rust function item
796         //! into a closure or a `proc`.
797
798         let b = self.shallow_resolve(b);
799         let InferOk { value: b, mut obligations } =
800             self.normalize_associated_types_in_as_infer_ok(self.cause.span, b);
801         debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
802
803         match b.kind() {
804             ty::FnPtr(b_sig) => {
805                 let a_sig = a.fn_sig(self.tcx);
806                 // Intrinsics are not coercible to function pointers
807                 if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic {
808                     return Err(TypeError::IntrinsicCast);
809                 }
810
811                 // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
812                 if let ty::FnDef(def_id, _) = *a.kind() {
813                     if b_sig.unsafety() == hir::Unsafety::Normal
814                         && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
815                     {
816                         return Err(TypeError::TargetFeatureCast(def_id));
817                     }
818                 }
819
820                 let InferOk { value: a_sig, obligations: o1 } =
821                     self.normalize_associated_types_in_as_infer_ok(self.cause.span, a_sig);
822                 obligations.extend(o1);
823
824                 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
825                 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
826                     a_fn_pointer,
827                     a_sig,
828                     b,
829                     |unsafe_ty| {
830                         vec![
831                             Adjustment {
832                                 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
833                                 target: a_fn_pointer,
834                             },
835                             Adjustment {
836                                 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
837                                 target: unsafe_ty,
838                             },
839                         ]
840                     },
841                     simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
842                 )?;
843
844                 obligations.extend(o2);
845                 Ok(InferOk { value, obligations })
846             }
847             _ => self.unify_and(a, b, identity),
848         }
849     }
850
851     fn coerce_closure_to_fn(
852         &self,
853         a: Ty<'tcx>,
854         closure_def_id_a: DefId,
855         substs_a: SubstsRef<'tcx>,
856         b: Ty<'tcx>,
857     ) -> CoerceResult<'tcx> {
858         //! Attempts to coerce from the type of a non-capturing closure
859         //! into a function pointer.
860         //!
861
862         let b = self.shallow_resolve(b);
863
864         match b.kind() {
865             // At this point we haven't done capture analysis, which means
866             // that the ClosureSubsts just contains an inference variable instead
867             // of tuple of captured types.
868             //
869             // All we care here is if any variable is being captured and not the exact paths,
870             // so we check `upvars_mentioned` for root variables being captured.
871             ty::FnPtr(fn_ty)
872                 if self
873                     .tcx
874                     .upvars_mentioned(closure_def_id_a.expect_local())
875                     .map_or(true, |u| u.is_empty()) =>
876             {
877                 // We coerce the closure, which has fn type
878                 //     `extern "rust-call" fn((arg0,arg1,...)) -> _`
879                 // to
880                 //     `fn(arg0,arg1,...) -> _`
881                 // or
882                 //     `unsafe fn(arg0,arg1,...) -> _`
883                 let closure_sig = substs_a.as_closure().sig();
884                 let unsafety = fn_ty.unsafety();
885                 let pointer_ty =
886                     self.tcx.mk_fn_ptr(self.tcx.signature_unclosure(closure_sig, unsafety));
887                 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
888                 self.unify_and(
889                     pointer_ty,
890                     b,
891                     simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
892                 )
893             }
894             _ => self.unify_and(a, b, identity),
895         }
896     }
897
898     fn coerce_unsafe_ptr(
899         &self,
900         a: Ty<'tcx>,
901         b: Ty<'tcx>,
902         mutbl_b: hir::Mutability,
903     ) -> CoerceResult<'tcx> {
904         debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
905
906         let (is_ref, mt_a) = match *a.kind() {
907             ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
908             ty::RawPtr(mt) => (false, mt),
909             _ => return self.unify_and(a, b, identity),
910         };
911         coerce_mutbls(mt_a.mutbl, mutbl_b)?;
912
913         // Check that the types which they point at are compatible.
914         let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
915         // Although references and unsafe ptrs have the same
916         // representation, we still register an Adjust::DerefRef so that
917         // regionck knows that the region for `a` must be valid here.
918         if is_ref {
919             self.unify_and(a_unsafe, b, |target| {
920                 vec![
921                     Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
922                     Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
923                 ]
924             })
925         } else if mt_a.mutbl != mutbl_b {
926             self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
927         } else {
928             self.unify_and(a_unsafe, b, identity)
929         }
930     }
931 }
932
933 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
934     /// Attempt to coerce an expression to a type, and return the
935     /// adjusted type of the expression, if successful.
936     /// Adjustments are only recorded if the coercion succeeded.
937     /// The expressions *must not* have any pre-existing adjustments.
938     pub fn try_coerce(
939         &self,
940         expr: &hir::Expr<'_>,
941         expr_ty: Ty<'tcx>,
942         target: Ty<'tcx>,
943         allow_two_phase: AllowTwoPhase,
944     ) -> RelateResult<'tcx, Ty<'tcx>> {
945         let source = self.resolve_vars_with_obligations(expr_ty);
946         debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
947
948         let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
949         let coerce = Coerce::new(self, cause, allow_two_phase);
950         let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
951
952         let (adjustments, _) = self.register_infer_ok_obligations(ok);
953         self.apply_adjustments(expr, adjustments);
954         Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target })
955     }
956
957     /// Same as `try_coerce()`, but without side-effects.
958     pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
959         let source = self.resolve_vars_with_obligations(expr_ty);
960         debug!("coercion::can({:?} -> {:?})", source, target);
961
962         let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
963         // We don't ever need two-phase here since we throw out the result of the coercion
964         let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
965         self.probe(|_| coerce.coerce(source, target)).is_ok()
966     }
967
968     /// Given a type and a target type, this function will calculate and return
969     /// how many dereference steps needed to achieve `expr_ty <: target`. If
970     /// it's not possible, return `None`.
971     pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
972         let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
973         // We don't ever need two-phase here since we throw out the result of the coercion
974         let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
975         coerce
976             .autoderef(rustc_span::DUMMY_SP, expr_ty)
977             .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
978     }
979
980     /// Given some expressions, their known unified type and another expression,
981     /// tries to unify the types, potentially inserting coercions on any of the
982     /// provided expressions and returns their LUB (aka "common supertype").
983     ///
984     /// This is really an internal helper. From outside the coercion
985     /// module, you should instantiate a `CoerceMany` instance.
986     fn try_find_coercion_lub<E>(
987         &self,
988         cause: &ObligationCause<'tcx>,
989         exprs: &[E],
990         prev_ty: Ty<'tcx>,
991         new: &hir::Expr<'_>,
992         new_ty: Ty<'tcx>,
993     ) -> RelateResult<'tcx, Ty<'tcx>>
994     where
995         E: AsCoercionSite,
996     {
997         let prev_ty = self.resolve_vars_with_obligations(prev_ty);
998         let new_ty = self.resolve_vars_with_obligations(new_ty);
999         debug!(
1000             "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1001             prev_ty,
1002             new_ty,
1003             exprs.len()
1004         );
1005
1006         // The following check fixes #88097, where the compiler erroneously
1007         // attempted to coerce a closure type to itself via a function pointer.
1008         if prev_ty == new_ty {
1009             return Ok(prev_ty);
1010         }
1011
1012         // Special-case that coercion alone cannot handle:
1013         // Function items or non-capturing closures of differing IDs or InternalSubsts.
1014         let (a_sig, b_sig) = {
1015             let is_capturing_closure = |ty| {
1016                 if let &ty::Closure(closure_def_id, _substs) = ty {
1017                     self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
1018                 } else {
1019                     false
1020                 }
1021             };
1022             if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) {
1023                 (None, None)
1024             } else {
1025                 match (prev_ty.kind(), new_ty.kind()) {
1026                     (ty::FnDef(..), ty::FnDef(..)) => {
1027                         // Don't reify if the function types have a LUB, i.e., they
1028                         // are the same function and their parameters have a LUB.
1029                         match self
1030                             .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1031                         {
1032                             // We have a LUB of prev_ty and new_ty, just return it.
1033                             Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1034                             Err(_) => {
1035                                 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
1036                             }
1037                         }
1038                     }
1039                     (ty::Closure(_, substs), ty::FnDef(..)) => {
1040                         let b_sig = new_ty.fn_sig(self.tcx);
1041                         let a_sig = self
1042                             .tcx
1043                             .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
1044                         (Some(a_sig), Some(b_sig))
1045                     }
1046                     (ty::FnDef(..), ty::Closure(_, substs)) => {
1047                         let a_sig = prev_ty.fn_sig(self.tcx);
1048                         let b_sig = self
1049                             .tcx
1050                             .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
1051                         (Some(a_sig), Some(b_sig))
1052                     }
1053                     (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => (
1054                         Some(self.tcx.signature_unclosure(
1055                             substs_a.as_closure().sig(),
1056                             hir::Unsafety::Normal,
1057                         )),
1058                         Some(self.tcx.signature_unclosure(
1059                             substs_b.as_closure().sig(),
1060                             hir::Unsafety::Normal,
1061                         )),
1062                     ),
1063                     _ => (None, None),
1064                 }
1065             }
1066         };
1067         if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
1068             // Intrinsics are not coercible to function pointers.
1069             if a_sig.abi() == Abi::RustIntrinsic
1070                 || a_sig.abi() == Abi::PlatformIntrinsic
1071                 || b_sig.abi() == Abi::RustIntrinsic
1072                 || b_sig.abi() == Abi::PlatformIntrinsic
1073             {
1074                 return Err(TypeError::IntrinsicCast);
1075             }
1076             // The signature must match.
1077             let a_sig = self.normalize_associated_types_in(new.span, a_sig);
1078             let b_sig = self.normalize_associated_types_in(new.span, b_sig);
1079             let sig = self
1080                 .at(cause, self.param_env)
1081                 .trace(prev_ty, new_ty)
1082                 .lub(a_sig, b_sig)
1083                 .map(|ok| self.register_infer_ok_obligations(ok))?;
1084
1085             // Reify both sides and return the reified fn pointer type.
1086             let fn_ptr = self.tcx.mk_fn_ptr(sig);
1087             let prev_adjustment = match prev_ty.kind() {
1088                 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.unsafety())),
1089                 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1090                 _ => unreachable!(),
1091             };
1092             let next_adjustment = match new_ty.kind() {
1093                 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.unsafety())),
1094                 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1095                 _ => unreachable!(),
1096             };
1097             for expr in exprs.iter().map(|e| e.as_coercion_site()) {
1098                 self.apply_adjustments(
1099                     expr,
1100                     vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1101                 );
1102             }
1103             self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1104             return Ok(fn_ptr);
1105         }
1106
1107         // Configure a Coerce instance to compute the LUB.
1108         // We don't allow two-phase borrows on any autorefs this creates since we
1109         // probably aren't processing function arguments here and even if we were,
1110         // they're going to get autorefed again anyway and we can apply 2-phase borrows
1111         // at that time.
1112         let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
1113         coerce.use_lub = true;
1114
1115         // First try to coerce the new expression to the type of the previous ones,
1116         // but only if the new expression has no coercion already applied to it.
1117         let mut first_error = None;
1118         if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1119             let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1120             match result {
1121                 Ok(ok) => {
1122                     let (adjustments, target) = self.register_infer_ok_obligations(ok);
1123                     self.apply_adjustments(new, adjustments);
1124                     debug!(
1125                         "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}",
1126                         prev_ty, new_ty,
1127                     );
1128                     return Ok(target);
1129                 }
1130                 Err(e) => first_error = Some(e),
1131             }
1132         }
1133
1134         // Then try to coerce the previous expressions to the type of the new one.
1135         // This requires ensuring there are no coercions applied to *any* of the
1136         // previous expressions, other than noop reborrows (ignoring lifetimes).
1137         for expr in exprs {
1138             let expr = expr.as_coercion_site();
1139             let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
1140                 &[Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }] =>
1141                 {
1142                     match *self.node_ty(expr.hir_id).kind() {
1143                         ty::Ref(_, _, mt_orig) => {
1144                             let mutbl_adj: hir::Mutability = mutbl_adj.into();
1145                             // Reborrow that we can safely ignore, because
1146                             // the next adjustment can only be a Deref
1147                             // which will be merged into it.
1148                             mutbl_adj == mt_orig
1149                         }
1150                         _ => false,
1151                     }
1152                 }
1153                 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1154                 _ => false,
1155             };
1156
1157             if !noop {
1158                 debug!(
1159                     "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1160                     expr,
1161                 );
1162
1163                 return self
1164                     .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1165                     .map(|ok| self.register_infer_ok_obligations(ok));
1166             }
1167         }
1168
1169         match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1170             Err(_) => {
1171                 // Avoid giving strange errors on failed attempts.
1172                 if let Some(e) = first_error {
1173                     Err(e)
1174                 } else {
1175                     self.commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1176                         .map(|ok| self.register_infer_ok_obligations(ok))
1177                 }
1178             }
1179             Ok(ok) => {
1180                 debug!(
1181                     "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?}",
1182                     prev_ty, new_ty,
1183                 );
1184                 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1185                 for expr in exprs {
1186                     let expr = expr.as_coercion_site();
1187                     self.apply_adjustments(expr, adjustments.clone());
1188                 }
1189                 Ok(target)
1190             }
1191         }
1192     }
1193 }
1194
1195 /// CoerceMany encapsulates the pattern you should use when you have
1196 /// many expressions that are all getting coerced to a common
1197 /// type. This arises, for example, when you have a match (the result
1198 /// of each arm is coerced to a common type). It also arises in less
1199 /// obvious places, such as when you have many `break foo` expressions
1200 /// that target the same loop, or the various `return` expressions in
1201 /// a function.
1202 ///
1203 /// The basic protocol is as follows:
1204 ///
1205 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1206 ///   This will also serve as the "starting LUB". The expectation is
1207 ///   that this type is something which all of the expressions *must*
1208 ///   be coercible to. Use a fresh type variable if needed.
1209 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1210 ///   - In some cases we wish to coerce "non-expressions" whose types are implicitly
1211 ///     unit. This happens for example if you have a `break` with no expression,
1212 ///     or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1213 ///   - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1214 ///     from you so that you don't have to worry your pretty head about it.
1215 ///     But if an error is reported, the final type will be `err`.
1216 ///   - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1217 ///     previously coerced expressions.
1218 /// - When all done, invoke `complete()`. This will return the LUB of
1219 ///   all your expressions.
1220 ///   - WARNING: I don't believe this final type is guaranteed to be
1221 ///     related to your initial `expected_ty` in any particular way,
1222 ///     although it will typically be a subtype, so you should check it.
1223 ///   - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1224 ///     previously coerced expressions.
1225 ///
1226 /// Example:
1227 ///
1228 /// ```
1229 /// let mut coerce = CoerceMany::new(expected_ty);
1230 /// for expr in exprs {
1231 ///     let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1232 ///     coerce.coerce(fcx, &cause, expr, expr_ty);
1233 /// }
1234 /// let final_ty = coerce.complete(fcx);
1235 /// ```
1236 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1237     expected_ty: Ty<'tcx>,
1238     final_ty: Option<Ty<'tcx>>,
1239     expressions: Expressions<'tcx, 'exprs, E>,
1240     pushed: usize,
1241 }
1242
1243 /// The type of a `CoerceMany` that is storing up the expressions into
1244 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1245 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1246
1247 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1248     Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1249     UpFront(&'exprs [E]),
1250 }
1251
1252 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1253     /// The usual case; collect the set of expressions dynamically.
1254     /// If the full set of coercion sites is known before hand,
1255     /// consider `with_coercion_sites()` instead to avoid allocation.
1256     pub fn new(expected_ty: Ty<'tcx>) -> Self {
1257         Self::make(expected_ty, Expressions::Dynamic(vec![]))
1258     }
1259
1260     /// As an optimization, you can create a `CoerceMany` with a
1261     /// pre-existing slice of expressions. In this case, you are
1262     /// expected to pass each element in the slice to `coerce(...)` in
1263     /// order. This is used with arrays in particular to avoid
1264     /// needlessly cloning the slice.
1265     pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1266         Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1267     }
1268
1269     fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1270         CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1271     }
1272
1273     /// Returns the "expected type" with which this coercion was
1274     /// constructed. This represents the "downward propagated" type
1275     /// that was given to us at the start of typing whatever construct
1276     /// we are typing (e.g., the match expression).
1277     ///
1278     /// Typically, this is used as the expected type when
1279     /// type-checking each of the alternative expressions whose types
1280     /// we are trying to merge.
1281     pub fn expected_ty(&self) -> Ty<'tcx> {
1282         self.expected_ty
1283     }
1284
1285     /// Returns the current "merged type", representing our best-guess
1286     /// at the LUB of the expressions we've seen so far (if any). This
1287     /// isn't *final* until you call `self.final()`, which will return
1288     /// the merged type.
1289     pub fn merged_ty(&self) -> Ty<'tcx> {
1290         self.final_ty.unwrap_or(self.expected_ty)
1291     }
1292
1293     /// Indicates that the value generated by `expression`, which is
1294     /// of type `expression_ty`, is one of the possibilities that we
1295     /// could coerce from. This will record `expression`, and later
1296     /// calls to `coerce` may come back and add adjustments and things
1297     /// if necessary.
1298     pub fn coerce<'a>(
1299         &mut self,
1300         fcx: &FnCtxt<'a, 'tcx>,
1301         cause: &ObligationCause<'tcx>,
1302         expression: &'tcx hir::Expr<'tcx>,
1303         expression_ty: Ty<'tcx>,
1304     ) {
1305         self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1306     }
1307
1308     /// Indicates that one of the inputs is a "forced unit". This
1309     /// occurs in a case like `if foo { ... };`, where the missing else
1310     /// generates a "forced unit". Another example is a `loop { break;
1311     /// }`, where the `break` has no argument expression. We treat
1312     /// these cases slightly differently for error-reporting
1313     /// purposes. Note that these tend to correspond to cases where
1314     /// the `()` expression is implicit in the source, and hence we do
1315     /// not take an expression argument.
1316     ///
1317     /// The `augment_error` gives you a chance to extend the error
1318     /// message, in case any results (e.g., we use this to suggest
1319     /// removing a `;`).
1320     pub fn coerce_forced_unit<'a>(
1321         &mut self,
1322         fcx: &FnCtxt<'a, 'tcx>,
1323         cause: &ObligationCause<'tcx>,
1324         augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1325         label_unit_as_expected: bool,
1326     ) {
1327         self.coerce_inner(
1328             fcx,
1329             cause,
1330             None,
1331             fcx.tcx.mk_unit(),
1332             Some(augment_error),
1333             label_unit_as_expected,
1334         )
1335     }
1336
1337     /// The inner coercion "engine". If `expression` is `None`, this
1338     /// is a forced-unit case, and hence `expression_ty` must be
1339     /// `Nil`.
1340     #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1341     crate fn coerce_inner<'a>(
1342         &mut self,
1343         fcx: &FnCtxt<'a, 'tcx>,
1344         cause: &ObligationCause<'tcx>,
1345         expression: Option<&'tcx hir::Expr<'tcx>>,
1346         mut expression_ty: Ty<'tcx>,
1347         augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1348         label_expression_as_expected: bool,
1349     ) {
1350         // Incorporate whatever type inference information we have
1351         // until now; in principle we might also want to process
1352         // pending obligations, but doing so should only improve
1353         // compatibility (hopefully that is true) by helping us
1354         // uncover never types better.
1355         if expression_ty.is_ty_var() {
1356             expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1357         }
1358
1359         // If we see any error types, just propagate that error
1360         // upwards.
1361         if expression_ty.references_error() || self.merged_ty().references_error() {
1362             self.final_ty = Some(fcx.tcx.ty_error());
1363             return;
1364         }
1365
1366         // Handle the actual type unification etc.
1367         let result = if let Some(expression) = expression {
1368             if self.pushed == 0 {
1369                 // Special-case the first expression we are coercing.
1370                 // To be honest, I'm not entirely sure why we do this.
1371                 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1372                 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1373             } else {
1374                 match self.expressions {
1375                     Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1376                         cause,
1377                         exprs,
1378                         self.merged_ty(),
1379                         expression,
1380                         expression_ty,
1381                     ),
1382                     Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1383                         cause,
1384                         &coercion_sites[0..self.pushed],
1385                         self.merged_ty(),
1386                         expression,
1387                         expression_ty,
1388                     ),
1389                 }
1390             }
1391         } else {
1392             // this is a hack for cases where we default to `()` because
1393             // the expression etc has been omitted from the source. An
1394             // example is an `if let` without an else:
1395             //
1396             //     if let Some(x) = ... { }
1397             //
1398             // we wind up with a second match arm that is like `_ =>
1399             // ()`.  That is the case we are considering here. We take
1400             // a different path to get the right "expected, found"
1401             // message and so forth (and because we know that
1402             // `expression_ty` will be unit).
1403             //
1404             // Another example is `break` with no argument expression.
1405             assert!(expression_ty.is_unit(), "if let hack without unit type");
1406             fcx.at(cause, fcx.param_env)
1407                 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1408                 .map(|infer_ok| {
1409                     fcx.register_infer_ok_obligations(infer_ok);
1410                     expression_ty
1411                 })
1412         };
1413
1414         match result {
1415             Ok(v) => {
1416                 self.final_ty = Some(v);
1417                 if let Some(e) = expression {
1418                     match self.expressions {
1419                         Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1420                         Expressions::UpFront(coercion_sites) => {
1421                             // if the user gave us an array to validate, check that we got
1422                             // the next expression in the list, as expected
1423                             assert_eq!(
1424                                 coercion_sites[self.pushed].as_coercion_site().hir_id,
1425                                 e.hir_id
1426                             );
1427                         }
1428                     }
1429                     self.pushed += 1;
1430                 }
1431             }
1432             Err(coercion_error) => {
1433                 let (expected, found) = if label_expression_as_expected {
1434                     // In the case where this is a "forced unit", like
1435                     // `break`, we want to call the `()` "expected"
1436                     // since it is implied by the syntax.
1437                     // (Note: not all force-units work this way.)"
1438                     (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1439                 } else {
1440                     // Otherwise, the "expected" type for error
1441                     // reporting is the current unification type,
1442                     // which is basically the LUB of the expressions
1443                     // we've seen so far (combined with the expected
1444                     // type)
1445                     (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1446                 };
1447
1448                 let mut err;
1449                 let mut unsized_return = false;
1450                 match cause.code {
1451                     ObligationCauseCode::ReturnNoExpression => {
1452                         err = struct_span_err!(
1453                             fcx.tcx.sess,
1454                             cause.span,
1455                             E0069,
1456                             "`return;` in a function whose return type is not `()`"
1457                         );
1458                         err.span_label(cause.span, "return type is not `()`");
1459                     }
1460                     ObligationCauseCode::BlockTailExpression(blk_id) => {
1461                         let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1462                         err = self.report_return_mismatched_types(
1463                             cause,
1464                             expected,
1465                             found,
1466                             coercion_error,
1467                             fcx,
1468                             parent_id,
1469                             expression.map(|expr| (expr, blk_id)),
1470                         );
1471                         if !fcx.tcx.features().unsized_locals {
1472                             unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1473                         }
1474                     }
1475                     ObligationCauseCode::ReturnValue(id) => {
1476                         err = self.report_return_mismatched_types(
1477                             cause,
1478                             expected,
1479                             found,
1480                             coercion_error,
1481                             fcx,
1482                             id,
1483                             None,
1484                         );
1485                         if !fcx.tcx.features().unsized_locals {
1486                             let id = fcx.tcx.hir().get_parent_node(id);
1487                             unsized_return = self.is_return_ty_unsized(fcx, id);
1488                         }
1489                     }
1490                     _ => {
1491                         err = fcx.report_mismatched_types(cause, expected, found, coercion_error);
1492                     }
1493                 }
1494
1495                 if let Some(augment_error) = augment_error {
1496                     augment_error(&mut err);
1497                 }
1498
1499                 if let Some(expr) = expression {
1500                     fcx.emit_coerce_suggestions(&mut err, expr, found, expected, None);
1501                 }
1502
1503                 // Error possibly reported in `check_assign` so avoid emitting error again.
1504                 let assign_to_bool = expression
1505                     // #67273: Use initial expected type as opposed to `expected`.
1506                     // Otherwise we end up using prior coercions in e.g. a `match` expression:
1507                     // ```
1508                     // match i {
1509                     //     0 => true, // Because of this...
1510                     //     1 => i = 1, // ...`expected == bool` now, but not when checking `i = 1`.
1511                     //     _ => (),
1512                     // };
1513                     // ```
1514                     .filter(|e| fcx.is_assign_to_bool(e, self.expected_ty()))
1515                     .is_some();
1516
1517                 err.emit_unless(assign_to_bool || unsized_return);
1518
1519                 self.final_ty = Some(fcx.tcx.ty_error());
1520             }
1521         }
1522     }
1523
1524     fn report_return_mismatched_types<'a>(
1525         &self,
1526         cause: &ObligationCause<'tcx>,
1527         expected: Ty<'tcx>,
1528         found: Ty<'tcx>,
1529         ty_err: TypeError<'tcx>,
1530         fcx: &FnCtxt<'a, 'tcx>,
1531         id: hir::HirId,
1532         expression: Option<(&'tcx hir::Expr<'tcx>, hir::HirId)>,
1533     ) -> DiagnosticBuilder<'a> {
1534         let mut err = fcx.report_mismatched_types(cause, expected, found, ty_err);
1535
1536         let mut pointing_at_return_type = false;
1537         let mut fn_output = None;
1538
1539         // Verify that this is a tail expression of a function, otherwise the
1540         // label pointing out the cause for the type coercion will be wrong
1541         // as prior return coercions would not be relevant (#57664).
1542         let parent_id = fcx.tcx.hir().get_parent_node(id);
1543         let fn_decl = if let Some((expr, blk_id)) = expression {
1544             pointing_at_return_type =
1545                 fcx.suggest_mismatched_types_on_tail(&mut err, expr, expected, found, blk_id);
1546             let parent = fcx.tcx.hir().get(parent_id);
1547             if let (Some(cond_expr), true, false) = (
1548                 fcx.tcx.hir().get_if_cause(expr.hir_id),
1549                 expected.is_unit(),
1550                 pointing_at_return_type,
1551             ) {
1552                 // If the block is from an external macro or try (`?`) desugaring, then
1553                 // do not suggest adding a semicolon, because there's nowhere to put it.
1554                 // See issues #81943 and #87051.
1555                 if cond_expr.span.desugaring_kind().is_none()
1556                     && !in_external_macro(fcx.tcx.sess, cond_expr.span)
1557                     && !matches!(
1558                         cond_expr.kind,
1559                         hir::ExprKind::Match(.., hir::MatchSource::TryDesugar)
1560                     )
1561                 {
1562                     err.span_label(cond_expr.span, "expected this to be `()`");
1563                     if expr.can_have_side_effects() {
1564                         fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1565                     }
1566                 }
1567             }
1568             fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1569         } else {
1570             fcx.get_fn_decl(parent_id)
1571         };
1572
1573         if let Some((fn_decl, can_suggest)) = fn_decl {
1574             if expression.is_none() {
1575                 pointing_at_return_type |= fcx.suggest_missing_return_type(
1576                     &mut err,
1577                     &fn_decl,
1578                     expected,
1579                     found,
1580                     can_suggest,
1581                     fcx.tcx.hir().get_parent_item(id),
1582                 );
1583             }
1584             if !pointing_at_return_type {
1585                 fn_output = Some(&fn_decl.output); // `impl Trait` return type
1586             }
1587         }
1588
1589         let parent_id = fcx.tcx.hir().get_parent_item(id);
1590         let parent_item = fcx.tcx.hir().get(parent_id);
1591
1592         if let (Some((expr, _)), Some((fn_decl, _, _))) =
1593             (expression, fcx.get_node_fn_decl(parent_item))
1594         {
1595             fcx.suggest_missing_break_or_return_expr(
1596                 &mut err, expr, fn_decl, expected, found, id, parent_id,
1597             );
1598         }
1599
1600         if let (Some(sp), Some(fn_output)) = (fcx.ret_coercion_span.get(), fn_output) {
1601             self.add_impl_trait_explanation(&mut err, cause, fcx, expected, sp, fn_output);
1602         }
1603         err
1604     }
1605
1606     fn add_impl_trait_explanation<'a>(
1607         &self,
1608         err: &mut DiagnosticBuilder<'a>,
1609         cause: &ObligationCause<'tcx>,
1610         fcx: &FnCtxt<'a, 'tcx>,
1611         expected: Ty<'tcx>,
1612         sp: Span,
1613         fn_output: &hir::FnRetTy<'_>,
1614     ) {
1615         let return_sp = fn_output.span();
1616         err.span_label(return_sp, "expected because this return type...");
1617         err.span_label(
1618             sp,
1619             format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1620         );
1621         let impl_trait_msg = "for information on `impl Trait`, see \
1622                 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1623                 #returning-types-that-implement-traits>";
1624         let trait_obj_msg = "for information on trait objects, see \
1625                 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1626                 #using-trait-objects-that-allow-for-values-of-different-types>";
1627         err.note("to return `impl Trait`, all returned values must be of the same type");
1628         err.note(impl_trait_msg);
1629         let snippet = fcx
1630             .tcx
1631             .sess
1632             .source_map()
1633             .span_to_snippet(return_sp)
1634             .unwrap_or_else(|_| "dyn Trait".to_string());
1635         let mut snippet_iter = snippet.split_whitespace();
1636         let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1637         // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1638         let mut is_object_safe = false;
1639         if let hir::FnRetTy::Return(ty) = fn_output {
1640             // Get the return type.
1641             if let hir::TyKind::OpaqueDef(..) = ty.kind {
1642                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1643                 // Get the `impl Trait`'s `DefId`.
1644                 if let ty::Opaque(def_id, _) = ty.kind() {
1645                     let hir_id = fcx.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1646                     // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1647                     // get the `Trait`'s `DefId`.
1648                     if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1649                         fcx.tcx.hir().expect_item(hir_id).kind
1650                     {
1651                         // Are of this `impl Trait`'s traits object safe?
1652                         is_object_safe = bounds.iter().all(|bound| {
1653                             bound
1654                                 .trait_ref()
1655                                 .and_then(|t| t.trait_def_id())
1656                                 .map_or(false, |def_id| {
1657                                     fcx.tcx.object_safety_violations(def_id).is_empty()
1658                                 })
1659                         })
1660                     }
1661                 }
1662             }
1663         };
1664         if has_impl {
1665             if is_object_safe {
1666                 err.multipart_suggestion(
1667                     "you could change the return type to be a boxed trait object",
1668                     vec![
1669                         (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
1670                         (return_sp.shrink_to_hi(), ">".to_string()),
1671                     ],
1672                     Applicability::MachineApplicable,
1673                 );
1674                 let sugg = vec![sp, cause.span]
1675                     .into_iter()
1676                     .flat_map(|sp| {
1677                         vec![
1678                             (sp.shrink_to_lo(), "Box::new(".to_string()),
1679                             (sp.shrink_to_hi(), ")".to_string()),
1680                         ]
1681                         .into_iter()
1682                     })
1683                     .collect::<Vec<_>>();
1684                 err.multipart_suggestion(
1685                     "if you change the return type to expect trait objects, box the returned \
1686                      expressions",
1687                     sugg,
1688                     Applicability::MaybeIncorrect,
1689                 );
1690             } else {
1691                 err.help(&format!(
1692                     "if the trait `{}` were object safe, you could return a boxed trait object",
1693                     &snippet[5..]
1694                 ));
1695             }
1696             err.note(trait_obj_msg);
1697         }
1698         err.help("you could instead create a new `enum` with a variant for each returned type");
1699     }
1700
1701     fn is_return_ty_unsized(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
1702         if let Some((fn_decl, _)) = fcx.get_fn_decl(blk_id) {
1703             if let hir::FnRetTy::Return(ty) = fn_decl.output {
1704                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1705                 if let ty::Dynamic(..) = ty.kind() {
1706                     return true;
1707                 }
1708             }
1709         }
1710         false
1711     }
1712
1713     pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1714         if let Some(final_ty) = self.final_ty {
1715             final_ty
1716         } else {
1717             // If we only had inputs that were of type `!` (or no
1718             // inputs at all), then the final type is `!`.
1719             assert_eq!(self.pushed, 0);
1720             fcx.tcx.types.never
1721         }
1722     }
1723 }
1724
1725 /// Something that can be converted into an expression to which we can
1726 /// apply a coercion.
1727 pub trait AsCoercionSite {
1728     fn as_coercion_site(&self) -> &hir::Expr<'_>;
1729 }
1730
1731 impl AsCoercionSite for hir::Expr<'_> {
1732     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1733         self
1734     }
1735 }
1736
1737 impl<'a, T> AsCoercionSite for &'a T
1738 where
1739     T: AsCoercionSite,
1740 {
1741     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1742         (**self).as_coercion_site()
1743     }
1744 }
1745
1746 impl AsCoercionSite for ! {
1747     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1748         unreachable!()
1749     }
1750 }
1751
1752 impl AsCoercionSite for hir::Arm<'_> {
1753     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1754         &self.body
1755     }
1756 }