]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/coercion.rs
Auto merge of #48630 - alexcrichton:more-sccache, r=kennytm
[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::lint;
70 use rustc::traits::{self, ObligationCause, ObligationCauseCode};
71 use rustc::ty::adjustment::{Adjustment, Adjust, AutoBorrow, AutoBorrowMutability};
72 use rustc::ty::{self, TypeAndMut, Ty, ClosureSubsts};
73 use rustc::ty::fold::TypeFoldable;
74 use rustc::ty::error::TypeError;
75 use rustc::ty::relate::RelateResult;
76 use errors::DiagnosticBuilder;
77 use syntax::feature_gate;
78 use syntax::ptr::P;
79 use syntax_pos;
80
81 use std::collections::VecDeque;
82 use std::ops::Deref;
83
84 struct Coerce<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
85     fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
86     cause: ObligationCause<'tcx>,
87     use_lub: bool,
88 }
89
90 impl<'a, 'gcx, 'tcx> Deref for Coerce<'a, 'gcx, 'tcx> {
91     type Target = FnCtxt<'a, 'gcx, 'tcx>;
92     fn deref(&self) -> &Self::Target {
93         &self.fcx
94     }
95 }
96
97 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
98
99 fn coerce_mutbls<'tcx>(from_mutbl: hir::Mutability,
100                        to_mutbl: hir::Mutability)
101                        -> RelateResult<'tcx, ()> {
102     match (from_mutbl, to_mutbl) {
103         (hir::MutMutable, hir::MutMutable) |
104         (hir::MutImmutable, hir::MutImmutable) |
105         (hir::MutMutable, hir::MutImmutable) => Ok(()),
106         (hir::MutImmutable, hir::MutMutable) => Err(TypeError::Mutability),
107     }
108 }
109
110 fn identity(_: Ty) -> Vec<Adjustment> { vec![] }
111
112 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
113     move |target| vec![Adjustment { kind, target }]
114 }
115
116 fn success<'tcx>(adj: Vec<Adjustment<'tcx>>,
117                  target: Ty<'tcx>,
118                  obligations: traits::PredicateObligations<'tcx>)
119                  -> CoerceResult<'tcx> {
120     Ok(InferOk {
121         value: (adj, target),
122         obligations
123     })
124 }
125
126 impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> {
127     fn new(fcx: &'f FnCtxt<'f, 'gcx, 'tcx>, cause: ObligationCause<'tcx>) -> Self {
128         Coerce {
129             fcx,
130             cause,
131             use_lub: false,
132         }
133     }
134
135     fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
136         self.commit_if_ok(|_| {
137             if self.use_lub {
138                 self.at(&self.cause, self.fcx.param_env)
139                     .lub(b, a)
140             } else {
141                 self.at(&self.cause, self.fcx.param_env)
142                     .sup(b, a)
143                     .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
144             }
145         })
146     }
147
148     /// Unify two types (using sub or lub) and produce a specific coercion.
149     fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F)
150                     -> CoerceResult<'tcx>
151         where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
152     {
153         self.unify(&a, &b).and_then(|InferOk { value: ty, obligations }| {
154             success(f(ty), ty, obligations)
155         })
156     }
157
158     fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
159         let a = self.shallow_resolve(a);
160         debug!("Coerce.tys({:?} => {:?})", a, b);
161
162         // Just ignore error types.
163         if a.references_error() || b.references_error() {
164             return success(vec![], b, vec![]);
165         }
166
167         if a.is_never() {
168             // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
169             // type variable, we want `?T` to fallback to `!` if not
170             // otherwise constrained. An example where this arises:
171             //
172             //     let _: Option<?T> = Some({ return; });
173             //
174             // here, we would coerce from `!` to `?T`.
175             let b = self.shallow_resolve(b);
176             return if self.shallow_resolve(b).is_ty_var() {
177                 // micro-optimization: no need for this if `b` is
178                 // already resolved in some way.
179                 let diverging_ty = self.next_diverging_ty_var(
180                     ty::UniverseIndex::ROOT,
181                     TypeVariableOrigin::AdjustmentType(self.cause.span));
182                 self.unify_and(&b, &diverging_ty, simple(Adjust::NeverToAny))
183             } else {
184                 success(simple(Adjust::NeverToAny)(b), b, vec![])
185             };
186         }
187
188         // Consider coercing the subtype to a DST
189         //
190         // NOTE: this is wrapped in a `commit_if_ok` because it creates
191         // a "spurious" type variable, and we don't want to have that
192         // type variable in memory if the coercion fails.
193         let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
194         if unsize.is_ok() {
195             debug!("coerce: unsize successful");
196             return unsize;
197         }
198         debug!("coerce: unsize failed");
199
200         // Examine the supertype and consider auto-borrowing.
201         //
202         // Note: does not attempt to resolve type variables we encounter.
203         // See above for details.
204         match b.sty {
205             ty::TyRawPtr(mt_b) => {
206                 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
207             }
208
209             ty::TyRef(r_b, mt_b) => {
210                 return self.coerce_borrowed_pointer(a, b, r_b, mt_b);
211             }
212
213             _ => {}
214         }
215
216         match a.sty {
217             ty::TyFnDef(..) => {
218                 // Function items are coercible to any closure
219                 // type; function pointers are not (that would
220                 // require double indirection).
221                 // Additionally, we permit coercion of function
222                 // items to drop the unsafe qualifier.
223                 self.coerce_from_fn_item(a, b)
224             }
225             ty::TyFnPtr(a_f) => {
226                 // We permit coercion of fn pointers to drop the
227                 // unsafe qualifier.
228                 self.coerce_from_fn_pointer(a, a_f, b)
229             }
230             ty::TyClosure(def_id_a, substs_a) => {
231                 // Non-capturing closures are coercible to
232                 // function pointers
233                 self.coerce_closure_to_fn(a, def_id_a, substs_a, b)
234             }
235             _ => {
236                 // Otherwise, just use unification rules.
237                 self.unify_and(a, b, identity)
238             }
239         }
240     }
241
242     /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
243     /// To match `A` with `B`, autoderef will be performed,
244     /// calling `deref`/`deref_mut` where necessary.
245     fn coerce_borrowed_pointer(&self,
246                                a: Ty<'tcx>,
247                                b: Ty<'tcx>,
248                                r_b: ty::Region<'tcx>,
249                                mt_b: TypeAndMut<'tcx>)
250                                -> CoerceResult<'tcx> {
251
252         debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
253
254         // If we have a parameter of type `&M T_a` and the value
255         // provided is `expr`, we will be adding an implicit borrow,
256         // meaning that we convert `f(expr)` to `f(&M *expr)`.  Therefore,
257         // to type check, we will construct the type that `&M*expr` would
258         // yield.
259
260         let (r_a, mt_a) = match a.sty {
261             ty::TyRef(r_a, mt_a) => {
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(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::TyRef(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                 // Deref-coercion is a case where we deliberately
429                 // disallow two-phase borrows in its initial
430                 // deployment; see discussion on PR #47489.
431                 allow_two_phase_borrow: false,
432             }
433         };
434         adjustments.push(Adjustment {
435             kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
436             target: ty
437         });
438
439         debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}",
440                ty,
441                adjustments);
442
443         success(adjustments, ty, obligations)
444     }
445
446
447     // &[T; n] or &mut [T; n] -> &[T]
448     // or &mut [T; n] -> &mut [T]
449     // or &Concrete -> &Trait, etc.
450     fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
451         debug!("coerce_unsized(source={:?}, target={:?})", source, target);
452
453         let traits = (self.tcx.lang_items().unsize_trait(),
454                       self.tcx.lang_items().coerce_unsized_trait());
455         let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
456             (u, cu)
457         } else {
458             debug!("Missing Unsize or CoerceUnsized traits");
459             return Err(TypeError::Mismatch);
460         };
461
462         // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
463         // a DST unless we have to. This currently comes out in the wash since
464         // we can't unify [T] with U. But to properly support DST, we need to allow
465         // that, at which point we will need extra checks on the target here.
466
467         // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
468         let reborrow = match (&source.sty, &target.sty) {
469             (&ty::TyRef(_, mt_a), &ty::TyRef(_, mt_b)) => {
470                 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
471
472                 let coercion = Coercion(self.cause.span);
473                 let r_borrow = self.next_region_var(coercion);
474                 let mutbl = match mt_b.mutbl {
475                     hir::MutImmutable => AutoBorrowMutability::Immutable,
476                     hir::MutMutable => AutoBorrowMutability::Mutable {
477                         allow_two_phase_borrow: false,
478                     }
479                 };
480                 Some((Adjustment {
481                     kind: Adjust::Deref(None),
482                     target: mt_a.ty
483                 }, Adjustment {
484                     kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
485                     target:  self.tcx.mk_ref(r_borrow, ty::TypeAndMut {
486                         mutbl: mt_b.mutbl,
487                         ty: mt_a.ty
488                     })
489                 }))
490             }
491             (&ty::TyRef(_, mt_a), &ty::TyRawPtr(mt_b)) => {
492                 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
493
494                 Some((Adjustment {
495                     kind: Adjust::Deref(None),
496                     target: mt_a.ty
497                 }, Adjustment {
498                     kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b.mutbl)),
499                     target:  self.tcx.mk_ptr(ty::TypeAndMut {
500                         mutbl: mt_b.mutbl,
501                         ty: mt_a.ty
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(ty::UniverseIndex::ROOT, origin);
515         let mut coercion = self.unify_and(coerce_target, target, |target| {
516             let unsize = Adjustment {
517                 kind: Adjust::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         // Use a FIFO queue for this custom fulfillment procedure.
531         let mut queue = VecDeque::new();
532
533         // Create an obligation for `Source: CoerceUnsized<Target>`.
534         let cause = ObligationCause::misc(self.cause.span, self.body_id);
535         queue.push_back(self.tcx.predicate_for_trait_def(self.fcx.param_env,
536                                                          cause,
537                                                          coerce_unsized_did,
538                                                          0,
539                                                          coerce_source,
540                                                          &[coerce_target]));
541
542         let mut has_unsized_tuple_coercion = false;
543
544         // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
545         // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
546         // inference might unify those two inner type variables later.
547         let traits = [coerce_unsized_did, unsize_did];
548         while let Some(obligation) = queue.pop_front() {
549             debug!("coerce_unsized resolve step: {:?}", obligation);
550             let trait_ref = match obligation.predicate {
551                 ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => {
552                     if unsize_did == tr.def_id() {
553                         if let ty::TyTuple(..) = tr.0.input_types().nth(1).unwrap().sty {
554                             debug!("coerce_unsized: found unsized tuple coercion");
555                             has_unsized_tuple_coercion = true;
556                         }
557                     }
558                     tr.clone()
559                 }
560                 _ => {
561                     coercion.obligations.push(obligation);
562                     continue;
563                 }
564             };
565             match selcx.select(&obligation.with(trait_ref)) {
566                 // Uncertain or unimplemented.
567                 Ok(None) |
568                 Err(traits::Unimplemented) => {
569                     debug!("coerce_unsized: early return - can't prove obligation");
570                     return Err(TypeError::Mismatch);
571                 }
572
573                 // Object safety violations or miscellaneous.
574                 Err(err) => {
575                     self.report_selection_error(&obligation, &err);
576                     // Treat this like an obligation and follow through
577                     // with the unsizing - the lack of a coercion should
578                     // be silent, as it causes a type mismatch later.
579                 }
580
581                 Ok(Some(vtable)) => {
582                     for obligation in vtable.nested_obligations() {
583                         queue.push_back(obligation);
584                     }
585                 }
586             }
587         }
588
589         if has_unsized_tuple_coercion && !self.tcx.sess.features.borrow().unsized_tuple_coercion {
590             feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
591                                            "unsized_tuple_coercion",
592                                            self.cause.span,
593                                            feature_gate::GateIssue::Language,
594                                            feature_gate::EXPLAIN_UNSIZED_TUPLE_COERCION);
595         }
596
597         Ok(coercion)
598     }
599
600     fn coerce_from_safe_fn<F, G>(&self,
601                                  a: Ty<'tcx>,
602                                  fn_ty_a: ty::PolyFnSig<'tcx>,
603                                  b: Ty<'tcx>,
604                                  to_unsafe: F,
605                                  normal: G)
606                                  -> CoerceResult<'tcx>
607         where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
608               G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
609     {
610         if let ty::TyFnPtr(fn_ty_b) = b.sty {
611             match (fn_ty_a.unsafety(), fn_ty_b.unsafety()) {
612                 (hir::Unsafety::Normal, hir::Unsafety::Unsafe) => {
613                     let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
614                     return self.unify_and(unsafe_a, b, to_unsafe);
615                 }
616                 _ => {}
617             }
618         }
619         self.unify_and(a, b, normal)
620     }
621
622     fn coerce_from_fn_pointer(&self,
623                               a: Ty<'tcx>,
624                               fn_ty_a: ty::PolyFnSig<'tcx>,
625                               b: Ty<'tcx>)
626                               -> CoerceResult<'tcx> {
627         //! Attempts to coerce from the type of a Rust function item
628         //! into a closure or a `proc`.
629         //!
630
631         let b = self.shallow_resolve(b);
632         debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
633
634         self.coerce_from_safe_fn(a, fn_ty_a, b,
635             simple(Adjust::UnsafeFnPointer), identity)
636     }
637
638     fn coerce_from_fn_item(&self,
639                            a: Ty<'tcx>,
640                            b: Ty<'tcx>)
641                            -> CoerceResult<'tcx> {
642         //! Attempts to coerce from the type of a Rust function item
643         //! into a closure or a `proc`.
644         //!
645
646         let b = self.shallow_resolve(b);
647         debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
648
649         match b.sty {
650             ty::TyFnPtr(_) => {
651                 let a_sig = a.fn_sig(self.tcx);
652                 let InferOk { value: a_sig, mut obligations } =
653                     self.normalize_associated_types_in_as_infer_ok(self.cause.span, &a_sig);
654
655                 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
656                 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
657                     a_fn_pointer,
658                     a_sig,
659                     b,
660                     |unsafe_ty| {
661                         vec![
662                             Adjustment { kind: Adjust::ReifyFnPointer, target: a_fn_pointer },
663                             Adjustment { kind: Adjust::UnsafeFnPointer, target: unsafe_ty },
664                         ]
665                     },
666                     simple(Adjust::ReifyFnPointer)
667                 )?;
668
669                 obligations.extend(o2);
670                 Ok(InferOk { value, obligations })
671             }
672             _ => self.unify_and(a, b, identity),
673         }
674     }
675
676     fn coerce_closure_to_fn(&self,
677                            a: Ty<'tcx>,
678                            def_id_a: DefId,
679                            substs_a: ClosureSubsts<'tcx>,
680                            b: Ty<'tcx>)
681                            -> CoerceResult<'tcx> {
682         //! Attempts to coerce from the type of a non-capturing closure
683         //! into a function pointer.
684         //!
685
686         let b = self.shallow_resolve(b);
687
688         let node_id_a = self.tcx.hir.as_local_node_id(def_id_a).unwrap();
689         match b.sty {
690             ty::TyFnPtr(_) if self.tcx.with_freevars(node_id_a, |v| v.is_empty()) => {
691                 // We coerce the closure, which has fn type
692                 //     `extern "rust-call" fn((arg0,arg1,...)) -> _`
693                 // to
694                 //     `fn(arg0,arg1,...) -> _`
695                 let sig = self.closure_sig(def_id_a, substs_a);
696                 let pointer_ty = self.tcx.coerce_closure_fn_ty(sig);
697                 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})",
698                        a, b, pointer_ty);
699                 self.unify_and(pointer_ty, b, simple(Adjust::ClosureFnPointer))
700             }
701             _ => self.unify_and(a, b, identity),
702         }
703     }
704
705     fn coerce_unsafe_ptr(&self,
706                          a: Ty<'tcx>,
707                          b: Ty<'tcx>,
708                          mutbl_b: hir::Mutability)
709                          -> CoerceResult<'tcx> {
710         debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
711
712         let (is_ref, mt_a) = match a.sty {
713             ty::TyRef(_, mt) => (true, mt),
714             ty::TyRawPtr(mt) => (false, mt),
715             _ => {
716                 return self.unify_and(a, b, identity);
717             }
718         };
719
720         // Check that the types which they point at are compatible.
721         let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut {
722             mutbl: mutbl_b,
723             ty: mt_a.ty,
724         });
725         coerce_mutbls(mt_a.mutbl, mutbl_b)?;
726         // Although references and unsafe ptrs have the same
727         // representation, we still register an Adjust::DerefRef so that
728         // regionck knows that the region for `a` must be valid here.
729         if is_ref {
730             self.unify_and(a_unsafe, b, |target| {
731                 vec![Adjustment {
732                     kind: Adjust::Deref(None),
733                     target: mt_a.ty
734                 }, Adjustment {
735                     kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
736                     target
737                 }]
738             })
739         } else if mt_a.mutbl != mutbl_b {
740             self.unify_and(a_unsafe, b, simple(Adjust::MutToConstPointer))
741         } else {
742             self.unify_and(a_unsafe, b, identity)
743         }
744     }
745 }
746
747 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
748     /// Attempt to coerce an expression to a type, and return the
749     /// adjusted type of the expression, if successful.
750     /// Adjustments are only recorded if the coercion succeeded.
751     /// The expressions *must not* have any pre-existing adjustments.
752     pub fn try_coerce(&self,
753                       expr: &hir::Expr,
754                       expr_ty: Ty<'tcx>,
755                       expr_diverges: Diverges,
756                       target: Ty<'tcx>)
757                       -> RelateResult<'tcx, Ty<'tcx>> {
758         let source = self.resolve_type_vars_with_obligations(expr_ty);
759         debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
760
761         // Special-ish case: we can coerce any type `T` into the `!`
762         // type, but only if the source expression diverges.
763         if target.is_never() && expr_diverges.always() {
764             debug!("permit coercion to `!` because expr diverges");
765             if self.can_eq(self.param_env, source, target).is_err() {
766                 self.tcx.lint_node(
767                     lint::builtin::COERCE_NEVER,
768                     expr.id,
769                     expr.span,
770                     &format!("cannot coerce `{}` to !", source)
771                 );
772                 return Ok(target);
773             }
774         }
775
776         let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
777         let coerce = Coerce::new(self, cause);
778         let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
779
780         let (adjustments, _) = self.register_infer_ok_obligations(ok);
781         self.apply_adjustments(expr, adjustments);
782         Ok(target)
783     }
784
785     /// Same as `try_coerce()`, but without side-effects.
786     pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
787         let source = self.resolve_type_vars_with_obligations(expr_ty);
788         debug!("coercion::can({:?} -> {:?})", source, target);
789
790         let cause = self.cause(syntax_pos::DUMMY_SP, ObligationCauseCode::ExprAssignable);
791         let coerce = Coerce::new(self, cause);
792         self.probe(|_| coerce.coerce(source, target)).is_ok()
793     }
794
795     /// Given some expressions, their known unified type and another expression,
796     /// tries to unify the types, potentially inserting coercions on any of the
797     /// provided expressions and returns their LUB (aka "common supertype").
798     ///
799     /// This is really an internal helper. From outside the coercion
800     /// module, you should instantiate a `CoerceMany` instance.
801     fn try_find_coercion_lub<E>(&self,
802                                 cause: &ObligationCause<'tcx>,
803                                 exprs: &[E],
804                                 prev_ty: Ty<'tcx>,
805                                 new: &hir::Expr,
806                                 new_ty: Ty<'tcx>,
807                                 new_diverges: Diverges)
808                                 -> RelateResult<'tcx, Ty<'tcx>>
809         where E: AsCoercionSite
810     {
811         let prev_ty = self.resolve_type_vars_with_obligations(prev_ty);
812         let new_ty = self.resolve_type_vars_with_obligations(new_ty);
813         debug!("coercion::try_find_coercion_lub({:?}, {:?})", prev_ty, new_ty);
814
815         // Special-ish case: we can coerce any type `T` into the `!`
816         // type, but only if the source expression diverges.
817         if prev_ty.is_never() && new_diverges.always() {
818             debug!("permit coercion to `!` because expr diverges");
819             return Ok(prev_ty);
820         }
821
822         // Special-case that coercion alone cannot handle:
823         // Two function item types of differing IDs or Substs.
824         if let (&ty::TyFnDef(..), &ty::TyFnDef(..)) = (&prev_ty.sty, &new_ty.sty) {
825             // Don't reify if the function types have a LUB, i.e. they
826             // are the same function and their parameters have a LUB.
827             let lub_ty = self.commit_if_ok(|_| {
828                 self.at(cause, self.param_env)
829                     .lub(prev_ty, new_ty)
830             }).map(|ok| self.register_infer_ok_obligations(ok));
831
832             if lub_ty.is_ok() {
833                 // We have a LUB of prev_ty and new_ty, just return it.
834                 return lub_ty;
835             }
836
837             // The signature must match.
838             let a_sig = prev_ty.fn_sig(self.tcx);
839             let a_sig = self.normalize_associated_types_in(new.span, &a_sig);
840             let b_sig = new_ty.fn_sig(self.tcx);
841             let b_sig = self.normalize_associated_types_in(new.span, &b_sig);
842             let sig = self.at(cause, self.param_env)
843                           .trace(prev_ty, new_ty)
844                           .lub(&a_sig, &b_sig)
845                           .map(|ok| self.register_infer_ok_obligations(ok))?;
846
847             // Reify both sides and return the reified fn pointer type.
848             let fn_ptr = self.tcx.mk_fn_ptr(sig);
849             for expr in exprs.iter().map(|e| e.as_coercion_site()).chain(Some(new)) {
850                 // The only adjustment that can produce an fn item is
851                 // `NeverToAny`, so this should always be valid.
852                 self.apply_adjustments(expr, vec![Adjustment {
853                     kind: Adjust::ReifyFnPointer,
854                     target: fn_ptr
855                 }]);
856             }
857             return Ok(fn_ptr);
858         }
859
860         let mut coerce = Coerce::new(self, cause.clone());
861         coerce.use_lub = true;
862
863         // First try to coerce the new expression to the type of the previous ones,
864         // but only if the new expression has no coercion already applied to it.
865         let mut first_error = None;
866         if !self.tables.borrow().adjustments().contains_key(new.hir_id) {
867             let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
868             match result {
869                 Ok(ok) => {
870                     let (adjustments, target) = self.register_infer_ok_obligations(ok);
871                     self.apply_adjustments(new, adjustments);
872                     return Ok(target);
873                 }
874                 Err(e) => first_error = Some(e),
875             }
876         }
877
878         // Then try to coerce the previous expressions to the type of the new one.
879         // This requires ensuring there are no coercions applied to *any* of the
880         // previous expressions, other than noop reborrows (ignoring lifetimes).
881         for expr in exprs {
882             let expr = expr.as_coercion_site();
883             let noop = match self.tables.borrow().expr_adjustments(expr) {
884                 &[
885                     Adjustment { kind: Adjust::Deref(_), .. },
886                     Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }
887                 ] => {
888                     match self.node_ty(expr.hir_id).sty {
889                         ty::TyRef(_, mt_orig) => {
890                             let mutbl_adj: hir::Mutability = mutbl_adj.into();
891                             // Reborrow that we can safely ignore, because
892                             // the next adjustment can only be a Deref
893                             // which will be merged into it.
894                             mutbl_adj == mt_orig.mutbl
895                         }
896                         _ => false,
897                     }
898                 }
899                 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
900                 _ => false,
901             };
902
903             if !noop {
904                 return self.commit_if_ok(|_| {
905                     self.at(cause, self.param_env)
906                         .lub(prev_ty, new_ty)
907                 }).map(|ok| self.register_infer_ok_obligations(ok));
908             }
909         }
910
911         match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
912             Err(_) => {
913                 // Avoid giving strange errors on failed attempts.
914                 if let Some(e) = first_error {
915                     Err(e)
916                 } else {
917                     self.commit_if_ok(|_| {
918                         self.at(cause, self.param_env)
919                             .lub(prev_ty, new_ty)
920                     }).map(|ok| self.register_infer_ok_obligations(ok))
921                 }
922             }
923             Ok(ok) => {
924                 let (adjustments, target) = self.register_infer_ok_obligations(ok);
925                 for expr in exprs {
926                     let expr = expr.as_coercion_site();
927                     self.apply_adjustments(expr, adjustments.clone());
928                 }
929                 Ok(target)
930             }
931         }
932     }
933 }
934
935 /// CoerceMany encapsulates the pattern you should use when you have
936 /// many expressions that are all getting coerced to a common
937 /// type. This arises, for example, when you have a match (the result
938 /// of each arm is coerced to a common type). It also arises in less
939 /// obvious places, such as when you have many `break foo` expressions
940 /// that target the same loop, or the various `return` expressions in
941 /// a function.
942 ///
943 /// The basic protocol is as follows:
944 ///
945 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
946 ///   This will also serve as the "starting LUB". The expectation is
947 ///   that this type is something which all of the expressions *must*
948 ///   be coercible to. Use a fresh type variable if needed.
949 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
950 ///   - In some cases we wish to coerce "non-expressions" whose types are implicitly
951 ///     unit. This happens for example if you have a `break` with no expression,
952 ///     or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
953 ///   - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
954 ///     from you so that you don't have to worry your pretty head about it.
955 ///     But if an error is reported, the final type will be `err`.
956 ///   - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
957 ///     previously coerced expressions.
958 /// - When all done, invoke `complete()`. This will return the LUB of
959 ///   all your expressions.
960 ///   - WARNING: I don't believe this final type is guaranteed to be
961 ///     related to your initial `expected_ty` in any particular way,
962 ///     although it will typically be a subtype, so you should check it.
963 ///   - Invoking `complete()` may cause us to go and adjust the "adjustments" on
964 ///     previously coerced expressions.
965 ///
966 /// Example:
967 ///
968 /// ```
969 /// let mut coerce = CoerceMany::new(expected_ty);
970 /// for expr in exprs {
971 ///     let expr_ty = fcx.check_expr_with_expectation(expr, expected);
972 ///     coerce.coerce(fcx, &cause, expr, expr_ty);
973 /// }
974 /// let final_ty = coerce.complete(fcx);
975 /// ```
976 pub struct CoerceMany<'gcx, 'tcx, 'exprs, E>
977     where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
978 {
979     expected_ty: Ty<'tcx>,
980     final_ty: Option<Ty<'tcx>>,
981     expressions: Expressions<'gcx, 'exprs, E>,
982     pushed: usize,
983 }
984
985 /// The type of a `CoerceMany` that is storing up the expressions into
986 /// a buffer. We use this in `check/mod.rs` for things like `break`.
987 pub type DynamicCoerceMany<'gcx, 'tcx> = CoerceMany<'gcx, 'tcx, 'gcx, P<hir::Expr>>;
988
989 enum Expressions<'gcx, 'exprs, E>
990     where E: 'exprs + AsCoercionSite,
991 {
992     Dynamic(Vec<&'gcx hir::Expr>),
993     UpFront(&'exprs [E]),
994 }
995
996 impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E>
997     where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
998 {
999     /// The usual case; collect the set of expressions dynamically.
1000     /// If the full set of coercion sites is known before hand,
1001     /// consider `with_coercion_sites()` instead to avoid allocation.
1002     pub fn new(expected_ty: Ty<'tcx>) -> Self {
1003         Self::make(expected_ty, Expressions::Dynamic(vec![]))
1004     }
1005
1006     /// As an optimization, you can create a `CoerceMany` with a
1007     /// pre-existing slice of expressions. In this case, you are
1008     /// expected to pass each element in the slice to `coerce(...)` in
1009     /// order. This is used with arrays in particular to avoid
1010     /// needlessly cloning the slice.
1011     pub fn with_coercion_sites(expected_ty: Ty<'tcx>,
1012                                coercion_sites: &'exprs [E])
1013                       -> Self {
1014         Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1015     }
1016
1017     fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'gcx, 'exprs, E>) -> Self {
1018         CoerceMany {
1019             expected_ty,
1020             final_ty: None,
1021             expressions,
1022             pushed: 0,
1023         }
1024     }
1025
1026     /// Return the "expected type" with which this coercion was
1027     /// constructed.  This represents the "downward propagated" type
1028     /// that was given to us at the start of typing whatever construct
1029     /// we are typing (e.g., the match expression).
1030     ///
1031     /// Typically, this is used as the expected type when
1032     /// type-checking each of the alternative expressions whose types
1033     /// we are trying to merge.
1034     pub fn expected_ty(&self) -> Ty<'tcx> {
1035         self.expected_ty
1036     }
1037
1038     /// Returns the current "merged type", representing our best-guess
1039     /// at the LUB of the expressions we've seen so far (if any). This
1040     /// isn't *final* until you call `self.final()`, which will return
1041     /// the merged type.
1042     pub fn merged_ty(&self) -> Ty<'tcx> {
1043         self.final_ty.unwrap_or(self.expected_ty)
1044     }
1045
1046     /// Indicates that the value generated by `expression`, which is
1047     /// of type `expression_ty`, is one of the possibility that we
1048     /// could coerce from. This will record `expression` and later
1049     /// calls to `coerce` may come back and add adjustments and things
1050     /// if necessary.
1051     pub fn coerce<'a>(&mut self,
1052                       fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1053                       cause: &ObligationCause<'tcx>,
1054                       expression: &'gcx hir::Expr,
1055                       expression_ty: Ty<'tcx>,
1056                       expression_diverges: Diverges)
1057     {
1058         self.coerce_inner(fcx,
1059                           cause,
1060                           Some(expression),
1061                           expression_ty,
1062                           expression_diverges,
1063                           None, false)
1064     }
1065
1066     /// Indicates that one of the inputs is a "forced unit". This
1067     /// occurs in a case like `if foo { ... };`, where the missing else
1068     /// generates a "forced unit". Another example is a `loop { break;
1069     /// }`, where the `break` has no argument expression. We treat
1070     /// these cases slightly differently for error-reporting
1071     /// purposes. Note that these tend to correspond to cases where
1072     /// the `()` expression is implicit in the source, and hence we do
1073     /// not take an expression argument.
1074     ///
1075     /// The `augment_error` gives you a chance to extend the error
1076     /// message, in case any results (e.g., we use this to suggest
1077     /// removing a `;`).
1078     pub fn coerce_forced_unit<'a>(&mut self,
1079                                   fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1080                                   cause: &ObligationCause<'tcx>,
1081                                   augment_error: &mut FnMut(&mut DiagnosticBuilder),
1082                                   label_unit_as_expected: bool)
1083     {
1084         self.coerce_inner(fcx,
1085                           cause,
1086                           None,
1087                           fcx.tcx.mk_nil(),
1088                           Diverges::Maybe,
1089                           Some(augment_error),
1090                           label_unit_as_expected)
1091     }
1092
1093     /// The inner coercion "engine". If `expression` is `None`, this
1094     /// is a forced-unit case, and hence `expression_ty` must be
1095     /// `Nil`.
1096     fn coerce_inner<'a>(&mut self,
1097                         fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1098                         cause: &ObligationCause<'tcx>,
1099                         expression: Option<&'gcx hir::Expr>,
1100                         mut expression_ty: Ty<'tcx>,
1101                         expression_diverges: Diverges,
1102                         augment_error: Option<&mut FnMut(&mut DiagnosticBuilder)>,
1103                         label_expression_as_expected: bool)
1104     {
1105         // Incorporate whatever type inference information we have
1106         // until now; in principle we might also want to process
1107         // pending obligations, but doing so should only improve
1108         // compatibility (hopefully that is true) by helping us
1109         // uncover never types better.
1110         if expression_ty.is_ty_var() {
1111             expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1112         }
1113
1114         // If we see any error types, just propagate that error
1115         // upwards.
1116         if expression_ty.references_error() || self.merged_ty().references_error() {
1117             self.final_ty = Some(fcx.tcx.types.err);
1118             return;
1119         }
1120
1121         // Handle the actual type unification etc.
1122         let result = if let Some(expression) = expression {
1123             if self.pushed == 0 {
1124                 // Special-case the first expression we are coercing.
1125                 // To be honest, I'm not entirely sure why we do this.
1126                 fcx.try_coerce(expression, expression_ty, expression_diverges, self.expected_ty)
1127             } else {
1128                 match self.expressions {
1129                     Expressions::Dynamic(ref exprs) =>
1130                         fcx.try_find_coercion_lub(cause,
1131                                                   exprs,
1132                                                   self.merged_ty(),
1133                                                   expression,
1134                                                   expression_ty,
1135                                                   expression_diverges),
1136                     Expressions::UpFront(ref coercion_sites) =>
1137                         fcx.try_find_coercion_lub(cause,
1138                                                   &coercion_sites[0..self.pushed],
1139                                                   self.merged_ty(),
1140                                                   expression,
1141                                                   expression_ty,
1142                                                   expression_diverges),
1143                 }
1144             }
1145         } else {
1146             // this is a hack for cases where we default to `()` because
1147             // the expression etc has been omitted from the source. An
1148             // example is an `if let` without an else:
1149             //
1150             //     if let Some(x) = ... { }
1151             //
1152             // we wind up with a second match arm that is like `_ =>
1153             // ()`.  That is the case we are considering here. We take
1154             // a different path to get the right "expected, found"
1155             // message and so forth (and because we know that
1156             // `expression_ty` will be unit).
1157             //
1158             // Another example is `break` with no argument expression.
1159             assert!(expression_ty.is_nil());
1160             assert!(expression_ty.is_nil(), "if let hack without unit type");
1161             fcx.at(cause, fcx.param_env)
1162                .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1163                .map(|infer_ok| {
1164                    fcx.register_infer_ok_obligations(infer_ok);
1165                    expression_ty
1166                })
1167         };
1168
1169         match result {
1170             Ok(v) => {
1171                 self.final_ty = Some(v);
1172                 if let Some(e) = expression {
1173                     match self.expressions {
1174                         Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1175                         Expressions::UpFront(coercion_sites) => {
1176                             // if the user gave us an array to validate, check that we got
1177                             // the next expression in the list, as expected
1178                             assert_eq!(coercion_sites[self.pushed].as_coercion_site().id, e.id);
1179                         }
1180                     }
1181                     self.pushed += 1;
1182                 }
1183             }
1184             Err(err) => {
1185                 let (expected, found) = if label_expression_as_expected {
1186                     // In the case where this is a "forced unit", like
1187                     // `break`, we want to call the `()` "expected"
1188                     // since it is implied by the syntax.
1189                     // (Note: not all force-units work this way.)"
1190                     (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1191                 } else {
1192                     // Otherwise, the "expected" type for error
1193                     // reporting is the current unification type,
1194                     // which is basically the LUB of the expressions
1195                     // we've seen so far (combined with the expected
1196                     // type)
1197                     (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1198                 };
1199
1200                 let mut db;
1201                 match cause.code {
1202                     ObligationCauseCode::ReturnNoExpression => {
1203                         db = struct_span_err!(
1204                             fcx.tcx.sess, cause.span, E0069,
1205                             "`return;` in a function whose return type is not `()`");
1206                         db.span_label(cause.span, "return type is not ()");
1207                     }
1208                     ObligationCauseCode::BlockTailExpression(blk_id) => {
1209                         db = fcx.report_mismatched_types(cause, expected, found, err);
1210
1211                         let expr = expression.unwrap_or_else(|| {
1212                             span_bug!(cause.span,
1213                                       "supposed to be part of a block tail expression, but the \
1214                                        expression is empty");
1215                         });
1216                         fcx.suggest_mismatched_types_on_tail(&mut db, expr,
1217                                                              expected, found,
1218                                                              cause.span, blk_id);
1219                     }
1220                     _ => {
1221                         db = fcx.report_mismatched_types(cause, expected, found, err);
1222                     }
1223                 }
1224
1225                 if let Some(augment_error) = augment_error {
1226                     augment_error(&mut db);
1227                 }
1228
1229                 db.emit();
1230
1231                 self.final_ty = Some(fcx.tcx.types.err);
1232             }
1233         }
1234     }
1235
1236     pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1237         if let Some(final_ty) = self.final_ty {
1238             final_ty
1239         } else {
1240             // If we only had inputs that were of type `!` (or no
1241             // inputs at all), then the final type is `!`.
1242             assert_eq!(self.pushed, 0);
1243             fcx.tcx.types.never
1244         }
1245     }
1246 }
1247
1248 /// Something that can be converted into an expression to which we can
1249 /// apply a coercion.
1250 pub trait AsCoercionSite {
1251     fn as_coercion_site(&self) -> &hir::Expr;
1252 }
1253
1254 impl AsCoercionSite for hir::Expr {
1255     fn as_coercion_site(&self) -> &hir::Expr {
1256         self
1257     }
1258 }
1259
1260 impl AsCoercionSite for P<hir::Expr> {
1261     fn as_coercion_site(&self) -> &hir::Expr {
1262         self
1263     }
1264 }
1265
1266 impl<'a, T> AsCoercionSite for &'a T
1267     where T: AsCoercionSite
1268 {
1269     fn as_coercion_site(&self) -> &hir::Expr {
1270         (**self).as_coercion_site()
1271     }
1272 }
1273
1274 impl AsCoercionSite for ! {
1275     fn as_coercion_site(&self) -> &hir::Expr {
1276         unreachable!()
1277     }
1278 }
1279
1280 impl AsCoercionSite for hir::Arm {
1281     fn as_coercion_site(&self) -> &hir::Expr {
1282         &self.body
1283     }
1284 }