]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/coercion.rs
Rollup merge of #60951 - saleemjaffer:mir_better_error_enum, r=oli-obk
[rust.git] / src / librustc_typeck / 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/const things (that is, when the expected is &T
14 //! but you have &const T or &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/run-pass/coerce-reborrow-*.rs` tests for
17 //! examples of where this is useful.
18 //!
19 //! ## Subtle note
20 //!
21 //! When deciding what type coercions to consider, we do not attempt to
22 //! resolve any type variables we may encounter. This is because `b`
23 //! represents the expected type "as the user wrote it", meaning that if
24 //! the user defined a generic function like
25 //!
26 //!    fn foo<A>(a: A, b: A) { ... }
27 //!
28 //! and then we wrote `foo(&1, @2)`, we will not auto-borrow
29 //! either argument. In older code we went to some lengths to
30 //! resolve the `b` variable, which could mean that we'd
31 //! auto-borrow later arguments but not earlier ones, which
32 //! seems very confusing.
33 //!
34 //! ## Subtler note
35 //!
36 //! However, right now, if the user manually specifies the
37 //! values for the type variables, as so:
38 //!
39 //!    foo::<&int>(@1, @2)
40 //!
41 //! then we *will* auto-borrow, because we can't distinguish this from a
42 //! function that declared `&int`. This is inconsistent but it's easiest
43 //! at the moment. The right thing to do, I think, is to consider the
44 //! *unsubstituted* type when deciding whether to auto-borrow, but the
45 //! *substituted* type when considering the bounds and so forth. But most
46 //! of our methods don't give access to the unsubstituted type, and
47 //! rightly so because they'd be error-prone. So maybe the thing to do is
48 //! to actually determine the kind of coercions that should occur
49 //! separately and pass them in. Or maybe it's ok as is. Anyway, it's
50 //! sort of a minor point so I've opted to leave it for later -- after all,
51 //! we may want to adjust precisely when coercions occur.
52
53 use crate::check::{FnCtxt, Needs};
54 use errors::DiagnosticBuilder;
55 use rustc::hir;
56 use rustc::hir::def_id::DefId;
57 use rustc::hir::ptr::P;
58 use rustc::infer::{Coercion, InferResult, InferOk};
59 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
60 use rustc::traits::{self, ObligationCause, ObligationCauseCode};
61 use rustc::ty::adjustment::{
62     Adjustment, Adjust, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast
63 };
64 use rustc::ty::{self, TypeAndMut, Ty, ClosureSubsts};
65 use rustc::ty::fold::TypeFoldable;
66 use rustc::ty::error::TypeError;
67 use rustc::ty::relate::RelateResult;
68 use smallvec::{smallvec, SmallVec};
69 use std::ops::Deref;
70 use syntax::feature_gate;
71 use syntax::symbol::sym;
72 use syntax_pos;
73
74 struct Coerce<'a, 'tcx> {
75     fcx: &'a FnCtxt<'a, 'tcx>,
76     cause: ObligationCause<'tcx>,
77     use_lub: bool,
78     /// Determines whether or not allow_two_phase_borrow is set on any
79     /// autoref adjustments we create while coercing. We don't want to
80     /// allow deref coercions to create two-phase borrows, at least initially,
81     /// but we do need two-phase borrows for function argument reborrows.
82     /// See #47489 and #48598
83     /// See docs on the "AllowTwoPhase" type for a more detailed discussion
84     allow_two_phase: AllowTwoPhase,
85 }
86
87 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
88     type Target = FnCtxt<'a, 'tcx>;
89     fn deref(&self) -> &Self::Target {
90         &self.fcx
91     }
92 }
93
94 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
95
96 fn coerce_mutbls<'tcx>(from_mutbl: hir::Mutability,
97                        to_mutbl: hir::Mutability)
98                        -> RelateResult<'tcx, ()> {
99     match (from_mutbl, to_mutbl) {
100         (hir::MutMutable, hir::MutMutable) |
101         (hir::MutImmutable, hir::MutImmutable) |
102         (hir::MutMutable, hir::MutImmutable) => Ok(()),
103         (hir::MutImmutable, hir::MutMutable) => Err(TypeError::Mutability),
104     }
105 }
106
107 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> { vec![] }
108
109 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
110     move |target| vec![Adjustment { kind, target }]
111 }
112
113 fn success<'tcx>(adj: Vec<Adjustment<'tcx>>,
114                  target: Ty<'tcx>,
115                  obligations: traits::PredicateObligations<'tcx>)
116                  -> CoerceResult<'tcx> {
117     Ok(InferOk {
118         value: (adj, target),
119         obligations
120     })
121 }
122
123 impl<'f, 'tcx> Coerce<'f, 'tcx> {
124     fn new(
125         fcx: &'f FnCtxt<'f, 'tcx>,
126         cause: ObligationCause<'tcx>,
127         allow_two_phase: AllowTwoPhase,
128     ) -> Self {
129         Coerce {
130             fcx,
131             cause,
132             allow_two_phase,
133             use_lub: false,
134         }
135     }
136
137     fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
138         self.commit_if_ok(|_| {
139             if self.use_lub {
140                 self.at(&self.cause, self.fcx.param_env).lub(b, a)
141             } else {
142                 self.at(&self.cause, self.fcx.param_env)
143                     .sup(b, a)
144                     .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
145             }
146         })
147     }
148
149     /// Unify two types (using sub or lub) and produce a specific coercion.
150     fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F)
151                     -> CoerceResult<'tcx>
152         where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
153     {
154         self.unify(&a, &b).and_then(|InferOk { value: ty, obligations }| {
155             success(f(ty), ty, obligations)
156         })
157     }
158
159     fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
160         let a = self.shallow_resolve(a);
161         debug!("Coerce.tys({:?} => {:?})", a, b);
162
163         // Just ignore error types.
164         if a.references_error() || b.references_error() {
165             return success(vec![], b, vec![]);
166         }
167
168         if a.is_never() {
169             // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
170             // type variable, we want `?T` to fallback to `!` if not
171             // otherwise constrained. An example where this arises:
172             //
173             //     let _: Option<?T> = Some({ return; });
174             //
175             // here, we would coerce from `!` to `?T`.
176             let b = self.shallow_resolve(b);
177             return if self.shallow_resolve(b).is_ty_var() {
178                 // Micro-optimization: no need for this if `b` is
179                 // already resolved in some way.
180                 let diverging_ty = self.next_diverging_ty_var(
181                     TypeVariableOrigin {
182                         kind: TypeVariableOriginKind::AdjustmentType,
183                         span: self.cause.span,
184                     },
185                 );
186                 self.unify_and(&b, &diverging_ty, simple(Adjust::NeverToAny))
187             } else {
188                 success(simple(Adjust::NeverToAny)(b), b, vec![])
189             };
190         }
191
192         // Consider coercing the subtype to a DST
193         //
194         // NOTE: this is wrapped in a `commit_if_ok` because it creates
195         // a "spurious" type variable, and we don't want to have that
196         // type variable in memory if the coercion fails.
197         let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
198         if unsize.is_ok() {
199             debug!("coerce: unsize successful");
200             return unsize;
201         }
202         debug!("coerce: unsize failed");
203
204         // Examine the supertype and consider auto-borrowing.
205         //
206         // Note: does not attempt to resolve type variables we encounter.
207         // See above for details.
208         match b.sty {
209             ty::RawPtr(mt_b) => {
210                 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
211             }
212
213             ty::Ref(r_b, ty, mutbl) => {
214                 let mt_b = ty::TypeAndMut { ty, mutbl };
215                 return self.coerce_borrowed_pointer(a, b, r_b, mt_b);
216             }
217
218             _ => {}
219         }
220
221         match a.sty {
222             ty::FnDef(..) => {
223                 // Function items are coercible to any closure
224                 // type; function pointers are not (that would
225                 // require double indirection).
226                 // Additionally, we permit coercion of function
227                 // items to drop the unsafe qualifier.
228                 self.coerce_from_fn_item(a, b)
229             }
230             ty::FnPtr(a_f) => {
231                 // We permit coercion of fn pointers to drop the
232                 // unsafe qualifier.
233                 self.coerce_from_fn_pointer(a, a_f, b)
234             }
235             ty::Closure(def_id_a, substs_a) => {
236                 // Non-capturing closures are coercible to
237                 // function pointers or unsafe function pointers.
238                 // It cannot convert closures that require unsafe.
239                 self.coerce_closure_to_fn(a, def_id_a, substs_a, b)
240             }
241             _ => {
242                 // Otherwise, just use unification rules.
243                 self.unify_and(a, b, identity)
244             }
245         }
246     }
247
248     /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
249     /// To match `A` with `B`, autoderef will be performed,
250     /// calling `deref`/`deref_mut` where necessary.
251     fn coerce_borrowed_pointer(&self,
252                                a: Ty<'tcx>,
253                                b: Ty<'tcx>,
254                                r_b: ty::Region<'tcx>,
255                                mt_b: TypeAndMut<'tcx>)
256                                -> CoerceResult<'tcx>
257     {
258         debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
259
260         // If we have a parameter of type `&M T_a` and the value
261         // provided is `expr`, we will be adding an implicit borrow,
262         // meaning that we convert `f(expr)` to `f(&M *expr)`.  Therefore,
263         // to type check, we will construct the type that `&M*expr` would
264         // yield.
265
266         let (r_a, mt_a) = match a.sty {
267             ty::Ref(r_a, ty, mutbl) => {
268                 let mt_a = ty::TypeAndMut { ty, mutbl };
269                 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
270                 (r_a, mt_a)
271             }
272             _ => return self.unify_and(a, b, identity),
273         };
274
275         let span = self.cause.span;
276
277         let mut first_error = None;
278         let mut r_borrow_var = None;
279         let mut autoderef = self.autoderef(span, a);
280         let mut found = None;
281
282         for (referent_ty, autoderefs) in autoderef.by_ref() {
283             if autoderefs == 0 {
284                 // Don't let this pass, otherwise it would cause
285                 // &T to autoref to &&T.
286                 continue;
287             }
288
289             // At this point, we have deref'd `a` to `referent_ty`.  So
290             // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
291             // In the autoderef loop for `&'a mut Vec<T>`, we would get
292             // three callbacks:
293             //
294             // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
295             // - `Vec<T>` -- 1 deref
296             // - `[T]` -- 2 deref
297             //
298             // At each point after the first callback, we want to
299             // check to see whether this would match out target type
300             // (`&'b mut [T]`) if we autoref'd it. We can't just
301             // compare the referent types, though, because we still
302             // have to consider the mutability. E.g., in the case
303             // we've been considering, we have an `&mut` reference, so
304             // the `T` in `[T]` needs to be unified with equality.
305             //
306             // Therefore, we construct reference types reflecting what
307             // the types will be after we do the final auto-ref and
308             // compare those. Note that this means we use the target
309             // mutability [1], since it may be that we are coercing
310             // from `&mut T` to `&U`.
311             //
312             // One fine point concerns the region that we use. We
313             // choose the region such that the region of the final
314             // type that results from `unify` will be the region we
315             // want for the autoref:
316             //
317             // - if in sub mode, that means we want to use `'b` (the
318             //   region from the target reference) for both
319             //   pointers [2]. This is because sub mode (somewhat
320             //   arbitrarily) returns the subtype region.  In the case
321             //   where we are coercing to a target type, we know we
322             //   want to use that target type region (`'b`) because --
323             //   for the program to type-check -- it must be the
324             //   smaller of the two.
325             //   - One fine point. It may be surprising that we can
326             //     use `'b` without relating `'a` and `'b`. The reason
327             //     that this is ok is that what we produce is
328             //     effectively a `&'b *x` expression (if you could
329             //     annotate the region of a borrow), and regionck has
330             //     code that adds edges from the region of a borrow
331             //     (`'b`, here) into the regions in the borrowed
332             //     expression (`*x`, here).  (Search for "link".)
333             // - if in lub mode, things can get fairly complicated. The
334             //   easiest thing is just to make a fresh
335             //   region variable [4], which effectively means we defer
336             //   the decision to region inference (and regionck, which will add
337             //   some more edges to this variable). However, this can wind up
338             //   creating a crippling number of variables in some cases --
339             //   e.g., #32278 -- so we optimize one particular case [3].
340             //   Let me try to explain with some examples:
341             //   - The "running example" above represents the simple case,
342             //     where we have one `&` reference at the outer level and
343             //     ownership all the rest of the way down. In this case,
344             //     we want `LUB('a, 'b)` as the resulting region.
345             //   - However, if there are nested borrows, that region is
346             //     too strong. Consider a coercion from `&'a &'x Rc<T>` to
347             //     `&'b T`. In this case, `'a` is actually irrelevant.
348             //     The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
349             //     we get spurious errors (`run-pass/regions-lub-ref-ref-rc.rs`).
350             //     (The errors actually show up in borrowck, typically, because
351             //     this extra edge causes the region `'a` to be inferred to something
352             //     too big, which then results in borrowck errors.)
353             //   - We could track the innermost shared reference, but there is already
354             //     code in regionck that has the job of creating links between
355             //     the region of a borrow and the regions in the thing being
356             //     borrowed (here, `'a` and `'x`), and it knows how to handle
357             //     all the various cases. So instead we just make a region variable
358             //     and let regionck figure it out.
359             let r = if !self.use_lub {
360                 r_b // [2] above
361             } else if autoderefs == 1 {
362                 r_a // [3] above
363             } else {
364                 if r_borrow_var.is_none() {
365                     // create var lazilly, at most once
366                     let coercion = Coercion(span);
367                     let r = self.next_region_var(coercion);
368                     r_borrow_var = Some(r); // [4] above
369                 }
370                 r_borrow_var.unwrap()
371             };
372             let derefd_ty_a = self.tcx.mk_ref(r,
373                                               TypeAndMut {
374                                                   ty: referent_ty,
375                                                   mutbl: mt_b.mutbl, // [1] above
376                                               });
377             match self.unify(derefd_ty_a, b) {
378                 Ok(ok) => {
379                     found = Some(ok);
380                     break;
381                 }
382                 Err(err) => {
383                     if first_error.is_none() {
384                         first_error = Some(err);
385                     }
386                 }
387             }
388         }
389
390         // Extract type or return an error. We return the first error
391         // we got, which should be from relating the "base" type
392         // (e.g., in example above, the failure from relating `Vec<T>`
393         // to the target type), since that should be the least
394         // confusing.
395         let InferOk { value: ty, mut obligations } = match found {
396             Some(d) => d,
397             None => {
398                 let err = first_error.expect("coerce_borrowed_pointer had no error");
399                 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
400                 return Err(err);
401             }
402         };
403
404         if ty == a && mt_a.mutbl == hir::MutImmutable && autoderef.step_count() == 1 {
405             // As a special case, if we would produce `&'a *x`, that's
406             // a total no-op. We end up with the type `&'a T` just as
407             // we started with.  In that case, just skip it
408             // altogether. This is just an optimization.
409             //
410             // Note that for `&mut`, we DO want to reborrow --
411             // otherwise, this would be a move, which might be an
412             // error. For example `foo(self.x)` where `self` and
413             // `self.x` both have `&mut `type would be a move of
414             // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
415             // which is a borrow.
416             assert_eq!(mt_b.mutbl, hir::MutImmutable); // can only coerce &T -> &U
417             return success(vec![], ty, obligations);
418         }
419
420         let needs = Needs::maybe_mut_place(mt_b.mutbl);
421         let InferOk { value: mut adjustments, obligations: o }
422             = autoderef.adjust_steps_as_infer_ok(self, needs);
423         obligations.extend(o);
424         obligations.extend(autoderef.into_obligations());
425
426         // Now apply the autoref. We have to extract the region out of
427         // the final ref type we got.
428         let r_borrow = match ty.sty {
429             ty::Ref(r_borrow, _, _) => r_borrow,
430             _ => span_bug!(span, "expected a ref type, got {:?}", ty),
431         };
432         let mutbl = match mt_b.mutbl {
433             hir::MutImmutable => AutoBorrowMutability::Immutable,
434             hir::MutMutable => AutoBorrowMutability::Mutable {
435                 allow_two_phase_borrow: self.allow_two_phase,
436             }
437         };
438         adjustments.push(Adjustment {
439             kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
440             target: ty
441         });
442
443         debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}",
444                ty,
445                adjustments);
446
447         success(adjustments, ty, obligations)
448     }
449
450
451     // &[T; n] or &mut [T; n] -> &[T]
452     // or &mut [T; n] -> &mut [T]
453     // or &Concrete -> &Trait, etc.
454     fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
455         debug!("coerce_unsized(source={:?}, target={:?})", source, target);
456
457         let traits = (self.tcx.lang_items().unsize_trait(),
458                       self.tcx.lang_items().coerce_unsized_trait());
459         let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
460             (u, cu)
461         } else {
462             debug!("missing Unsize or CoerceUnsized traits");
463             return Err(TypeError::Mismatch);
464         };
465
466         // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
467         // a DST unless we have to. This currently comes out in the wash since
468         // we can't unify [T] with U. But to properly support DST, we need to allow
469         // that, at which point we will need extra checks on the target here.
470
471         // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
472         let reborrow = match (&source.sty, &target.sty) {
473             (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
474                 coerce_mutbls(mutbl_a, mutbl_b)?;
475
476                 let coercion = Coercion(self.cause.span);
477                 let r_borrow = self.next_region_var(coercion);
478                 let mutbl = match mutbl_b {
479                     hir::MutImmutable => AutoBorrowMutability::Immutable,
480                     hir::MutMutable => AutoBorrowMutability::Mutable {
481                         // We don't allow two-phase borrows here, at least for initial
482                         // implementation. If it happens that this coercion is a function argument,
483                         // the reborrow in coerce_borrowed_ptr will pick it up.
484                         allow_two_phase_borrow: AllowTwoPhase::No,
485                     }
486                 };
487                 Some((Adjustment {
488                     kind: Adjust::Deref(None),
489                     target: ty_a
490                 }, Adjustment {
491                     kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
492                     target:  self.tcx.mk_ref(r_borrow, ty::TypeAndMut {
493                         mutbl: mutbl_b,
494                         ty: ty_a
495                     })
496                 }))
497             }
498             (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
499                 coerce_mutbls(mt_a, mt_b)?;
500
501                 Some((Adjustment {
502                     kind: Adjust::Deref(None),
503                     target: ty_a
504                 }, Adjustment {
505                     kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
506                     target:  self.tcx.mk_ptr(ty::TypeAndMut {
507                         mutbl: mt_b,
508                         ty: ty_a
509                     })
510                 }))
511             }
512             _ => None,
513         };
514         let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
515
516         // Setup either a subtyping or a LUB relationship between
517         // the `CoerceUnsized` target type and the expected type.
518         // We only have the latter, so we use an inference variable
519         // for the former and let type inference do the rest.
520         let origin = TypeVariableOrigin {
521             kind: TypeVariableOriginKind::MiscVariable,
522             span: self.cause.span,
523         };
524         let coerce_target = self.next_ty_var(origin);
525         let mut coercion = self.unify_and(coerce_target, target, |target| {
526             let unsize = Adjustment {
527                 kind: Adjust::Pointer(PointerCast::Unsize),
528                 target
529             };
530             match reborrow {
531                 None => vec![unsize],
532                 Some((ref deref, ref autoref)) => {
533                     vec![deref.clone(), autoref.clone(), unsize]
534                 }
535             }
536         })?;
537
538         let mut selcx = traits::SelectionContext::new(self);
539
540         // Create an obligation for `Source: CoerceUnsized<Target>`.
541         let cause = ObligationCause::misc(self.cause.span, self.body_id);
542
543         // Use a FIFO queue for this custom fulfillment procedure.
544         //
545         // A Vec (or SmallVec) is not a natural choice for a queue. However,
546         // this code path is hot, and this queue usually has a max length of 1
547         // and almost never more than 3. By using a SmallVec we avoid an
548         // allocation, at the (very small) cost of (occasionally) having to
549         // shift subsequent elements down when removing the front element.
550         let mut queue: SmallVec<[_; 4]> =
551             smallvec![self.tcx.predicate_for_trait_def(self.fcx.param_env,
552                                                        cause,
553                                                        coerce_unsized_did,
554                                                        0,
555                                                        coerce_source,
556                                                        &[coerce_target.into()])];
557
558         let mut has_unsized_tuple_coercion = false;
559
560         // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
561         // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
562         // inference might unify those two inner type variables later.
563         let traits = [coerce_unsized_did, unsize_did];
564         while !queue.is_empty() {
565             let obligation = queue.remove(0);
566             debug!("coerce_unsized resolve step: {:?}", obligation);
567             let trait_ref = match obligation.predicate {
568                 ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => {
569                     if unsize_did == tr.def_id() {
570                         let sty = &tr.skip_binder().input_types().nth(1).unwrap().sty;
571                         if let ty::Tuple(..) = sty {
572                             debug!("coerce_unsized: found unsized tuple coercion");
573                             has_unsized_tuple_coercion = true;
574                         }
575                     }
576                     tr.clone()
577                 }
578                 _ => {
579                     coercion.obligations.push(obligation);
580                     continue;
581                 }
582             };
583             match selcx.select(&obligation.with(trait_ref)) {
584                 // Uncertain or unimplemented.
585                 Ok(None) => {
586                     if trait_ref.def_id() == unsize_did {
587                         let trait_ref = self.resolve_vars_if_possible(&trait_ref);
588                         let self_ty = trait_ref.skip_binder().self_ty();
589                         let unsize_ty = trait_ref.skip_binder().input_types().nth(1).unwrap();
590                         debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_ref);
591                         match (&self_ty.sty, &unsize_ty.sty) {
592                             (ty::Infer(ty::TyVar(v)),
593                              ty::Dynamic(..)) if self.type_var_is_sized(*v) => {
594                                 debug!("coerce_unsized: have sized infer {:?}", v);
595                                 coercion.obligations.push(obligation);
596                                 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
597                                 // for unsizing.
598                             }
599                             _ => {
600                                 // Some other case for `$0: Unsize<Something>`. Note that we
601                                 // hit this case even if `Something` is a sized type, so just
602                                 // don't do the coercion.
603                                 debug!("coerce_unsized: ambiguous unsize");
604                                 return Err(TypeError::Mismatch);
605                             }
606                         }
607                     } else {
608                         debug!("coerce_unsized: early return - ambiguous");
609                         return Err(TypeError::Mismatch);
610                     }
611                 }
612                 Err(traits::Unimplemented) => {
613                     debug!("coerce_unsized: early return - can't prove obligation");
614                     return Err(TypeError::Mismatch);
615                 }
616
617                 // Object safety violations or miscellaneous.
618                 Err(err) => {
619                     self.report_selection_error(&obligation, &err, false);
620                     // Treat this like an obligation and follow through
621                     // with the unsizing - the lack of a coercion should
622                     // be silent, as it causes a type mismatch later.
623                 }
624
625                 Ok(Some(vtable)) => {
626                     queue.extend(vtable.nested_obligations())
627                 }
628             }
629         }
630
631         if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
632             feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
633                                            sym::unsized_tuple_coercion,
634                                            self.cause.span,
635                                            feature_gate::GateIssue::Language,
636                                            feature_gate::EXPLAIN_UNSIZED_TUPLE_COERCION);
637         }
638
639         Ok(coercion)
640     }
641
642     fn coerce_from_safe_fn<F, G>(&self,
643                                  a: Ty<'tcx>,
644                                  fn_ty_a: ty::PolyFnSig<'tcx>,
645                                  b: Ty<'tcx>,
646                                  to_unsafe: F,
647                                  normal: G)
648                                  -> CoerceResult<'tcx>
649         where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
650               G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
651     {
652         if let ty::FnPtr(fn_ty_b) = b.sty {
653             if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe)
654                 = (fn_ty_a.unsafety(), fn_ty_b.unsafety())
655             {
656                 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
657                 return self.unify_and(unsafe_a, b, to_unsafe);
658             }
659         }
660         self.unify_and(a, b, normal)
661     }
662
663     fn coerce_from_fn_pointer(&self,
664                               a: Ty<'tcx>,
665                               fn_ty_a: ty::PolyFnSig<'tcx>,
666                               b: Ty<'tcx>)
667                               -> CoerceResult<'tcx> {
668         //! Attempts to coerce from the type of a Rust function item
669         //! into a closure or a `proc`.
670         //!
671
672         let b = self.shallow_resolve(b);
673         debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
674
675         self.coerce_from_safe_fn(a, fn_ty_a, b,
676             simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)), identity)
677     }
678
679     fn coerce_from_fn_item(&self,
680                            a: Ty<'tcx>,
681                            b: Ty<'tcx>)
682                            -> CoerceResult<'tcx> {
683         //! Attempts to coerce from the type of a Rust function item
684         //! into a closure or a `proc`.
685
686         let b = self.shallow_resolve(b);
687         debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
688
689         match b.sty {
690             ty::FnPtr(_) => {
691                 let a_sig = a.fn_sig(self.tcx);
692                 let InferOk { value: a_sig, mut obligations } =
693                     self.normalize_associated_types_in_as_infer_ok(self.cause.span, &a_sig);
694
695                 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
696                 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
697                     a_fn_pointer,
698                     a_sig,
699                     b,
700                     |unsafe_ty| {
701                         vec![
702                             Adjustment {
703                                 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
704                                 target: a_fn_pointer
705                             },
706                             Adjustment {
707                                 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
708                                 target: unsafe_ty
709                             },
710                         ]
711                     },
712                     simple(Adjust::Pointer(PointerCast::ReifyFnPointer))
713                 )?;
714
715                 obligations.extend(o2);
716                 Ok(InferOk { value, obligations })
717             }
718             _ => self.unify_and(a, b, identity),
719         }
720     }
721
722     fn coerce_closure_to_fn(&self,
723                            a: Ty<'tcx>,
724                            def_id_a: DefId,
725                            substs_a: ClosureSubsts<'tcx>,
726                            b: Ty<'tcx>)
727                            -> CoerceResult<'tcx> {
728         //! Attempts to coerce from the type of a non-capturing closure
729         //! into a function pointer.
730         //!
731
732         let b = self.shallow_resolve(b);
733
734         match b.sty {
735             ty::FnPtr(fn_ty) if self.tcx.upvars(def_id_a).map_or(true, |v| v.is_empty()) => {
736                 // We coerce the closure, which has fn type
737                 //     `extern "rust-call" fn((arg0,arg1,...)) -> _`
738                 // to
739                 //     `fn(arg0,arg1,...) -> _`
740                 // or
741                 //     `unsafe fn(arg0,arg1,...) -> _`
742                 let sig = self.closure_sig(def_id_a, substs_a);
743                 let unsafety = fn_ty.unsafety();
744                 let pointer_ty = self.tcx.coerce_closure_fn_ty(sig, unsafety);
745                 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})",
746                        a, b, pointer_ty);
747                 self.unify_and(pointer_ty, b, simple(
748                     Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))
749                 ))
750             }
751             _ => self.unify_and(a, b, identity),
752         }
753     }
754
755     fn coerce_unsafe_ptr(&self,
756                          a: Ty<'tcx>,
757                          b: Ty<'tcx>,
758                          mutbl_b: hir::Mutability)
759                          -> CoerceResult<'tcx> {
760         debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
761
762         let (is_ref, mt_a) = match a.sty {
763             ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
764             ty::RawPtr(mt) => (false, mt),
765             _ => return self.unify_and(a, b, identity)
766         };
767
768         // Check that the types which they point at are compatible.
769         let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut {
770             mutbl: mutbl_b,
771             ty: mt_a.ty,
772         });
773         coerce_mutbls(mt_a.mutbl, mutbl_b)?;
774         // Although references and unsafe ptrs have the same
775         // representation, we still register an Adjust::DerefRef so that
776         // regionck knows that the region for `a` must be valid here.
777         if is_ref {
778             self.unify_and(a_unsafe, b, |target| {
779                 vec![Adjustment {
780                     kind: Adjust::Deref(None),
781                     target: mt_a.ty
782                 }, Adjustment {
783                     kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
784                     target
785                 }]
786             })
787         } else if mt_a.mutbl != mutbl_b {
788             self.unify_and(
789                 a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer))
790             )
791         } else {
792             self.unify_and(a_unsafe, b, identity)
793         }
794     }
795 }
796
797 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
798     /// Attempt to coerce an expression to a type, and return the
799     /// adjusted type of the expression, if successful.
800     /// Adjustments are only recorded if the coercion succeeded.
801     /// The expressions *must not* have any pre-existing adjustments.
802     pub fn try_coerce(&self,
803                       expr: &hir::Expr,
804                       expr_ty: Ty<'tcx>,
805                       target: Ty<'tcx>,
806                       allow_two_phase: AllowTwoPhase)
807                       -> RelateResult<'tcx, Ty<'tcx>> {
808         let source = self.resolve_type_vars_with_obligations(expr_ty);
809         debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
810
811         let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
812         let coerce = Coerce::new(self, cause, allow_two_phase);
813         let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
814
815         let (adjustments, _) = self.register_infer_ok_obligations(ok);
816         self.apply_adjustments(expr, adjustments);
817         Ok(target)
818     }
819
820     /// Same as `try_coerce()`, but without side-effects.
821     pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
822         let source = self.resolve_type_vars_with_obligations(expr_ty);
823         debug!("coercion::can({:?} -> {:?})", source, target);
824
825         let cause = self.cause(syntax_pos::DUMMY_SP, ObligationCauseCode::ExprAssignable);
826         // We don't ever need two-phase here since we throw out the result of the coercion
827         let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
828         self.probe(|_| coerce.coerce(source, target)).is_ok()
829     }
830
831     /// Given some expressions, their known unified type and another expression,
832     /// tries to unify the types, potentially inserting coercions on any of the
833     /// provided expressions and returns their LUB (aka "common supertype").
834     ///
835     /// This is really an internal helper. From outside the coercion
836     /// module, you should instantiate a `CoerceMany` instance.
837     fn try_find_coercion_lub<E>(&self,
838                                 cause: &ObligationCause<'tcx>,
839                                 exprs: &[E],
840                                 prev_ty: Ty<'tcx>,
841                                 new: &hir::Expr,
842                                 new_ty: Ty<'tcx>)
843                                 -> RelateResult<'tcx, Ty<'tcx>>
844         where E: AsCoercionSite
845     {
846         let prev_ty = self.resolve_type_vars_with_obligations(prev_ty);
847         let new_ty = self.resolve_type_vars_with_obligations(new_ty);
848         debug!("coercion::try_find_coercion_lub({:?}, {:?})", prev_ty, new_ty);
849
850         // Special-case that coercion alone cannot handle:
851         // Two function item types of differing IDs or InternalSubsts.
852         if let (&ty::FnDef(..), &ty::FnDef(..)) = (&prev_ty.sty, &new_ty.sty) {
853             // Don't reify if the function types have a LUB, i.e., they
854             // are the same function and their parameters have a LUB.
855             let lub_ty = self.commit_if_ok(|_| {
856                 self.at(cause, self.param_env)
857                     .lub(prev_ty, new_ty)
858             }).map(|ok| self.register_infer_ok_obligations(ok));
859
860             if lub_ty.is_ok() {
861                 // We have a LUB of prev_ty and new_ty, just return it.
862                 return lub_ty;
863             }
864
865             // The signature must match.
866             let a_sig = prev_ty.fn_sig(self.tcx);
867             let a_sig = self.normalize_associated_types_in(new.span, &a_sig);
868             let b_sig = new_ty.fn_sig(self.tcx);
869             let b_sig = self.normalize_associated_types_in(new.span, &b_sig);
870             let sig = self.at(cause, self.param_env)
871                           .trace(prev_ty, new_ty)
872                           .lub(&a_sig, &b_sig)
873                           .map(|ok| self.register_infer_ok_obligations(ok))?;
874
875             // Reify both sides and return the reified fn pointer type.
876             let fn_ptr = self.tcx.mk_fn_ptr(sig);
877             for expr in exprs.iter().map(|e| e.as_coercion_site()).chain(Some(new)) {
878                 // The only adjustment that can produce an fn item is
879                 // `NeverToAny`, so this should always be valid.
880                 self.apply_adjustments(expr, vec![Adjustment {
881                     kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
882                     target: fn_ptr
883                 }]);
884             }
885             return Ok(fn_ptr);
886         }
887
888         // Configure a Coerce instance to compute the LUB.
889         // We don't allow two-phase borrows on any autorefs this creates since we
890         // probably aren't processing function arguments here and even if we were,
891         // they're going to get autorefed again anyway and we can apply 2-phase borrows
892         // at that time.
893         let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
894         coerce.use_lub = true;
895
896         // First try to coerce the new expression to the type of the previous ones,
897         // but only if the new expression has no coercion already applied to it.
898         let mut first_error = None;
899         if !self.tables.borrow().adjustments().contains_key(new.hir_id) {
900             let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
901             match result {
902                 Ok(ok) => {
903                     let (adjustments, target) = self.register_infer_ok_obligations(ok);
904                     self.apply_adjustments(new, adjustments);
905                     return Ok(target);
906                 }
907                 Err(e) => first_error = Some(e),
908             }
909         }
910
911         // Then try to coerce the previous expressions to the type of the new one.
912         // This requires ensuring there are no coercions applied to *any* of the
913         // previous expressions, other than noop reborrows (ignoring lifetimes).
914         for expr in exprs {
915             let expr = expr.as_coercion_site();
916             let noop = match self.tables.borrow().expr_adjustments(expr) {
917                 &[
918                     Adjustment { kind: Adjust::Deref(_), .. },
919                     Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }
920                 ] => {
921                     match self.node_ty(expr.hir_id).sty {
922                         ty::Ref(_, _, mt_orig) => {
923                             let mutbl_adj: hir::Mutability = mutbl_adj.into();
924                             // Reborrow that we can safely ignore, because
925                             // the next adjustment can only be a Deref
926                             // which will be merged into it.
927                             mutbl_adj == mt_orig
928                         }
929                         _ => false,
930                     }
931                 }
932                 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
933                 _ => false,
934             };
935
936             if !noop {
937                 return self.commit_if_ok(|_|
938                     self.at(cause, self.param_env)
939                         .lub(prev_ty, new_ty)
940                 ).map(|ok| self.register_infer_ok_obligations(ok));
941             }
942         }
943
944         match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
945             Err(_) => {
946                 // Avoid giving strange errors on failed attempts.
947                 if let Some(e) = first_error {
948                     Err(e)
949                 } else {
950                     self.commit_if_ok(|_|
951                         self.at(cause, self.param_env)
952                             .lub(prev_ty, new_ty)
953                     ).map(|ok| self.register_infer_ok_obligations(ok))
954                 }
955             }
956             Ok(ok) => {
957                 let (adjustments, target) = self.register_infer_ok_obligations(ok);
958                 for expr in exprs {
959                     let expr = expr.as_coercion_site();
960                     self.apply_adjustments(expr, adjustments.clone());
961                 }
962                 Ok(target)
963             }
964         }
965     }
966 }
967
968 /// CoerceMany encapsulates the pattern you should use when you have
969 /// many expressions that are all getting coerced to a common
970 /// type. This arises, for example, when you have a match (the result
971 /// of each arm is coerced to a common type). It also arises in less
972 /// obvious places, such as when you have many `break foo` expressions
973 /// that target the same loop, or the various `return` expressions in
974 /// a function.
975 ///
976 /// The basic protocol is as follows:
977 ///
978 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
979 ///   This will also serve as the "starting LUB". The expectation is
980 ///   that this type is something which all of the expressions *must*
981 ///   be coercible to. Use a fresh type variable if needed.
982 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
983 ///   - In some cases we wish to coerce "non-expressions" whose types are implicitly
984 ///     unit. This happens for example if you have a `break` with no expression,
985 ///     or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
986 ///   - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
987 ///     from you so that you don't have to worry your pretty head about it.
988 ///     But if an error is reported, the final type will be `err`.
989 ///   - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
990 ///     previously coerced expressions.
991 /// - When all done, invoke `complete()`. This will return the LUB of
992 ///   all your expressions.
993 ///   - WARNING: I don't believe this final type is guaranteed to be
994 ///     related to your initial `expected_ty` in any particular way,
995 ///     although it will typically be a subtype, so you should check it.
996 ///   - Invoking `complete()` may cause us to go and adjust the "adjustments" on
997 ///     previously coerced expressions.
998 ///
999 /// Example:
1000 ///
1001 /// ```
1002 /// let mut coerce = CoerceMany::new(expected_ty);
1003 /// for expr in exprs {
1004 ///     let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1005 ///     coerce.coerce(fcx, &cause, expr, expr_ty);
1006 /// }
1007 /// let final_ty = coerce.complete(fcx);
1008 /// ```
1009 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1010     expected_ty: Ty<'tcx>,
1011     final_ty: Option<Ty<'tcx>>,
1012     expressions: Expressions<'tcx, 'exprs, E>,
1013     pushed: usize,
1014 }
1015
1016 /// The type of a `CoerceMany` that is storing up the expressions into
1017 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1018 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, P<hir::Expr>>;
1019
1020 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1021     Dynamic(Vec<&'tcx hir::Expr>),
1022     UpFront(&'exprs [E]),
1023 }
1024
1025 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1026     /// The usual case; collect the set of expressions dynamically.
1027     /// If the full set of coercion sites is known before hand,
1028     /// consider `with_coercion_sites()` instead to avoid allocation.
1029     pub fn new(expected_ty: Ty<'tcx>) -> Self {
1030         Self::make(expected_ty, Expressions::Dynamic(vec![]))
1031     }
1032
1033     /// As an optimization, you can create a `CoerceMany` with a
1034     /// pre-existing slice of expressions. In this case, you are
1035     /// expected to pass each element in the slice to `coerce(...)` in
1036     /// order. This is used with arrays in particular to avoid
1037     /// needlessly cloning the slice.
1038     pub fn with_coercion_sites(expected_ty: Ty<'tcx>,
1039                                coercion_sites: &'exprs [E])
1040                                -> Self {
1041         Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1042     }
1043
1044     fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1045         CoerceMany {
1046             expected_ty,
1047             final_ty: None,
1048             expressions,
1049             pushed: 0,
1050         }
1051     }
1052
1053     /// Returns the "expected type" with which this coercion was
1054     /// constructed. This represents the "downward propagated" type
1055     /// that was given to us at the start of typing whatever construct
1056     /// we are typing (e.g., the match expression).
1057     ///
1058     /// Typically, this is used as the expected type when
1059     /// type-checking each of the alternative expressions whose types
1060     /// we are trying to merge.
1061     pub fn expected_ty(&self) -> Ty<'tcx> {
1062         self.expected_ty
1063     }
1064
1065     /// Returns the current "merged type", representing our best-guess
1066     /// at the LUB of the expressions we've seen so far (if any). This
1067     /// isn't *final* until you call `self.final()`, which will return
1068     /// the merged type.
1069     pub fn merged_ty(&self) -> Ty<'tcx> {
1070         self.final_ty.unwrap_or(self.expected_ty)
1071     }
1072
1073     /// Indicates that the value generated by `expression`, which is
1074     /// of type `expression_ty`, is one of the possibilities that we
1075     /// could coerce from. This will record `expression`, and later
1076     /// calls to `coerce` may come back and add adjustments and things
1077     /// if necessary.
1078     pub fn coerce<'a>(
1079         &mut self,
1080         fcx: &FnCtxt<'a, 'tcx>,
1081         cause: &ObligationCause<'tcx>,
1082         expression: &'tcx hir::Expr,
1083         expression_ty: Ty<'tcx>,
1084     ) {
1085         self.coerce_inner(fcx,
1086                           cause,
1087                           Some(expression),
1088                           expression_ty,
1089                           None, false)
1090     }
1091
1092     /// Indicates that one of the inputs is a "forced unit". This
1093     /// occurs in a case like `if foo { ... };`, where the missing else
1094     /// generates a "forced unit". Another example is a `loop { break;
1095     /// }`, where the `break` has no argument expression. We treat
1096     /// these cases slightly differently for error-reporting
1097     /// purposes. Note that these tend to correspond to cases where
1098     /// the `()` expression is implicit in the source, and hence we do
1099     /// not take an expression argument.
1100     ///
1101     /// The `augment_error` gives you a chance to extend the error
1102     /// message, in case any results (e.g., we use this to suggest
1103     /// removing a `;`).
1104     pub fn coerce_forced_unit<'a>(
1105         &mut self,
1106         fcx: &FnCtxt<'a, 'tcx>,
1107         cause: &ObligationCause<'tcx>,
1108         augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1109         label_unit_as_expected: bool,
1110     ) {
1111         self.coerce_inner(fcx,
1112                           cause,
1113                           None,
1114                           fcx.tcx.mk_unit(),
1115                           Some(augment_error),
1116                           label_unit_as_expected)
1117     }
1118
1119     /// The inner coercion "engine". If `expression` is `None`, this
1120     /// is a forced-unit case, and hence `expression_ty` must be
1121     /// `Nil`.
1122     fn coerce_inner<'a>(
1123         &mut self,
1124         fcx: &FnCtxt<'a, 'tcx>,
1125         cause: &ObligationCause<'tcx>,
1126         expression: Option<&'tcx hir::Expr>,
1127         mut expression_ty: Ty<'tcx>,
1128         augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1129         label_expression_as_expected: bool,
1130     ) {
1131         // Incorporate whatever type inference information we have
1132         // until now; in principle we might also want to process
1133         // pending obligations, but doing so should only improve
1134         // compatibility (hopefully that is true) by helping us
1135         // uncover never types better.
1136         if expression_ty.is_ty_var() {
1137             expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1138         }
1139
1140         // If we see any error types, just propagate that error
1141         // upwards.
1142         if expression_ty.references_error() || self.merged_ty().references_error() {
1143             self.final_ty = Some(fcx.tcx.types.err);
1144             return;
1145         }
1146
1147         // Handle the actual type unification etc.
1148         let result = if let Some(expression) = expression {
1149             if self.pushed == 0 {
1150                 // Special-case the first expression we are coercing.
1151                 // To be honest, I'm not entirely sure why we do this.
1152                 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1153                 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1154             } else {
1155                 match self.expressions {
1156                     Expressions::Dynamic(ref exprs) =>
1157                         fcx.try_find_coercion_lub(cause,
1158                                                   exprs,
1159                                                   self.merged_ty(),
1160                                                   expression,
1161                                                   expression_ty),
1162                     Expressions::UpFront(ref coercion_sites) =>
1163                         fcx.try_find_coercion_lub(cause,
1164                                                   &coercion_sites[0..self.pushed],
1165                                                   self.merged_ty(),
1166                                                   expression,
1167                                                   expression_ty),
1168                 }
1169             }
1170         } else {
1171             // this is a hack for cases where we default to `()` because
1172             // the expression etc has been omitted from the source. An
1173             // example is an `if let` without an else:
1174             //
1175             //     if let Some(x) = ... { }
1176             //
1177             // we wind up with a second match arm that is like `_ =>
1178             // ()`.  That is the case we are considering here. We take
1179             // a different path to get the right "expected, found"
1180             // message and so forth (and because we know that
1181             // `expression_ty` will be unit).
1182             //
1183             // Another example is `break` with no argument expression.
1184             assert!(expression_ty.is_unit(), "if let hack without unit type");
1185             fcx.at(cause, fcx.param_env)
1186                .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1187                .map(|infer_ok| {
1188                    fcx.register_infer_ok_obligations(infer_ok);
1189                    expression_ty
1190                })
1191         };
1192
1193         match result {
1194             Ok(v) => {
1195                 self.final_ty = Some(v);
1196                 if let Some(e) = expression {
1197                     match self.expressions {
1198                         Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1199                         Expressions::UpFront(coercion_sites) => {
1200                             // if the user gave us an array to validate, check that we got
1201                             // the next expression in the list, as expected
1202                             assert_eq!(coercion_sites[self.pushed].as_coercion_site().hir_id,
1203                                        e.hir_id);
1204                         }
1205                     }
1206                     self.pushed += 1;
1207                 }
1208             }
1209             Err(err) => {
1210                 let (expected, found) = if label_expression_as_expected {
1211                     // In the case where this is a "forced unit", like
1212                     // `break`, we want to call the `()` "expected"
1213                     // since it is implied by the syntax.
1214                     // (Note: not all force-units work this way.)"
1215                     (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1216                 } else {
1217                     // Otherwise, the "expected" type for error
1218                     // reporting is the current unification type,
1219                     // which is basically the LUB of the expressions
1220                     // we've seen so far (combined with the expected
1221                     // type)
1222                     (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1223                 };
1224
1225                 let mut db;
1226                 match cause.code {
1227                     ObligationCauseCode::ReturnNoExpression => {
1228                         db = struct_span_err!(
1229                             fcx.tcx.sess, cause.span, E0069,
1230                             "`return;` in a function whose return type is not `()`");
1231                         db.span_label(cause.span, "return type is not `()`");
1232                     }
1233                     ObligationCauseCode::BlockTailExpression(blk_id) => {
1234                         let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1235                         db = self.report_return_mismatched_types(
1236                             cause,
1237                             expected,
1238                             found,
1239                             err,
1240                             fcx,
1241                             parent_id,
1242                             expression.map(|expr| (expr, blk_id)),
1243                         );
1244                     }
1245                     ObligationCauseCode::ReturnType(id) => {
1246                         db = self.report_return_mismatched_types(
1247                             cause, expected, found, err, fcx, id, None);
1248                     }
1249                     _ => {
1250                         db = fcx.report_mismatched_types(cause, expected, found, err);
1251                     }
1252                 }
1253
1254                 if let Some(augment_error) = augment_error {
1255                     augment_error(&mut db);
1256                 }
1257
1258                 // Error possibly reported in `check_assign` so avoid emitting error again.
1259                 db.emit_unless(expression.filter(|e| fcx.is_assign_to_bool(e, expected)).is_some());
1260
1261                 self.final_ty = Some(fcx.tcx.types.err);
1262             }
1263         }
1264     }
1265
1266     fn report_return_mismatched_types<'a>(
1267         &self,
1268         cause: &ObligationCause<'tcx>,
1269         expected: Ty<'tcx>,
1270         found: Ty<'tcx>,
1271         err: TypeError<'tcx>,
1272         fcx: &FnCtxt<'a, 'tcx>,
1273         id: hir::HirId,
1274         expression: Option<(&'tcx hir::Expr, hir::HirId)>,
1275     ) -> DiagnosticBuilder<'a> {
1276         let mut db = fcx.report_mismatched_types(cause, expected, found, err);
1277
1278         let mut pointing_at_return_type = false;
1279         let mut return_sp = None;
1280
1281         // Verify that this is a tail expression of a function, otherwise the
1282         // label pointing out the cause for the type coercion will be wrong
1283         // as prior return coercions would not be relevant (#57664).
1284         let parent_id = fcx.tcx.hir().get_parent_node(id);
1285         let fn_decl = if let Some((expr, blk_id)) = expression {
1286             pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1287                 &mut db,
1288                 expr,
1289                 expected,
1290                 found,
1291                 cause.span,
1292                 blk_id,
1293             );
1294             let parent = fcx.tcx.hir().get(parent_id);
1295             fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1296         } else {
1297             fcx.get_fn_decl(parent_id)
1298         };
1299
1300         if let (Some((fn_decl, can_suggest)), _) = (fn_decl, pointing_at_return_type) {
1301             if expression.is_none() {
1302                 pointing_at_return_type |= fcx.suggest_missing_return_type(
1303                     &mut db, &fn_decl, expected, found, can_suggest);
1304             }
1305             if !pointing_at_return_type {
1306                 return_sp = Some(fn_decl.output.span()); // `impl Trait` return type
1307             }
1308         }
1309         if let (Some(sp), Some(return_sp)) = (fcx.ret_coercion_span.borrow().as_ref(), return_sp) {
1310             db.span_label(return_sp, "expected because this return type...");
1311             db.span_label( *sp, format!(
1312                 "...is found to be `{}` here",
1313                 fcx.resolve_type_vars_with_obligations(expected),
1314             ));
1315         }
1316         db
1317     }
1318
1319     pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1320         if let Some(final_ty) = self.final_ty {
1321             final_ty
1322         } else {
1323             // If we only had inputs that were of type `!` (or no
1324             // inputs at all), then the final type is `!`.
1325             assert_eq!(self.pushed, 0);
1326             fcx.tcx.types.never
1327         }
1328     }
1329 }
1330
1331 /// Something that can be converted into an expression to which we can
1332 /// apply a coercion.
1333 pub trait AsCoercionSite {
1334     fn as_coercion_site(&self) -> &hir::Expr;
1335 }
1336
1337 impl AsCoercionSite for hir::Expr {
1338     fn as_coercion_site(&self) -> &hir::Expr {
1339         self
1340     }
1341 }
1342
1343 impl AsCoercionSite for P<hir::Expr> {
1344     fn as_coercion_site(&self) -> &hir::Expr {
1345         self
1346     }
1347 }
1348
1349 impl<'a, T> AsCoercionSite for &'a T
1350     where T: AsCoercionSite
1351 {
1352     fn as_coercion_site(&self) -> &hir::Expr {
1353         (**self).as_coercion_site()
1354     }
1355 }
1356
1357 impl AsCoercionSite for ! {
1358     fn as_coercion_site(&self) -> &hir::Expr {
1359         unreachable!()
1360     }
1361 }
1362
1363 impl AsCoercionSite for hir::Arm {
1364     fn as_coercion_site(&self) -> &hir::Expr {
1365         &self.body
1366     }
1367 }