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