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.
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.
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).
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.
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
36 //! fn foo<A>(a: A, b: A) { ... }
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.
46 //! However, right now, if the user manually specifies the
47 //! values for the type variables, as so:
49 //! foo::<&int>(@1, @2)
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.
63 use check::{autoderef, FnCtxt, UnresolvedTypeAction};
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;
73 use std::cell::RefCell;
74 use std::collections::VecDeque;
77 struct Coerce<'a, 'tcx: 'a> {
78 fcx: &'a FnCtxt<'a, 'tcx>,
79 origin: infer::TypeOrigin,
80 unsizing_obligations: RefCell<Vec<traits::PredicateObligation<'tcx>>>,
83 type CoerceResult<'tcx> = RelateResult<'tcx, Option<ty::AutoAdjustment<'tcx>>>;
85 impl<'f, 'tcx> Coerce<'f, 'tcx> {
86 fn tcx(&self) -> &ty::ctxt<'tcx> {
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.
95 fn unpack_actual_value<T, F>(&self, a: Ty<'tcx>, f: F) -> T where
96 F: FnOnce(Ty<'tcx>) -> T,
98 f(self.fcx.infcx().shallow_resolve(a))
105 -> CoerceResult<'tcx> {
106 debug!("Coerce.tys({:?} => {:?})",
110 // Consider coercing the subtype to a DST
111 let unsize = self.unpack_actual_value(a, |a| {
112 self.coerce_unsized(a, b)
118 // Examine the supertype and consider auto-borrowing.
120 // Note: does not attempt to resolve type variables we encounter.
121 // See above for details.
123 ty::TyRawPtr(mt_b) => {
124 return self.unpack_actual_value(a, |a| {
125 self.coerce_unsafe_ptr(a, b, mt_b.mutbl)
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)
138 self.unpack_actual_value(a, |a| {
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)
146 ty::TyBareFn(None, a_f) => {
147 // We permit coercion of fn pointers to drop the
149 self.coerce_from_fn_pointer(a, a_f, b)
152 // Otherwise, just use subtyping rules.
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,
166 mutbl_b: hir::Mutability)
167 -> CoerceResult<'tcx> {
168 debug!("coerce_borrowed_pointer(a={:?}, b={:?})",
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
179 ty::TyRef(_, mt_a) => {
180 try!(coerce_mutbls(mt_a.mutbl, mutbl_b));
182 _ => return self.subtype(a, b)
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));
190 let lvalue_pref = LvaluePreference::from_mutbl(mutbl_b);
191 let mut first_error = None;
192 let (_, autoderefs, success) = autoderef(self.fcx,
196 UnresolvedTypeAction::Ignore,
198 |inner_ty, autoderef| {
200 // Don't let this pass, otherwise it would cause
201 // &T to autoref to &&T.
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);
218 Ok(Some(AdjustDerefRef(AutoDerefRef {
219 autoderefs: autoderefs,
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?"))
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,
239 -> CoerceResult<'tcx> {
240 debug!("coerce_unsized(source={:?}, target={:?})",
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 {
249 debug!("Missing Unsize or CoerceUnsized traits");
250 return Err(TypeError::Mismatch);
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.
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));
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)))
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)))
274 let source = source.adjust_for_autoref(self.tcx(), reborrow);
276 let mut selcx = traits::SelectionContext::new(self.fcx.infcx());
278 // Use a FIFO queue for this custom fulfillment procedure.
279 let mut queue = VecDeque::new();
280 let mut leftover_predicates = vec![];
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(),
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()) => {
302 leftover_predicates.push(obligation);
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);
313 // Object safety violations or miscellaneous.
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.
321 Ok(Some(vtable)) => {
322 for obligation in vtable.nested_obligations() {
323 queue.push_back(obligation);
329 let mut obligations = self.unsizing_obligations.borrow_mut();
330 assert!(obligations.is_empty());
331 *obligations = leftover_predicates;
333 let adjustment = AutoDerefRef {
334 autoderefs: if reborrow.is_some() { 1 } else { 0 },
338 debug!("Success, coerced with {:?}", adjustment);
339 Ok(Some(AdjustDerefRef(adjustment)))
342 fn coerce_from_fn_pointer(&self,
344 fn_ty_a: &'tcx ty::BareFnTy<'tcx>,
346 -> CoerceResult<'tcx>
349 * Attempts to coerce from the type of a Rust function item
350 * into a closure or a `proc`.
353 self.unpack_actual_value(b, |b| {
354 debug!("coerce_from_fn_pointer(a={:?}, b={:?})",
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));
371 fn coerce_from_fn_item(&self,
373 fn_ty_a: &'tcx ty::BareFnTy<'tcx>,
375 -> CoerceResult<'tcx> {
377 * Attempts to coerce from the type of a Rust function item
378 * into a closure or a `proc`.
381 self.unpack_actual_value(b, |b| {
382 debug!("coerce_from_fn_item(a={:?}, b={:?})",
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))
391 _ => self.subtype(a, b)
396 fn coerce_unsafe_ptr(&self,
399 mutbl_b: hir::Mutability)
400 -> CoerceResult<'tcx> {
401 debug!("coerce_unsafe_ptr(a={:?}, b={:?})",
405 let (is_ref, mt_a) = match a.sty {
406 ty::TyRef(_, mt) => (true, mt),
407 ty::TyRawPtr(mt) => (false, mt),
409 return self.subtype(a, b);
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));
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.
422 Ok(Some(AdjustDerefRef(AutoDerefRef {
424 autoref: Some(ty::AutoUnsafe(mutbl_b)),
433 pub fn mk_assignty<'a, 'tcx>(fcx: &FnCtxt<'a, '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 {
444 origin: infer::ExprAssignable(expr.span),
445 unsizing_obligations: RefCell::new(vec![])
447 let adjustment = try!(coerce.coerce(expr, a, b));
448 unsizing_obligations = coerce.unsizing_obligations.into_inner();
453 if let Some(AdjustDerefRef(auto)) = adjustment {
454 if auto.unsize.is_some() {
455 for obligation in unsizing_obligations {
456 fcx.register_predicate(obligation);
461 if let Some(adjustment) = adjustment {
462 debug!("Success, coerced with {:?}", adjustment);
463 fcx.write_adjustment(expr.id, adjustment);
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)