]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/coercion.rs
d3a292676c5ef7f30b5ccfb607107f98f741e614
[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::{autoderef, FnCtxt, UnresolvedTypeAction};
64
65 use middle::infer::{self, Coercion};
66 use middle::traits::{self, ObligationCause};
67 use middle::traits::{predicate_for_trait_def, report_selection_error};
68 use middle::ty::{AutoDerefRef, AdjustDerefRef};
69 use middle::ty::{self, LvaluePreference, TypeAndMut, Ty, TypeError};
70 use middle::ty::relate::RelateResult;
71 use util::common::indent;
72
73 use std::cell::RefCell;
74 use std::collections::VecDeque;
75 use rustc_front::hir;
76
77 struct Coerce<'a, 'tcx: 'a> {
78     fcx: &'a FnCtxt<'a, 'tcx>,
79     origin: infer::TypeOrigin,
80     unsizing_obligations: RefCell<Vec<traits::PredicateObligation<'tcx>>>,
81 }
82
83 type CoerceResult<'tcx> = RelateResult<'tcx, Option<ty::AutoAdjustment<'tcx>>>;
84
85 impl<'f, 'tcx> Coerce<'f, 'tcx> {
86     fn tcx(&self) -> &ty::ctxt<'tcx> {
87         self.fcx.tcx()
88     }
89
90     fn subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
91         try!(self.fcx.infcx().sub_types(false, self.origin.clone(), a, b));
92         Ok(None) // No coercion required.
93     }
94
95     fn unpack_actual_value<T, F>(&self, a: Ty<'tcx>, f: F) -> T where
96         F: FnOnce(Ty<'tcx>) -> T,
97     {
98         f(self.fcx.infcx().shallow_resolve(a))
99     }
100
101     fn coerce(&self,
102               expr_a: &hir::Expr,
103               a: Ty<'tcx>,
104               b: Ty<'tcx>)
105               -> CoerceResult<'tcx> {
106         debug!("Coerce.tys({:?} => {:?})",
107                a,
108                b);
109
110         // Consider coercing the subtype to a DST
111         let unsize = self.unpack_actual_value(a, |a| {
112             self.coerce_unsized(a, b)
113         });
114         if unsize.is_ok() {
115             return unsize;
116         }
117
118         // Examine the supertype and consider auto-borrowing.
119         //
120         // Note: does not attempt to resolve type variables we encounter.
121         // See above for details.
122         match b.sty {
123             ty::TyRawPtr(mt_b) => {
124                 return self.unpack_actual_value(a, |a| {
125                     self.coerce_unsafe_ptr(a, b, mt_b.mutbl)
126                 });
127             }
128
129             ty::TyRef(_, mt_b) => {
130                 return self.unpack_actual_value(a, |a| {
131                     self.coerce_borrowed_pointer(expr_a, a, b, mt_b.mutbl)
132                 });
133             }
134
135             _ => {}
136         }
137
138         self.unpack_actual_value(a, |a| {
139             match a.sty {
140                 ty::TyBareFn(Some(_), a_f) => {
141                     // Function items are coercible to any closure
142                     // type; function pointers are not (that would
143                     // require double indirection).
144                     self.coerce_from_fn_item(a, a_f, b)
145                 }
146                 ty::TyBareFn(None, a_f) => {
147                     // We permit coercion of fn pointers to drop the
148                     // unsafe qualifier.
149                     self.coerce_from_fn_pointer(a, a_f, b)
150                 }
151                 _ => {
152                     // Otherwise, just use subtyping rules.
153                     self.subtype(a, b)
154                 }
155             }
156         })
157     }
158
159     /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
160     /// To match `A` with `B`, autoderef will be performed,
161     /// calling `deref`/`deref_mut` where necessary.
162     fn coerce_borrowed_pointer(&self,
163                                expr_a: &hir::Expr,
164                                a: Ty<'tcx>,
165                                b: Ty<'tcx>,
166                                mutbl_b: hir::Mutability)
167                                -> CoerceResult<'tcx> {
168         debug!("coerce_borrowed_pointer(a={:?}, b={:?})",
169                a,
170                b);
171
172         // If we have a parameter of type `&M T_a` and the value
173         // provided is `expr`, we will be adding an implicit borrow,
174         // meaning that we convert `f(expr)` to `f(&M *expr)`.  Therefore,
175         // to type check, we will construct the type that `&M*expr` would
176         // yield.
177
178         match a.sty {
179             ty::TyRef(_, mt_a) => {
180                 try!(coerce_mutbls(mt_a.mutbl, mutbl_b));
181             }
182             _ => return self.subtype(a, b)
183         }
184
185         let coercion = Coercion(self.origin.span());
186         let r_borrow = self.fcx.infcx().next_region_var(coercion);
187         let r_borrow = self.tcx().mk_region(r_borrow);
188         let autoref = Some(ty::AutoPtr(r_borrow, mutbl_b));
189
190         let lvalue_pref = LvaluePreference::from_mutbl(mutbl_b);
191         let mut first_error = None;
192         let (_, autoderefs, success) = autoderef(self.fcx,
193                                                  expr_a.span,
194                                                  a,
195                                                  Some(expr_a),
196                                                  UnresolvedTypeAction::Ignore,
197                                                  lvalue_pref,
198                                                  |inner_ty, autoderef| {
199             if autoderef == 0 {
200                 // Don't let this pass, otherwise it would cause
201                 // &T to autoref to &&T.
202                 return None;
203             }
204             let ty = self.tcx().mk_ref(r_borrow,
205                                         TypeAndMut {ty: inner_ty, mutbl: mutbl_b});
206             if let Err(err) = self.subtype(ty, b) {
207                 if first_error.is_none() {
208                     first_error = Some(err);
209                 }
210                 None
211             } else {
212                 Some(())
213             }
214         });
215
216         match success {
217             Some(_) => {
218                 Ok(Some(AdjustDerefRef(AutoDerefRef {
219                     autoderefs: autoderefs,
220                     autoref: autoref,
221                     unsize: None
222                 })))
223             }
224             None => {
225                 // Return original error as if overloaded deref was never
226                 // attempted, to avoid irrelevant/confusing error messages.
227                 Err(first_error.expect("coerce_borrowed_pointer failed with no error?"))
228             }
229         }
230     }
231
232
233     // &[T; n] or &mut [T; n] -> &[T]
234     // or &mut [T; n] -> &mut [T]
235     // or &Concrete -> &Trait, etc.
236     fn coerce_unsized(&self,
237                       source: Ty<'tcx>,
238                       target: Ty<'tcx>)
239                       -> CoerceResult<'tcx> {
240         debug!("coerce_unsized(source={:?}, target={:?})",
241                source,
242                target);
243
244         let traits = (self.tcx().lang_items.unsize_trait(),
245                       self.tcx().lang_items.coerce_unsized_trait());
246         let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
247             (u, cu)
248         } else {
249             debug!("Missing Unsize or CoerceUnsized traits");
250             return Err(TypeError::Mismatch);
251         };
252
253         // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
254         // a DST unless we have to. This currently comes out in the wash since
255         // we can't unify [T] with U. But to properly support DST, we need to allow
256         // that, at which point we will need extra checks on the target here.
257
258         // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
259         let (source, reborrow) = match (&source.sty, &target.sty) {
260             (&ty::TyRef(_, mt_a), &ty::TyRef(_, mt_b)) => {
261                 try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl));
262
263                 let coercion = Coercion(self.origin.span());
264                 let r_borrow = self.fcx.infcx().next_region_var(coercion);
265                 let region = self.tcx().mk_region(r_borrow);
266                 (mt_a.ty, Some(ty::AutoPtr(region, mt_b.mutbl)))
267             }
268             (&ty::TyRef(_, mt_a), &ty::TyRawPtr(mt_b)) => {
269                 try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl));
270                 (mt_a.ty, Some(ty::AutoUnsafe(mt_b.mutbl)))
271             }
272             _ => (source, None)
273         };
274         let source = source.adjust_for_autoref(self.tcx(), reborrow);
275
276         let mut selcx = traits::SelectionContext::new(self.fcx.infcx());
277
278         // Use a FIFO queue for this custom fulfillment procedure.
279         let mut queue = VecDeque::new();
280         let mut leftover_predicates = vec![];
281
282         // Create an obligation for `Source: CoerceUnsized<Target>`.
283         let cause = ObligationCause::misc(self.origin.span(), self.fcx.body_id);
284         queue.push_back(predicate_for_trait_def(self.tcx(),
285                                                 cause,
286                                                 coerce_unsized_did,
287                                                 0,
288                                                 source,
289                                                 vec![target]));
290
291         // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
292         // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
293         // inference might unify those two inner type variables later.
294         let traits = [coerce_unsized_did, unsize_did];
295         while let Some(obligation) = queue.pop_front() {
296             debug!("coerce_unsized resolve step: {:?}", obligation);
297             let trait_ref =  match obligation.predicate {
298                 ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => {
299                     tr.clone()
300                 }
301                 _ => {
302                     leftover_predicates.push(obligation);
303                     continue;
304                 }
305             };
306             match selcx.select(&obligation.with(trait_ref)) {
307                 // Uncertain or unimplemented.
308                 Ok(None) | Err(traits::Unimplemented) => {
309                     debug!("coerce_unsized: early return - can't prove obligation");
310                     return Err(TypeError::Mismatch);
311                 }
312
313                 // Object safety violations or miscellaneous.
314                 Err(err) => {
315                     report_selection_error(self.fcx.infcx(), &obligation, &err);
316                     // Treat this like an obligation and follow through
317                     // with the unsizing - the lack of a coercion should
318                     // be silent, as it causes a type mismatch later.
319                 }
320
321                 Ok(Some(vtable)) => {
322                     for obligation in vtable.nested_obligations() {
323                         queue.push_back(obligation);
324                     }
325                 }
326             }
327         }
328
329         let mut obligations = self.unsizing_obligations.borrow_mut();
330         assert!(obligations.is_empty());
331         *obligations = leftover_predicates;
332
333         let adjustment = AutoDerefRef {
334             autoderefs: if reborrow.is_some() { 1 } else { 0 },
335             autoref: reborrow,
336             unsize: Some(target)
337         };
338         debug!("Success, coerced with {:?}", adjustment);
339         Ok(Some(AdjustDerefRef(adjustment)))
340     }
341
342     fn coerce_from_fn_pointer(&self,
343                            a: Ty<'tcx>,
344                            fn_ty_a: &'tcx ty::BareFnTy<'tcx>,
345                            b: Ty<'tcx>)
346                            -> CoerceResult<'tcx>
347     {
348         /*!
349          * Attempts to coerce from the type of a Rust function item
350          * into a closure or a `proc`.
351          */
352
353         self.unpack_actual_value(b, |b| {
354             debug!("coerce_from_fn_pointer(a={:?}, b={:?})",
355                    a, b);
356
357             if let ty::TyBareFn(None, fn_ty_b) = b.sty {
358                 match (fn_ty_a.unsafety, fn_ty_b.unsafety) {
359                     (hir::Unsafety::Normal, hir::Unsafety::Unsafe) => {
360                         let unsafe_a = self.tcx().safe_to_unsafe_fn_ty(fn_ty_a);
361                         try!(self.subtype(unsafe_a, b));
362                         return Ok(Some(ty::AdjustUnsafeFnPointer));
363                     }
364                     _ => {}
365                 }
366             }
367             self.subtype(a, b)
368         })
369     }
370
371     fn coerce_from_fn_item(&self,
372                            a: Ty<'tcx>,
373                            fn_ty_a: &'tcx ty::BareFnTy<'tcx>,
374                            b: Ty<'tcx>)
375                            -> CoerceResult<'tcx> {
376         /*!
377          * Attempts to coerce from the type of a Rust function item
378          * into a closure or a `proc`.
379          */
380
381         self.unpack_actual_value(b, |b| {
382             debug!("coerce_from_fn_item(a={:?}, b={:?})",
383                    a, b);
384
385             match b.sty {
386                 ty::TyBareFn(None, _) => {
387                     let a_fn_pointer = self.tcx().mk_fn(None, fn_ty_a);
388                     try!(self.subtype(a_fn_pointer, b));
389                     Ok(Some(ty::AdjustReifyFnPointer))
390                 }
391                 _ => self.subtype(a, b)
392             }
393         })
394     }
395
396     fn coerce_unsafe_ptr(&self,
397                          a: Ty<'tcx>,
398                          b: Ty<'tcx>,
399                          mutbl_b: hir::Mutability)
400                          -> CoerceResult<'tcx> {
401         debug!("coerce_unsafe_ptr(a={:?}, b={:?})",
402                a,
403                b);
404
405         let (is_ref, mt_a) = match a.sty {
406             ty::TyRef(_, mt) => (true, mt),
407             ty::TyRawPtr(mt) => (false, mt),
408             _ => {
409                 return self.subtype(a, b);
410             }
411         };
412
413         // Check that the types which they point at are compatible.
414         let a_unsafe = self.tcx().mk_ptr(ty::TypeAndMut{ mutbl: mutbl_b, ty: mt_a.ty });
415         try!(self.subtype(a_unsafe, b));
416         try!(coerce_mutbls(mt_a.mutbl, mutbl_b));
417
418         // Although references and unsafe ptrs have the same
419         // representation, we still register an AutoDerefRef so that
420         // regionck knows that the region for `a` must be valid here.
421         if is_ref {
422             Ok(Some(AdjustDerefRef(AutoDerefRef {
423                 autoderefs: 1,
424                 autoref: Some(ty::AutoUnsafe(mutbl_b)),
425                 unsize: None
426             })))
427         } else {
428             Ok(None)
429         }
430     }
431 }
432
433 pub fn mk_assignty<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
434                              expr: &hir::Expr,
435                              a: Ty<'tcx>,
436                              b: Ty<'tcx>)
437                              -> RelateResult<'tcx, ()> {
438     debug!("mk_assignty({:?} -> {:?})", a, b);
439     let mut unsizing_obligations = vec![];
440     let adjustment = try!(indent(|| {
441         fcx.infcx().commit_if_ok(|_| {
442             let coerce = Coerce {
443                 fcx: fcx,
444                 origin: infer::ExprAssignable(expr.span),
445                 unsizing_obligations: RefCell::new(vec![])
446             };
447             let adjustment = try!(coerce.coerce(expr, a, b));
448             unsizing_obligations = coerce.unsizing_obligations.into_inner();
449             Ok(adjustment)
450         })
451     }));
452
453     if let Some(AdjustDerefRef(auto)) = adjustment {
454         if auto.unsize.is_some() {
455             for obligation in unsizing_obligations {
456                 fcx.register_predicate(obligation);
457             }
458         }
459     }
460
461     if let Some(adjustment) = adjustment {
462         debug!("Success, coerced with {:?}", adjustment);
463         fcx.write_adjustment(expr.id, adjustment);
464     }
465     Ok(())
466 }
467
468 fn coerce_mutbls<'tcx>(from_mutbl: hir::Mutability,
469                        to_mutbl: hir::Mutability)
470                        -> CoerceResult<'tcx> {
471     match (from_mutbl, to_mutbl) {
472         (hir::MutMutable, hir::MutMutable) |
473         (hir::MutImmutable, hir::MutImmutable) |
474         (hir::MutMutable, hir::MutImmutable) => Ok(None),
475         (hir::MutImmutable, hir::MutMutable) => Err(TypeError::Mutability)
476     }
477 }