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