]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/coercion.rs
Rollup merge of #88339 - piegamesde:master, r=joshtriplett
[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(obligation.clone(), &obligation, &err, false);
711                     // Treat this like an obligation and follow through
712                     // with the unsizing - the lack of a coercion should
713                     // be silent, as it causes a type mismatch later.
714                 }
715
716                 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
717             }
718         }
719
720         if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
721             feature_err(
722                 &self.tcx.sess.parse_sess,
723                 sym::unsized_tuple_coercion,
724                 self.cause.span,
725                 "unsized tuple coercion is not stable enough for use and is subject to change",
726             )
727             .emit();
728         }
729
730         if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting {
731             feature_err(
732                 &self.tcx.sess.parse_sess,
733                 sym::trait_upcasting,
734                 self.cause.span,
735                 "trait upcasting coercion is experimental",
736             )
737             .emit();
738         }
739
740         Ok(coercion)
741     }
742
743     fn coerce_from_safe_fn<F, G>(
744         &self,
745         a: Ty<'tcx>,
746         fn_ty_a: ty::PolyFnSig<'tcx>,
747         b: Ty<'tcx>,
748         to_unsafe: F,
749         normal: G,
750     ) -> CoerceResult<'tcx>
751     where
752         F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
753         G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
754     {
755         if let ty::FnPtr(fn_ty_b) = b.kind() {
756             if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
757                 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
758             {
759                 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
760                 return self.unify_and(unsafe_a, b, to_unsafe);
761             }
762         }
763         self.unify_and(a, b, normal)
764     }
765
766     fn coerce_from_fn_pointer(
767         &self,
768         a: Ty<'tcx>,
769         fn_ty_a: ty::PolyFnSig<'tcx>,
770         b: Ty<'tcx>,
771     ) -> CoerceResult<'tcx> {
772         //! Attempts to coerce from the type of a Rust function item
773         //! into a closure or a `proc`.
774         //!
775
776         let b = self.shallow_resolve(b);
777         debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
778
779         self.coerce_from_safe_fn(
780             a,
781             fn_ty_a,
782             b,
783             simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
784             identity,
785         )
786     }
787
788     fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
789         //! Attempts to coerce from the type of a Rust function item
790         //! into a closure or a `proc`.
791
792         let b = self.shallow_resolve(b);
793         let InferOk { value: b, mut obligations } =
794             self.normalize_associated_types_in_as_infer_ok(self.cause.span, b);
795         debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
796
797         match b.kind() {
798             ty::FnPtr(b_sig) => {
799                 let a_sig = a.fn_sig(self.tcx);
800                 // Intrinsics are not coercible to function pointers
801                 if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic {
802                     return Err(TypeError::IntrinsicCast);
803                 }
804
805                 // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
806                 if let ty::FnDef(def_id, _) = *a.kind() {
807                     if b_sig.unsafety() == hir::Unsafety::Normal
808                         && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
809                     {
810                         return Err(TypeError::TargetFeatureCast(def_id));
811                     }
812                 }
813
814                 let InferOk { value: a_sig, obligations: o1 } =
815                     self.normalize_associated_types_in_as_infer_ok(self.cause.span, a_sig);
816                 obligations.extend(o1);
817
818                 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
819                 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
820                     a_fn_pointer,
821                     a_sig,
822                     b,
823                     |unsafe_ty| {
824                         vec![
825                             Adjustment {
826                                 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
827                                 target: a_fn_pointer,
828                             },
829                             Adjustment {
830                                 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
831                                 target: unsafe_ty,
832                             },
833                         ]
834                     },
835                     simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
836                 )?;
837
838                 obligations.extend(o2);
839                 Ok(InferOk { value, obligations })
840             }
841             _ => self.unify_and(a, b, identity),
842         }
843     }
844
845     fn coerce_closure_to_fn(
846         &self,
847         a: Ty<'tcx>,
848         closure_def_id_a: DefId,
849         substs_a: SubstsRef<'tcx>,
850         b: Ty<'tcx>,
851     ) -> CoerceResult<'tcx> {
852         //! Attempts to coerce from the type of a non-capturing closure
853         //! into a function pointer.
854         //!
855
856         let b = self.shallow_resolve(b);
857
858         match b.kind() {
859             // At this point we haven't done capture analysis, which means
860             // that the ClosureSubsts just contains an inference variable instead
861             // of tuple of captured types.
862             //
863             // All we care here is if any variable is being captured and not the exact paths,
864             // so we check `upvars_mentioned` for root variables being captured.
865             ty::FnPtr(fn_ty)
866                 if self
867                     .tcx
868                     .upvars_mentioned(closure_def_id_a.expect_local())
869                     .map_or(true, |u| u.is_empty()) =>
870             {
871                 // We coerce the closure, which has fn type
872                 //     `extern "rust-call" fn((arg0,arg1,...)) -> _`
873                 // to
874                 //     `fn(arg0,arg1,...) -> _`
875                 // or
876                 //     `unsafe fn(arg0,arg1,...) -> _`
877                 let closure_sig = substs_a.as_closure().sig();
878                 let unsafety = fn_ty.unsafety();
879                 let pointer_ty =
880                     self.tcx.mk_fn_ptr(self.tcx.signature_unclosure(closure_sig, unsafety));
881                 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
882                 self.unify_and(
883                     pointer_ty,
884                     b,
885                     simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
886                 )
887             }
888             _ => self.unify_and(a, b, identity),
889         }
890     }
891
892     fn coerce_unsafe_ptr(
893         &self,
894         a: Ty<'tcx>,
895         b: Ty<'tcx>,
896         mutbl_b: hir::Mutability,
897     ) -> CoerceResult<'tcx> {
898         debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
899
900         let (is_ref, mt_a) = match *a.kind() {
901             ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
902             ty::RawPtr(mt) => (false, mt),
903             _ => return self.unify_and(a, b, identity),
904         };
905         coerce_mutbls(mt_a.mutbl, mutbl_b)?;
906
907         // Check that the types which they point at are compatible.
908         let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
909         // Although references and unsafe ptrs have the same
910         // representation, we still register an Adjust::DerefRef so that
911         // regionck knows that the region for `a` must be valid here.
912         if is_ref {
913             self.unify_and(a_unsafe, b, |target| {
914                 vec![
915                     Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
916                     Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
917                 ]
918             })
919         } else if mt_a.mutbl != mutbl_b {
920             self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
921         } else {
922             self.unify_and(a_unsafe, b, identity)
923         }
924     }
925 }
926
927 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
928     /// Attempt to coerce an expression to a type, and return the
929     /// adjusted type of the expression, if successful.
930     /// Adjustments are only recorded if the coercion succeeded.
931     /// The expressions *must not* have any pre-existing adjustments.
932     pub fn try_coerce(
933         &self,
934         expr: &hir::Expr<'_>,
935         expr_ty: Ty<'tcx>,
936         target: Ty<'tcx>,
937         allow_two_phase: AllowTwoPhase,
938     ) -> RelateResult<'tcx, Ty<'tcx>> {
939         let source = self.resolve_vars_with_obligations(expr_ty);
940         debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
941
942         let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
943         let coerce = Coerce::new(self, cause, allow_two_phase);
944         let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
945
946         let (adjustments, _) = self.register_infer_ok_obligations(ok);
947         self.apply_adjustments(expr, adjustments);
948         Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target })
949     }
950
951     /// Same as `try_coerce()`, but without side-effects.
952     pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
953         let source = self.resolve_vars_with_obligations(expr_ty);
954         debug!("coercion::can({:?} -> {:?})", source, target);
955
956         let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
957         // We don't ever need two-phase here since we throw out the result of the coercion
958         let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
959         self.probe(|_| coerce.coerce(source, target)).is_ok()
960     }
961
962     /// Given a type and a target type, this function will calculate and return
963     /// how many dereference steps needed to achieve `expr_ty <: target`. If
964     /// it's not possible, return `None`.
965     pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
966         let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
967         // We don't ever need two-phase here since we throw out the result of the coercion
968         let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
969         coerce
970             .autoderef(rustc_span::DUMMY_SP, expr_ty)
971             .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
972     }
973
974     /// Given some expressions, their known unified type and another expression,
975     /// tries to unify the types, potentially inserting coercions on any of the
976     /// provided expressions and returns their LUB (aka "common supertype").
977     ///
978     /// This is really an internal helper. From outside the coercion
979     /// module, you should instantiate a `CoerceMany` instance.
980     fn try_find_coercion_lub<E>(
981         &self,
982         cause: &ObligationCause<'tcx>,
983         exprs: &[E],
984         prev_ty: Ty<'tcx>,
985         new: &hir::Expr<'_>,
986         new_ty: Ty<'tcx>,
987     ) -> RelateResult<'tcx, Ty<'tcx>>
988     where
989         E: AsCoercionSite,
990     {
991         let prev_ty = self.resolve_vars_with_obligations(prev_ty);
992         let new_ty = self.resolve_vars_with_obligations(new_ty);
993         debug!(
994             "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
995             prev_ty,
996             new_ty,
997             exprs.len()
998         );
999
1000         // The following check fixes #88097, where the compiler erroneously
1001         // attempted to coerce a closure type to itself via a function pointer.
1002         if prev_ty == new_ty {
1003             return Ok(prev_ty);
1004         }
1005
1006         // Special-case that coercion alone cannot handle:
1007         // Function items or non-capturing closures of differing IDs or InternalSubsts.
1008         let (a_sig, b_sig) = {
1009             let is_capturing_closure = |ty| {
1010                 if let &ty::Closure(closure_def_id, _substs) = ty {
1011                     self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
1012                 } else {
1013                     false
1014                 }
1015             };
1016             if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) {
1017                 (None, None)
1018             } else {
1019                 match (prev_ty.kind(), new_ty.kind()) {
1020                     (ty::FnDef(..), ty::FnDef(..)) => {
1021                         // Don't reify if the function types have a LUB, i.e., they
1022                         // are the same function and their parameters have a LUB.
1023                         match self
1024                             .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1025                         {
1026                             // We have a LUB of prev_ty and new_ty, just return it.
1027                             Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1028                             Err(_) => {
1029                                 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
1030                             }
1031                         }
1032                     }
1033                     (ty::Closure(_, substs), ty::FnDef(..)) => {
1034                         let b_sig = new_ty.fn_sig(self.tcx);
1035                         let a_sig = self
1036                             .tcx
1037                             .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
1038                         (Some(a_sig), Some(b_sig))
1039                     }
1040                     (ty::FnDef(..), ty::Closure(_, substs)) => {
1041                         let a_sig = prev_ty.fn_sig(self.tcx);
1042                         let b_sig = self
1043                             .tcx
1044                             .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
1045                         (Some(a_sig), Some(b_sig))
1046                     }
1047                     (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => (
1048                         Some(self.tcx.signature_unclosure(
1049                             substs_a.as_closure().sig(),
1050                             hir::Unsafety::Normal,
1051                         )),
1052                         Some(self.tcx.signature_unclosure(
1053                             substs_b.as_closure().sig(),
1054                             hir::Unsafety::Normal,
1055                         )),
1056                     ),
1057                     _ => (None, None),
1058                 }
1059             }
1060         };
1061         if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
1062             // Intrinsics are not coercible to function pointers.
1063             if a_sig.abi() == Abi::RustIntrinsic
1064                 || a_sig.abi() == Abi::PlatformIntrinsic
1065                 || b_sig.abi() == Abi::RustIntrinsic
1066                 || b_sig.abi() == Abi::PlatformIntrinsic
1067             {
1068                 return Err(TypeError::IntrinsicCast);
1069             }
1070             // The signature must match.
1071             let a_sig = self.normalize_associated_types_in(new.span, a_sig);
1072             let b_sig = self.normalize_associated_types_in(new.span, b_sig);
1073             let sig = self
1074                 .at(cause, self.param_env)
1075                 .trace(prev_ty, new_ty)
1076                 .lub(a_sig, b_sig)
1077                 .map(|ok| self.register_infer_ok_obligations(ok))?;
1078
1079             // Reify both sides and return the reified fn pointer type.
1080             let fn_ptr = self.tcx.mk_fn_ptr(sig);
1081             let prev_adjustment = match prev_ty.kind() {
1082                 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.unsafety())),
1083                 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1084                 _ => unreachable!(),
1085             };
1086             let next_adjustment = match new_ty.kind() {
1087                 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.unsafety())),
1088                 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1089                 _ => unreachable!(),
1090             };
1091             for expr in exprs.iter().map(|e| e.as_coercion_site()) {
1092                 self.apply_adjustments(
1093                     expr,
1094                     vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1095                 );
1096             }
1097             self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1098             return Ok(fn_ptr);
1099         }
1100
1101         // Configure a Coerce instance to compute the LUB.
1102         // We don't allow two-phase borrows on any autorefs this creates since we
1103         // probably aren't processing function arguments here and even if we were,
1104         // they're going to get autorefed again anyway and we can apply 2-phase borrows
1105         // at that time.
1106         let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
1107         coerce.use_lub = true;
1108
1109         // First try to coerce the new expression to the type of the previous ones,
1110         // but only if the new expression has no coercion already applied to it.
1111         let mut first_error = None;
1112         if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1113             let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1114             match result {
1115                 Ok(ok) => {
1116                     let (adjustments, target) = self.register_infer_ok_obligations(ok);
1117                     self.apply_adjustments(new, adjustments);
1118                     debug!(
1119                         "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}",
1120                         prev_ty, new_ty,
1121                     );
1122                     return Ok(target);
1123                 }
1124                 Err(e) => first_error = Some(e),
1125             }
1126         }
1127
1128         // Then try to coerce the previous expressions to the type of the new one.
1129         // This requires ensuring there are no coercions applied to *any* of the
1130         // previous expressions, other than noop reborrows (ignoring lifetimes).
1131         for expr in exprs {
1132             let expr = expr.as_coercion_site();
1133             let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
1134                 &[Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }] =>
1135                 {
1136                     match *self.node_ty(expr.hir_id).kind() {
1137                         ty::Ref(_, _, mt_orig) => {
1138                             let mutbl_adj: hir::Mutability = mutbl_adj.into();
1139                             // Reborrow that we can safely ignore, because
1140                             // the next adjustment can only be a Deref
1141                             // which will be merged into it.
1142                             mutbl_adj == mt_orig
1143                         }
1144                         _ => false,
1145                     }
1146                 }
1147                 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1148                 _ => false,
1149             };
1150
1151             if !noop {
1152                 debug!(
1153                     "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1154                     expr,
1155                 );
1156
1157                 return self
1158                     .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1159                     .map(|ok| self.register_infer_ok_obligations(ok));
1160             }
1161         }
1162
1163         match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1164             Err(_) => {
1165                 // Avoid giving strange errors on failed attempts.
1166                 if let Some(e) = first_error {
1167                     Err(e)
1168                 } else {
1169                     self.commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1170                         .map(|ok| self.register_infer_ok_obligations(ok))
1171                 }
1172             }
1173             Ok(ok) => {
1174                 debug!(
1175                     "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?}",
1176                     prev_ty, new_ty,
1177                 );
1178                 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1179                 for expr in exprs {
1180                     let expr = expr.as_coercion_site();
1181                     self.apply_adjustments(expr, adjustments.clone());
1182                 }
1183                 Ok(target)
1184             }
1185         }
1186     }
1187 }
1188
1189 /// CoerceMany encapsulates the pattern you should use when you have
1190 /// many expressions that are all getting coerced to a common
1191 /// type. This arises, for example, when you have a match (the result
1192 /// of each arm is coerced to a common type). It also arises in less
1193 /// obvious places, such as when you have many `break foo` expressions
1194 /// that target the same loop, or the various `return` expressions in
1195 /// a function.
1196 ///
1197 /// The basic protocol is as follows:
1198 ///
1199 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1200 ///   This will also serve as the "starting LUB". The expectation is
1201 ///   that this type is something which all of the expressions *must*
1202 ///   be coercible to. Use a fresh type variable if needed.
1203 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1204 ///   - In some cases we wish to coerce "non-expressions" whose types are implicitly
1205 ///     unit. This happens for example if you have a `break` with no expression,
1206 ///     or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1207 ///   - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1208 ///     from you so that you don't have to worry your pretty head about it.
1209 ///     But if an error is reported, the final type will be `err`.
1210 ///   - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1211 ///     previously coerced expressions.
1212 /// - When all done, invoke `complete()`. This will return the LUB of
1213 ///   all your expressions.
1214 ///   - WARNING: I don't believe this final type is guaranteed to be
1215 ///     related to your initial `expected_ty` in any particular way,
1216 ///     although it will typically be a subtype, so you should check it.
1217 ///   - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1218 ///     previously coerced expressions.
1219 ///
1220 /// Example:
1221 ///
1222 /// ```
1223 /// let mut coerce = CoerceMany::new(expected_ty);
1224 /// for expr in exprs {
1225 ///     let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1226 ///     coerce.coerce(fcx, &cause, expr, expr_ty);
1227 /// }
1228 /// let final_ty = coerce.complete(fcx);
1229 /// ```
1230 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1231     expected_ty: Ty<'tcx>,
1232     final_ty: Option<Ty<'tcx>>,
1233     expressions: Expressions<'tcx, 'exprs, E>,
1234     pushed: usize,
1235 }
1236
1237 /// The type of a `CoerceMany` that is storing up the expressions into
1238 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1239 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1240
1241 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1242     Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1243     UpFront(&'exprs [E]),
1244 }
1245
1246 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1247     /// The usual case; collect the set of expressions dynamically.
1248     /// If the full set of coercion sites is known before hand,
1249     /// consider `with_coercion_sites()` instead to avoid allocation.
1250     pub fn new(expected_ty: Ty<'tcx>) -> Self {
1251         Self::make(expected_ty, Expressions::Dynamic(vec![]))
1252     }
1253
1254     /// As an optimization, you can create a `CoerceMany` with a
1255     /// pre-existing slice of expressions. In this case, you are
1256     /// expected to pass each element in the slice to `coerce(...)` in
1257     /// order. This is used with arrays in particular to avoid
1258     /// needlessly cloning the slice.
1259     pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1260         Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1261     }
1262
1263     fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1264         CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1265     }
1266
1267     /// Returns the "expected type" with which this coercion was
1268     /// constructed. This represents the "downward propagated" type
1269     /// that was given to us at the start of typing whatever construct
1270     /// we are typing (e.g., the match expression).
1271     ///
1272     /// Typically, this is used as the expected type when
1273     /// type-checking each of the alternative expressions whose types
1274     /// we are trying to merge.
1275     pub fn expected_ty(&self) -> Ty<'tcx> {
1276         self.expected_ty
1277     }
1278
1279     /// Returns the current "merged type", representing our best-guess
1280     /// at the LUB of the expressions we've seen so far (if any). This
1281     /// isn't *final* until you call `self.final()`, which will return
1282     /// the merged type.
1283     pub fn merged_ty(&self) -> Ty<'tcx> {
1284         self.final_ty.unwrap_or(self.expected_ty)
1285     }
1286
1287     /// Indicates that the value generated by `expression`, which is
1288     /// of type `expression_ty`, is one of the possibilities that we
1289     /// could coerce from. This will record `expression`, and later
1290     /// calls to `coerce` may come back and add adjustments and things
1291     /// if necessary.
1292     pub fn coerce<'a>(
1293         &mut self,
1294         fcx: &FnCtxt<'a, 'tcx>,
1295         cause: &ObligationCause<'tcx>,
1296         expression: &'tcx hir::Expr<'tcx>,
1297         expression_ty: Ty<'tcx>,
1298     ) {
1299         self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1300     }
1301
1302     /// Indicates that one of the inputs is a "forced unit". This
1303     /// occurs in a case like `if foo { ... };`, where the missing else
1304     /// generates a "forced unit". Another example is a `loop { break;
1305     /// }`, where the `break` has no argument expression. We treat
1306     /// these cases slightly differently for error-reporting
1307     /// purposes. Note that these tend to correspond to cases where
1308     /// the `()` expression is implicit in the source, and hence we do
1309     /// not take an expression argument.
1310     ///
1311     /// The `augment_error` gives you a chance to extend the error
1312     /// message, in case any results (e.g., we use this to suggest
1313     /// removing a `;`).
1314     pub fn coerce_forced_unit<'a>(
1315         &mut self,
1316         fcx: &FnCtxt<'a, 'tcx>,
1317         cause: &ObligationCause<'tcx>,
1318         augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1319         label_unit_as_expected: bool,
1320     ) {
1321         self.coerce_inner(
1322             fcx,
1323             cause,
1324             None,
1325             fcx.tcx.mk_unit(),
1326             Some(augment_error),
1327             label_unit_as_expected,
1328         )
1329     }
1330
1331     /// The inner coercion "engine". If `expression` is `None`, this
1332     /// is a forced-unit case, and hence `expression_ty` must be
1333     /// `Nil`.
1334     #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1335     crate fn coerce_inner<'a>(
1336         &mut self,
1337         fcx: &FnCtxt<'a, 'tcx>,
1338         cause: &ObligationCause<'tcx>,
1339         expression: Option<&'tcx hir::Expr<'tcx>>,
1340         mut expression_ty: Ty<'tcx>,
1341         augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1342         label_expression_as_expected: bool,
1343     ) {
1344         // Incorporate whatever type inference information we have
1345         // until now; in principle we might also want to process
1346         // pending obligations, but doing so should only improve
1347         // compatibility (hopefully that is true) by helping us
1348         // uncover never types better.
1349         if expression_ty.is_ty_var() {
1350             expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1351         }
1352
1353         // If we see any error types, just propagate that error
1354         // upwards.
1355         if expression_ty.references_error() || self.merged_ty().references_error() {
1356             self.final_ty = Some(fcx.tcx.ty_error());
1357             return;
1358         }
1359
1360         // Handle the actual type unification etc.
1361         let result = if let Some(expression) = expression {
1362             if self.pushed == 0 {
1363                 // Special-case the first expression we are coercing.
1364                 // To be honest, I'm not entirely sure why we do this.
1365                 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1366                 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1367             } else {
1368                 match self.expressions {
1369                     Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1370                         cause,
1371                         exprs,
1372                         self.merged_ty(),
1373                         expression,
1374                         expression_ty,
1375                     ),
1376                     Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1377                         cause,
1378                         &coercion_sites[0..self.pushed],
1379                         self.merged_ty(),
1380                         expression,
1381                         expression_ty,
1382                     ),
1383                 }
1384             }
1385         } else {
1386             // this is a hack for cases where we default to `()` because
1387             // the expression etc has been omitted from the source. An
1388             // example is an `if let` without an else:
1389             //
1390             //     if let Some(x) = ... { }
1391             //
1392             // we wind up with a second match arm that is like `_ =>
1393             // ()`.  That is the case we are considering here. We take
1394             // a different path to get the right "expected, found"
1395             // message and so forth (and because we know that
1396             // `expression_ty` will be unit).
1397             //
1398             // Another example is `break` with no argument expression.
1399             assert!(expression_ty.is_unit(), "if let hack without unit type");
1400             fcx.at(cause, fcx.param_env)
1401                 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1402                 .map(|infer_ok| {
1403                     fcx.register_infer_ok_obligations(infer_ok);
1404                     expression_ty
1405                 })
1406         };
1407
1408         match result {
1409             Ok(v) => {
1410                 self.final_ty = Some(v);
1411                 if let Some(e) = expression {
1412                     match self.expressions {
1413                         Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1414                         Expressions::UpFront(coercion_sites) => {
1415                             // if the user gave us an array to validate, check that we got
1416                             // the next expression in the list, as expected
1417                             assert_eq!(
1418                                 coercion_sites[self.pushed].as_coercion_site().hir_id,
1419                                 e.hir_id
1420                             );
1421                         }
1422                     }
1423                     self.pushed += 1;
1424                 }
1425             }
1426             Err(coercion_error) => {
1427                 let (expected, found) = if label_expression_as_expected {
1428                     // In the case where this is a "forced unit", like
1429                     // `break`, we want to call the `()` "expected"
1430                     // since it is implied by the syntax.
1431                     // (Note: not all force-units work this way.)"
1432                     (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1433                 } else {
1434                     // Otherwise, the "expected" type for error
1435                     // reporting is the current unification type,
1436                     // which is basically the LUB of the expressions
1437                     // we've seen so far (combined with the expected
1438                     // type)
1439                     (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1440                 };
1441
1442                 let mut err;
1443                 let mut unsized_return = false;
1444                 match cause.code {
1445                     ObligationCauseCode::ReturnNoExpression => {
1446                         err = struct_span_err!(
1447                             fcx.tcx.sess,
1448                             cause.span,
1449                             E0069,
1450                             "`return;` in a function whose return type is not `()`"
1451                         );
1452                         err.span_label(cause.span, "return type is not `()`");
1453                     }
1454                     ObligationCauseCode::BlockTailExpression(blk_id) => {
1455                         let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1456                         err = self.report_return_mismatched_types(
1457                             cause,
1458                             expected,
1459                             found,
1460                             coercion_error,
1461                             fcx,
1462                             parent_id,
1463                             expression.map(|expr| (expr, blk_id)),
1464                         );
1465                         if !fcx.tcx.features().unsized_locals {
1466                             unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1467                         }
1468                     }
1469                     ObligationCauseCode::ReturnValue(id) => {
1470                         err = self.report_return_mismatched_types(
1471                             cause,
1472                             expected,
1473                             found,
1474                             coercion_error,
1475                             fcx,
1476                             id,
1477                             None,
1478                         );
1479                         if !fcx.tcx.features().unsized_locals {
1480                             let id = fcx.tcx.hir().get_parent_node(id);
1481                             unsized_return = self.is_return_ty_unsized(fcx, id);
1482                         }
1483                     }
1484                     _ => {
1485                         err = fcx.report_mismatched_types(cause, expected, found, coercion_error);
1486                     }
1487                 }
1488
1489                 if let Some(augment_error) = augment_error {
1490                     augment_error(&mut err);
1491                 }
1492
1493                 if let Some(expr) = expression {
1494                     fcx.emit_coerce_suggestions(&mut err, expr, found, expected, None);
1495                 }
1496
1497                 // Error possibly reported in `check_assign` so avoid emitting error again.
1498                 let assign_to_bool = expression
1499                     // #67273: Use initial expected type as opposed to `expected`.
1500                     // Otherwise we end up using prior coercions in e.g. a `match` expression:
1501                     // ```
1502                     // match i {
1503                     //     0 => true, // Because of this...
1504                     //     1 => i = 1, // ...`expected == bool` now, but not when checking `i = 1`.
1505                     //     _ => (),
1506                     // };
1507                     // ```
1508                     .filter(|e| fcx.is_assign_to_bool(e, self.expected_ty()))
1509                     .is_some();
1510
1511                 err.emit_unless(assign_to_bool || unsized_return);
1512
1513                 self.final_ty = Some(fcx.tcx.ty_error());
1514             }
1515         }
1516     }
1517
1518     fn report_return_mismatched_types<'a>(
1519         &self,
1520         cause: &ObligationCause<'tcx>,
1521         expected: Ty<'tcx>,
1522         found: Ty<'tcx>,
1523         ty_err: TypeError<'tcx>,
1524         fcx: &FnCtxt<'a, 'tcx>,
1525         id: hir::HirId,
1526         expression: Option<(&'tcx hir::Expr<'tcx>, hir::HirId)>,
1527     ) -> DiagnosticBuilder<'a> {
1528         let mut err = fcx.report_mismatched_types(cause, expected, found, ty_err);
1529
1530         let mut pointing_at_return_type = false;
1531         let mut fn_output = None;
1532
1533         // Verify that this is a tail expression of a function, otherwise the
1534         // label pointing out the cause for the type coercion will be wrong
1535         // as prior return coercions would not be relevant (#57664).
1536         let parent_id = fcx.tcx.hir().get_parent_node(id);
1537         let fn_decl = if let Some((expr, blk_id)) = expression {
1538             pointing_at_return_type =
1539                 fcx.suggest_mismatched_types_on_tail(&mut err, expr, expected, found, blk_id);
1540             let parent = fcx.tcx.hir().get(parent_id);
1541             if let (Some(cond_expr), true, false) = (
1542                 fcx.tcx.hir().get_if_cause(expr.hir_id),
1543                 expected.is_unit(),
1544                 pointing_at_return_type,
1545             ) {
1546                 // If the block is from an external macro or try (`?`) desugaring, then
1547                 // do not suggest adding a semicolon, because there's nowhere to put it.
1548                 // See issues #81943 and #87051.
1549                 if cond_expr.span.desugaring_kind().is_none()
1550                     && !in_external_macro(fcx.tcx.sess, cond_expr.span)
1551                     && !matches!(
1552                         cond_expr.kind,
1553                         hir::ExprKind::Match(.., hir::MatchSource::TryDesugar)
1554                     )
1555                 {
1556                     err.span_label(cond_expr.span, "expected this to be `()`");
1557                     if expr.can_have_side_effects() {
1558                         fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1559                     }
1560                 }
1561             }
1562             fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1563         } else {
1564             fcx.get_fn_decl(parent_id)
1565         };
1566
1567         if let Some((fn_decl, can_suggest)) = fn_decl {
1568             if expression.is_none() {
1569                 pointing_at_return_type |= fcx.suggest_missing_return_type(
1570                     &mut err,
1571                     &fn_decl,
1572                     expected,
1573                     found,
1574                     can_suggest,
1575                     fcx.tcx.hir().get_parent_item(id),
1576                 );
1577             }
1578             if !pointing_at_return_type {
1579                 fn_output = Some(&fn_decl.output); // `impl Trait` return type
1580             }
1581         }
1582
1583         let parent_id = fcx.tcx.hir().get_parent_item(id);
1584         let parent_item = fcx.tcx.hir().get(parent_id);
1585
1586         if let (Some((expr, _)), Some((fn_decl, _, _))) =
1587             (expression, fcx.get_node_fn_decl(parent_item))
1588         {
1589             fcx.suggest_missing_break_or_return_expr(
1590                 &mut err, expr, fn_decl, expected, found, id, parent_id,
1591             );
1592         }
1593
1594         if let (Some(sp), Some(fn_output)) = (fcx.ret_coercion_span.get(), fn_output) {
1595             self.add_impl_trait_explanation(&mut err, cause, fcx, expected, sp, fn_output);
1596         }
1597         err
1598     }
1599
1600     fn add_impl_trait_explanation<'a>(
1601         &self,
1602         err: &mut DiagnosticBuilder<'a>,
1603         cause: &ObligationCause<'tcx>,
1604         fcx: &FnCtxt<'a, 'tcx>,
1605         expected: Ty<'tcx>,
1606         sp: Span,
1607         fn_output: &hir::FnRetTy<'_>,
1608     ) {
1609         let return_sp = fn_output.span();
1610         err.span_label(return_sp, "expected because this return type...");
1611         err.span_label(
1612             sp,
1613             format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1614         );
1615         let impl_trait_msg = "for information on `impl Trait`, see \
1616                 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1617                 #returning-types-that-implement-traits>";
1618         let trait_obj_msg = "for information on trait objects, see \
1619                 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1620                 #using-trait-objects-that-allow-for-values-of-different-types>";
1621         err.note("to return `impl Trait`, all returned values must be of the same type");
1622         err.note(impl_trait_msg);
1623         let snippet = fcx
1624             .tcx
1625             .sess
1626             .source_map()
1627             .span_to_snippet(return_sp)
1628             .unwrap_or_else(|_| "dyn Trait".to_string());
1629         let mut snippet_iter = snippet.split_whitespace();
1630         let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1631         // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1632         let mut is_object_safe = false;
1633         if let hir::FnRetTy::Return(ty) = fn_output {
1634             // Get the return type.
1635             if let hir::TyKind::OpaqueDef(..) = ty.kind {
1636                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1637                 // Get the `impl Trait`'s `DefId`.
1638                 if let ty::Opaque(def_id, _) = ty.kind() {
1639                     let hir_id = fcx.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1640                     // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1641                     // get the `Trait`'s `DefId`.
1642                     if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1643                         fcx.tcx.hir().expect_item(hir_id).kind
1644                     {
1645                         // Are of this `impl Trait`'s traits object safe?
1646                         is_object_safe = bounds.iter().all(|bound| {
1647                             bound
1648                                 .trait_ref()
1649                                 .and_then(|t| t.trait_def_id())
1650                                 .map_or(false, |def_id| {
1651                                     fcx.tcx.object_safety_violations(def_id).is_empty()
1652                                 })
1653                         })
1654                     }
1655                 }
1656             }
1657         };
1658         if has_impl {
1659             if is_object_safe {
1660                 err.multipart_suggestion(
1661                     "you could change the return type to be a boxed trait object",
1662                     vec![
1663                         (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
1664                         (return_sp.shrink_to_hi(), ">".to_string()),
1665                     ],
1666                     Applicability::MachineApplicable,
1667                 );
1668                 let sugg = vec![sp, cause.span]
1669                     .into_iter()
1670                     .flat_map(|sp| {
1671                         vec![
1672                             (sp.shrink_to_lo(), "Box::new(".to_string()),
1673                             (sp.shrink_to_hi(), ")".to_string()),
1674                         ]
1675                         .into_iter()
1676                     })
1677                     .collect::<Vec<_>>();
1678                 err.multipart_suggestion(
1679                     "if you change the return type to expect trait objects, box the returned \
1680                      expressions",
1681                     sugg,
1682                     Applicability::MaybeIncorrect,
1683                 );
1684             } else {
1685                 err.help(&format!(
1686                     "if the trait `{}` were object safe, you could return a boxed trait object",
1687                     &snippet[5..]
1688                 ));
1689             }
1690             err.note(trait_obj_msg);
1691         }
1692         err.help("you could instead create a new `enum` with a variant for each returned type");
1693     }
1694
1695     fn is_return_ty_unsized(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
1696         if let Some((fn_decl, _)) = fcx.get_fn_decl(blk_id) {
1697             if let hir::FnRetTy::Return(ty) = fn_decl.output {
1698                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1699                 if let ty::Dynamic(..) = ty.kind() {
1700                     return true;
1701                 }
1702             }
1703         }
1704         false
1705     }
1706
1707     pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1708         if let Some(final_ty) = self.final_ty {
1709             final_ty
1710         } else {
1711             // If we only had inputs that were of type `!` (or no
1712             // inputs at all), then the final type is `!`.
1713             assert_eq!(self.pushed, 0);
1714             fcx.tcx.types.never
1715         }
1716     }
1717 }
1718
1719 /// Something that can be converted into an expression to which we can
1720 /// apply a coercion.
1721 pub trait AsCoercionSite {
1722     fn as_coercion_site(&self) -> &hir::Expr<'_>;
1723 }
1724
1725 impl AsCoercionSite for hir::Expr<'_> {
1726     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1727         self
1728     }
1729 }
1730
1731 impl<'a, T> AsCoercionSite for &'a T
1732 where
1733     T: AsCoercionSite,
1734 {
1735     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1736         (**self).as_coercion_site()
1737     }
1738 }
1739
1740 impl AsCoercionSite for ! {
1741     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1742         unreachable!()
1743     }
1744 }
1745
1746 impl AsCoercionSite for hir::Arm<'_> {
1747     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1748         &self.body
1749     }
1750 }