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