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