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