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::{Diverges, FnCtxt};
66 use rustc::hir::def_id::DefId;
67 use rustc::infer::{Coercion, InferResult, InferOk};
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,
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;
79 use syntax::feature_gate;
83 use std::collections::VecDeque;
86 struct Coerce<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
87 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
88 cause: ObligationCause<'tcx>,
92 impl<'a, 'gcx, 'tcx> Deref for Coerce<'a, 'gcx, 'tcx> {
93 type Target = FnCtxt<'a, 'gcx, 'tcx>;
94 fn deref(&self) -> &Self::Target {
99 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
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),
112 fn identity(_: Ty) -> Vec<Adjustment> { vec![] }
114 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
115 move |target| vec![Adjustment { kind, target }]
118 fn success<'tcx>(adj: Vec<Adjustment<'tcx>>,
120 obligations: traits::PredicateObligations<'tcx>)
121 -> CoerceResult<'tcx> {
123 value: (adj, target),
128 impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> {
129 fn new(fcx: &'f FnCtxt<'f, 'gcx, 'tcx>, cause: ObligationCause<'tcx>) -> Self {
137 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
138 self.commit_if_ok(|_| {
140 self.at(&self.cause, self.fcx.param_env)
143 self.at(&self.cause, self.fcx.param_env)
145 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
150 /// Unify two types (using sub or lub) and produce a specific coercion.
151 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F)
152 -> CoerceResult<'tcx>
153 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
155 self.unify(&a, &b).and_then(|InferOk { value: ty, obligations }| {
156 success(f(ty), ty, obligations)
160 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
161 let a = self.shallow_resolve(a);
162 debug!("Coerce.tys({:?} => {:?})", a, b);
164 // Just ignore error types.
165 if a.references_error() || b.references_error() {
166 return success(vec![], b, vec![]);
170 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
171 // type variable, we want `?T` to fallback to `!` if not
172 // otherwise constrained. An example where this arises:
174 // let _: Option<?T> = Some({ return; });
176 // here, we would coerce from `!` to `?T`.
177 let b = self.shallow_resolve(b);
178 return if self.shallow_resolve(b).is_ty_var() {
179 // micro-optimization: no need for this if `b` is
180 // already resolved in some way.
181 let diverging_ty = self.next_diverging_ty_var(
182 TypeVariableOrigin::AdjustmentType(self.cause.span));
183 self.unify_and(&b, &diverging_ty, simple(Adjust::NeverToAny))
185 success(simple(Adjust::NeverToAny)(b), b, vec![])
189 // Consider coercing the subtype to a DST
191 // NOTE: this is wrapped in a `commit_if_ok` because it creates
192 // a "spurious" type variable, and we don't want to have that
193 // type variable in memory if the coercion fails.
194 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
196 debug!("coerce: unsize successful");
199 debug!("coerce: unsize failed");
201 // Examine the supertype and consider auto-borrowing.
203 // Note: does not attempt to resolve type variables we encounter.
204 // See above for details.
206 ty::TyRawPtr(mt_b) => {
207 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
210 ty::TyRef(r_b, mt_b) => {
211 return self.coerce_borrowed_pointer(a, b, r_b, mt_b);
219 // Function items are coercible to any closure
220 // type; function pointers are not (that would
221 // require double indirection).
222 // Additionally, we permit coercion of function
223 // items to drop the unsafe qualifier.
224 self.coerce_from_fn_item(a, b)
226 ty::TyFnPtr(a_f) => {
227 // We permit coercion of fn pointers to drop the
229 self.coerce_from_fn_pointer(a, a_f, b)
231 ty::TyClosure(def_id_a, substs_a) => {
232 // Non-capturing closures are coercible to
234 self.coerce_closure_to_fn(a, def_id_a, substs_a, b)
237 // Otherwise, just use unification rules.
238 self.unify_and(a, b, identity)
243 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
244 /// To match `A` with `B`, autoderef will be performed,
245 /// calling `deref`/`deref_mut` where necessary.
246 fn coerce_borrowed_pointer(&self,
249 r_b: ty::Region<'tcx>,
250 mt_b: TypeAndMut<'tcx>)
251 -> CoerceResult<'tcx> {
253 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
255 // If we have a parameter of type `&M T_a` and the value
256 // provided is `expr`, we will be adding an implicit borrow,
257 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
258 // to type check, we will construct the type that `&M*expr` would
261 let (r_a, mt_a) = match a.sty {
262 ty::TyRef(r_a, mt_a) => {
263 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
266 _ => return self.unify_and(a, b, identity),
269 let span = self.cause.span;
271 let mut first_error = None;
272 let mut r_borrow_var = None;
273 let mut autoderef = self.autoderef(span, a);
274 let mut found = None;
276 for (referent_ty, autoderefs) in autoderef.by_ref() {
278 // Don't let this pass, otherwise it would cause
279 // &T to autoref to &&T.
283 // At this point, we have deref'd `a` to `referent_ty`. So
284 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
285 // In the autoderef loop for `&'a mut Vec<T>`, we would get
288 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
289 // - `Vec<T>` -- 1 deref
290 // - `[T]` -- 2 deref
292 // At each point after the first callback, we want to
293 // check to see whether this would match out target type
294 // (`&'b mut [T]`) if we autoref'd it. We can't just
295 // compare the referent types, though, because we still
296 // have to consider the mutability. E.g., in the case
297 // we've been considering, we have an `&mut` reference, so
298 // the `T` in `[T]` needs to be unified with equality.
300 // Therefore, we construct reference types reflecting what
301 // the types will be after we do the final auto-ref and
302 // compare those. Note that this means we use the target
303 // mutability [1], since it may be that we are coercing
304 // from `&mut T` to `&U`.
306 // One fine point concerns the region that we use. We
307 // choose the region such that the region of the final
308 // type that results from `unify` will be the region we
309 // want for the autoref:
311 // - if in sub mode, that means we want to use `'b` (the
312 // region from the target reference) for both
313 // pointers [2]. This is because sub mode (somewhat
314 // arbitrarily) returns the subtype region. In the case
315 // where we are coercing to a target type, we know we
316 // want to use that target type region (`'b`) because --
317 // for the program to type-check -- it must be the
318 // smaller of the two.
319 // - One fine point. It may be surprising that we can
320 // use `'b` without relating `'a` and `'b`. The reason
321 // that this is ok is that what we produce is
322 // effectively a `&'b *x` expression (if you could
323 // annotate the region of a borrow), and regionck has
324 // code that adds edges from the region of a borrow
325 // (`'b`, here) into the regions in the borrowed
326 // expression (`*x`, here). (Search for "link".)
327 // - if in lub mode, things can get fairly complicated. The
328 // easiest thing is just to make a fresh
329 // region variable [4], which effectively means we defer
330 // the decision to region inference (and regionck, which will add
331 // some more edges to this variable). However, this can wind up
332 // creating a crippling number of variables in some cases --
333 // e.g. #32278 -- so we optimize one particular case [3].
334 // Let me try to explain with some examples:
335 // - The "running example" above represents the simple case,
336 // where we have one `&` reference at the outer level and
337 // ownership all the rest of the way down. In this case,
338 // we want `LUB('a, 'b)` as the resulting region.
339 // - However, if there are nested borrows, that region is
340 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
341 // `&'b T`. In this case, `'a` is actually irrelevant.
342 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
343 // we get spurious errors (`run-pass/regions-lub-ref-ref-rc.rs`).
344 // (The errors actually show up in borrowck, typically, because
345 // this extra edge causes the region `'a` to be inferred to something
346 // too big, which then results in borrowck errors.)
347 // - We could track the innermost shared reference, but there is already
348 // code in regionck that has the job of creating links between
349 // the region of a borrow and the regions in the thing being
350 // borrowed (here, `'a` and `'x`), and it knows how to handle
351 // all the various cases. So instead we just make a region variable
352 // and let regionck figure it out.
353 let r = if !self.use_lub {
355 } else if autoderefs == 1 {
358 if r_borrow_var.is_none() {
359 // create var lazilly, at most once
360 let coercion = Coercion(span);
361 let r = self.next_region_var(coercion);
362 r_borrow_var = Some(r); // [4] above
364 r_borrow_var.unwrap()
366 let derefd_ty_a = self.tcx.mk_ref(r,
369 mutbl: mt_b.mutbl, // [1] above
371 match self.unify(derefd_ty_a, b) {
377 if first_error.is_none() {
378 first_error = Some(err);
384 // Extract type or return an error. We return the first error
385 // we got, which should be from relating the "base" type
386 // (e.g., in example above, the failure from relating `Vec<T>`
387 // to the target type), since that should be the least
389 let InferOk { value: ty, mut obligations } = match found {
392 let err = first_error.expect("coerce_borrowed_pointer had no error");
393 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
398 if ty == a && mt_a.mutbl == hir::MutImmutable && autoderef.step_count() == 1 {
399 // As a special case, if we would produce `&'a *x`, that's
400 // a total no-op. We end up with the type `&'a T` just as
401 // we started with. In that case, just skip it
402 // altogether. This is just an optimization.
404 // Note that for `&mut`, we DO want to reborrow --
405 // otherwise, this would be a move, which might be an
406 // error. For example `foo(self.x)` where `self` and
407 // `self.x` both have `&mut `type would be a move of
408 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
409 // which is a borrow.
410 assert_eq!(mt_b.mutbl, hir::MutImmutable); // can only coerce &T -> &U
411 return success(vec![], ty, obligations);
414 let pref = LvaluePreference::from_mutbl(mt_b.mutbl);
415 let InferOk { value: mut adjustments, obligations: o }
416 = autoderef.adjust_steps_as_infer_ok(pref);
417 obligations.extend(o);
418 obligations.extend(autoderef.into_obligations());
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),
426 adjustments.push(Adjustment {
427 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mt_b.mutbl)),
431 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}",
435 success(adjustments, ty, obligations)
439 // &[T; n] or &mut [T; n] -> &[T]
440 // or &mut [T; n] -> &mut [T]
441 // or &Concrete -> &Trait, etc.
442 fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
443 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
445 let traits = (self.tcx.lang_items().unsize_trait(),
446 self.tcx.lang_items().coerce_unsized_trait());
447 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
450 debug!("Missing Unsize or CoerceUnsized traits");
451 return Err(TypeError::Mismatch);
454 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
455 // a DST unless we have to. This currently comes out in the wash since
456 // we can't unify [T] with U. But to properly support DST, we need to allow
457 // that, at which point we will need extra checks on the target here.
459 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
460 let reborrow = match (&source.sty, &target.sty) {
461 (&ty::TyRef(_, mt_a), &ty::TyRef(_, mt_b)) => {
462 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
464 let coercion = Coercion(self.cause.span);
465 let r_borrow = self.next_region_var(coercion);
467 kind: Adjust::Deref(None),
470 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mt_b.mutbl)),
471 target: self.tcx.mk_ref(r_borrow, ty::TypeAndMut {
477 (&ty::TyRef(_, mt_a), &ty::TyRawPtr(mt_b)) => {
478 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
481 kind: Adjust::Deref(None),
484 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b.mutbl)),
485 target: self.tcx.mk_ptr(ty::TypeAndMut {
493 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
495 // Setup either a subtyping or a LUB relationship between
496 // the `CoerceUnsized` target type and the expected type.
497 // We only have the latter, so we use an inference variable
498 // for the former and let type inference do the rest.
499 let origin = TypeVariableOrigin::MiscVariable(self.cause.span);
500 let coerce_target = self.next_ty_var(origin);
501 let mut coercion = self.unify_and(coerce_target, target, |target| {
502 let unsize = Adjustment {
503 kind: Adjust::Unsize,
507 None => vec![unsize],
508 Some((ref deref, ref autoref)) => {
509 vec![deref.clone(), autoref.clone(), unsize]
514 let mut selcx = traits::SelectionContext::new(self);
516 // Use a FIFO queue for this custom fulfillment procedure.
517 let mut queue = VecDeque::new();
519 // Create an obligation for `Source: CoerceUnsized<Target>`.
520 let cause = ObligationCause::misc(self.cause.span, self.body_id);
521 queue.push_back(self.tcx.predicate_for_trait_def(self.fcx.param_env,
528 let mut has_unsized_tuple_coercion = false;
530 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
531 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
532 // inference might unify those two inner type variables later.
533 let traits = [coerce_unsized_did, unsize_did];
534 while let Some(obligation) = queue.pop_front() {
535 debug!("coerce_unsized resolve step: {:?}", obligation);
536 let trait_ref = match obligation.predicate {
537 ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => {
538 if unsize_did == tr.def_id() {
539 if let ty::TyTuple(..) = tr.0.input_types().nth(1).unwrap().sty {
540 debug!("coerce_unsized: found unsized tuple coercion");
541 has_unsized_tuple_coercion = true;
547 coercion.obligations.push(obligation);
551 match selcx.select(&obligation.with(trait_ref)) {
552 // Uncertain or unimplemented.
554 Err(traits::Unimplemented) => {
555 debug!("coerce_unsized: early return - can't prove obligation");
556 return Err(TypeError::Mismatch);
559 // Object safety violations or miscellaneous.
561 self.report_selection_error(&obligation, &err);
562 // Treat this like an obligation and follow through
563 // with the unsizing - the lack of a coercion should
564 // be silent, as it causes a type mismatch later.
567 Ok(Some(vtable)) => {
568 for obligation in vtable.nested_obligations() {
569 queue.push_back(obligation);
575 if has_unsized_tuple_coercion && !self.tcx.sess.features.borrow().unsized_tuple_coercion {
576 feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
577 "unsized_tuple_coercion",
579 feature_gate::GateIssue::Language,
580 feature_gate::EXPLAIN_UNSIZED_TUPLE_COERCION);
586 fn coerce_from_safe_fn<F, G>(&self,
588 fn_ty_a: ty::PolyFnSig<'tcx>,
592 -> CoerceResult<'tcx>
593 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
594 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
596 if let ty::TyFnPtr(fn_ty_b) = b.sty {
597 match (fn_ty_a.unsafety(), fn_ty_b.unsafety()) {
598 (hir::Unsafety::Normal, hir::Unsafety::Unsafe) => {
599 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
600 return self.unify_and(unsafe_a, b, to_unsafe);
605 self.unify_and(a, b, normal)
608 fn coerce_from_fn_pointer(&self,
610 fn_ty_a: ty::PolyFnSig<'tcx>,
612 -> CoerceResult<'tcx> {
613 //! Attempts to coerce from the type of a Rust function item
614 //! into a closure or a `proc`.
617 let b = self.shallow_resolve(b);
618 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
620 self.coerce_from_safe_fn(a, fn_ty_a, b,
621 simple(Adjust::UnsafeFnPointer), identity)
624 fn coerce_from_fn_item(&self,
627 -> CoerceResult<'tcx> {
628 //! Attempts to coerce from the type of a Rust function item
629 //! into a closure or a `proc`.
632 let b = self.shallow_resolve(b);
633 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
637 let a_sig = a.fn_sig(self.tcx);
638 let InferOk { value: a_sig, mut obligations } =
639 self.normalize_associated_types_in_as_infer_ok(self.cause.span, &a_sig);
641 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
642 let InferOk { value, obligations: o2 } =
643 self.coerce_from_safe_fn(a_fn_pointer, a_sig, b,
644 simple(Adjust::ReifyFnPointer), simple(Adjust::ReifyFnPointer))?;
646 obligations.extend(o2);
647 Ok(InferOk { value, obligations })
649 _ => self.unify_and(a, b, identity),
653 fn coerce_closure_to_fn(&self,
656 substs_a: ClosureSubsts<'tcx>,
658 -> CoerceResult<'tcx> {
659 //! Attempts to coerce from the type of a non-capturing closure
660 //! into a function pointer.
663 let b = self.shallow_resolve(b);
665 let node_id_a = self.tcx.hir.as_local_node_id(def_id_a).unwrap();
667 ty::TyFnPtr(_) if self.tcx.with_freevars(node_id_a, |v| v.is_empty()) => {
668 // We coerce the closure, which has fn type
669 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
671 // `fn(arg0,arg1,...) -> _`
672 let sig = self.fn_sig(def_id_a).subst(self.tcx, substs_a.substs);
673 let converted_sig = sig.map_bound(|s| {
674 let params_iter = match s.inputs()[0].sty {
675 ty::TyTuple(params, _) => {
676 params.into_iter().cloned()
684 hir::Unsafety::Normal,
688 let pointer_ty = self.tcx.mk_fn_ptr(converted_sig);
689 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})",
691 self.unify_and(pointer_ty, b, simple(Adjust::ClosureFnPointer))
693 _ => self.unify_and(a, b, identity),
697 fn coerce_unsafe_ptr(&self,
700 mutbl_b: hir::Mutability)
701 -> CoerceResult<'tcx> {
702 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
704 let (is_ref, mt_a) = match a.sty {
705 ty::TyRef(_, mt) => (true, mt),
706 ty::TyRawPtr(mt) => (false, mt),
708 return self.unify_and(a, b, identity);
712 // Check that the types which they point at are compatible.
713 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut {
717 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
718 // Although references and unsafe ptrs have the same
719 // representation, we still register an Adjust::DerefRef so that
720 // regionck knows that the region for `a` must be valid here.
722 self.unify_and(a_unsafe, b, |target| {
724 kind: Adjust::Deref(None),
727 kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
731 } else if mt_a.mutbl != mutbl_b {
732 self.unify_and(a_unsafe, b, simple(Adjust::MutToConstPointer))
734 self.unify_and(a_unsafe, b, identity)
739 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
740 /// Attempt to coerce an expression to a type, and return the
741 /// adjusted type of the expression, if successful.
742 /// Adjustments are only recorded if the coercion succeeded.
743 /// The expressions *must not* have any pre-existing adjustments.
744 pub fn try_coerce(&self,
747 expr_diverges: Diverges,
749 -> RelateResult<'tcx, Ty<'tcx>> {
750 let source = self.resolve_type_vars_with_obligations(expr_ty);
751 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
753 // Special-ish case: we can coerce any type `T` into the `!`
754 // type, but only if the source expression diverges.
755 if target.is_never() && expr_diverges.always() {
756 debug!("permit coercion to `!` because expr diverges");
760 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
761 let coerce = Coerce::new(self, cause);
762 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
764 let (adjustments, _) = self.register_infer_ok_obligations(ok);
765 self.apply_adjustments(expr, adjustments);
769 /// Same as `try_coerce()`, but without side-effects.
770 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
771 let source = self.resolve_type_vars_with_obligations(expr_ty);
772 debug!("coercion::can({:?} -> {:?})", source, target);
774 let cause = self.cause(syntax_pos::DUMMY_SP, ObligationCauseCode::ExprAssignable);
775 let coerce = Coerce::new(self, cause);
776 self.probe(|_| coerce.coerce(source, target)).is_ok()
779 /// Given some expressions, their known unified type and another expression,
780 /// tries to unify the types, potentially inserting coercions on any of the
781 /// provided expressions and returns their LUB (aka "common supertype").
783 /// This is really an internal helper. From outside the coercion
784 /// module, you should instantiate a `CoerceMany` instance.
785 fn try_find_coercion_lub<E>(&self,
786 cause: &ObligationCause<'tcx>,
791 new_diverges: Diverges)
792 -> RelateResult<'tcx, Ty<'tcx>>
793 where E: AsCoercionSite
795 let prev_ty = self.resolve_type_vars_with_obligations(prev_ty);
796 let new_ty = self.resolve_type_vars_with_obligations(new_ty);
797 debug!("coercion::try_find_coercion_lub({:?}, {:?})", prev_ty, new_ty);
799 // Special-ish case: we can coerce any type `T` into the `!`
800 // type, but only if the source expression diverges.
801 if prev_ty.is_never() && new_diverges.always() {
802 debug!("permit coercion to `!` because expr diverges");
806 // Special-case that coercion alone cannot handle:
807 // Two function item types of differing IDs or Substs.
808 if let (&ty::TyFnDef(..), &ty::TyFnDef(..)) = (&prev_ty.sty, &new_ty.sty) {
809 // Don't reify if the function types have a LUB, i.e. they
810 // are the same function and their parameters have a LUB.
811 let lub_ty = self.commit_if_ok(|_| {
812 self.at(cause, self.param_env)
813 .lub(prev_ty, new_ty)
814 }).map(|ok| self.register_infer_ok_obligations(ok));
817 // We have a LUB of prev_ty and new_ty, just return it.
821 // The signature must match.
822 let a_sig = prev_ty.fn_sig(self.tcx);
823 let a_sig = self.normalize_associated_types_in(new.span, &a_sig);
824 let b_sig = new_ty.fn_sig(self.tcx);
825 let b_sig = self.normalize_associated_types_in(new.span, &b_sig);
826 let sig = self.at(cause, self.param_env)
827 .trace(prev_ty, new_ty)
829 .map(|ok| self.register_infer_ok_obligations(ok))?;
831 // Reify both sides and return the reified fn pointer type.
832 let fn_ptr = self.tcx.mk_fn_ptr(sig);
833 for expr in exprs.iter().map(|e| e.as_coercion_site()).chain(Some(new)) {
834 // The only adjustment that can produce an fn item is
835 // `NeverToAny`, so this should always be valid.
836 self.apply_adjustments(expr, vec![Adjustment {
837 kind: Adjust::ReifyFnPointer,
844 let mut coerce = Coerce::new(self, cause.clone());
845 coerce.use_lub = true;
847 // First try to coerce the new expression to the type of the previous ones,
848 // but only if the new expression has no coercion already applied to it.
849 let mut first_error = None;
850 if !self.tables.borrow().adjustments().contains_key(new.hir_id) {
851 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
854 let (adjustments, target) = self.register_infer_ok_obligations(ok);
855 self.apply_adjustments(new, adjustments);
858 Err(e) => first_error = Some(e),
862 // Then try to coerce the previous expressions to the type of the new one.
863 // This requires ensuring there are no coercions applied to *any* of the
864 // previous expressions, other than noop reborrows (ignoring lifetimes).
866 let expr = expr.as_coercion_site();
867 let noop = match self.tables.borrow().expr_adjustments(expr) {
869 Adjustment { kind: Adjust::Deref(_), .. },
870 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }
872 match self.node_ty(expr.hir_id).sty {
873 ty::TyRef(_, mt_orig) => {
874 // Reborrow that we can safely ignore, because
875 // the next adjustment can only be a Deref
876 // which will be merged into it.
877 mutbl_adj == mt_orig.mutbl
882 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
887 return self.commit_if_ok(|_| {
888 self.at(cause, self.param_env)
889 .lub(prev_ty, new_ty)
890 }).map(|ok| self.register_infer_ok_obligations(ok));
894 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
896 // Avoid giving strange errors on failed attempts.
897 if let Some(e) = first_error {
900 self.commit_if_ok(|_| {
901 self.at(cause, self.param_env)
902 .lub(prev_ty, new_ty)
903 }).map(|ok| self.register_infer_ok_obligations(ok))
907 let (adjustments, target) = self.register_infer_ok_obligations(ok);
909 let expr = expr.as_coercion_site();
910 self.apply_adjustments(expr, adjustments.clone());
918 /// CoerceMany encapsulates the pattern you should use when you have
919 /// many expressions that are all getting coerced to a common
920 /// type. This arises, for example, when you have a match (the result
921 /// of each arm is coerced to a common type). It also arises in less
922 /// obvious places, such as when you have many `break foo` expressions
923 /// that target the same loop, or the various `return` expressions in
926 /// The basic protocol is as follows:
928 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
929 /// This will also serve as the "starting LUB". The expectation is
930 /// that this type is something which all of the expressions *must*
931 /// be coercible to. Use a fresh type variable if needed.
932 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
933 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
934 /// unit. This happens for example if you have a `break` with no expression,
935 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
936 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
937 /// from you so that you don't have to worry your pretty head about it.
938 /// But if an error is reported, the final type will be `err`.
939 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
940 /// previously coerced expressions.
941 /// - When all done, invoke `complete()`. This will return the LUB of
942 /// all your expressions.
943 /// - WARNING: I don't believe this final type is guaranteed to be
944 /// related to your initial `expected_ty` in any particular way,
945 /// although it will typically be a subtype, so you should check it.
946 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
947 /// previously coerced expressions.
952 /// let mut coerce = CoerceMany::new(expected_ty);
953 /// for expr in exprs {
954 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
955 /// coerce.coerce(fcx, &cause, expr, expr_ty);
957 /// let final_ty = coerce.complete(fcx);
959 pub struct CoerceMany<'gcx, 'tcx, 'exprs, E>
960 where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
962 expected_ty: Ty<'tcx>,
963 final_ty: Option<Ty<'tcx>>,
964 expressions: Expressions<'gcx, 'exprs, E>,
968 /// The type of a `CoerceMany` that is storing up the expressions into
969 /// a buffer. We use this in `check/mod.rs` for things like `break`.
970 pub type DynamicCoerceMany<'gcx, 'tcx> = CoerceMany<'gcx, 'tcx, 'gcx, P<hir::Expr>>;
972 enum Expressions<'gcx, 'exprs, E>
973 where E: 'exprs + AsCoercionSite,
975 Dynamic(Vec<&'gcx hir::Expr>),
976 UpFront(&'exprs [E]),
979 impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E>
980 where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
982 /// The usual case; collect the set of expressions dynamically.
983 /// If the full set of coercion sites is known before hand,
984 /// consider `with_coercion_sites()` instead to avoid allocation.
985 pub fn new(expected_ty: Ty<'tcx>) -> Self {
986 Self::make(expected_ty, Expressions::Dynamic(vec![]))
989 /// As an optimization, you can create a `CoerceMany` with a
990 /// pre-existing slice of expressions. In this case, you are
991 /// expected to pass each element in the slice to `coerce(...)` in
992 /// order. This is used with arrays in particular to avoid
993 /// needlessly cloning the slice.
994 pub fn with_coercion_sites(expected_ty: Ty<'tcx>,
995 coercion_sites: &'exprs [E])
997 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1000 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'gcx, 'exprs, E>) -> Self {
1009 /// Return the "expected type" with which this coercion was
1010 /// constructed. This represents the "downward propagated" type
1011 /// that was given to us at the start of typing whatever construct
1012 /// we are typing (e.g., the match expression).
1014 /// Typically, this is used as the expected type when
1015 /// type-checking each of the alternative expressions whose types
1016 /// we are trying to merge.
1017 pub fn expected_ty(&self) -> Ty<'tcx> {
1021 /// Returns the current "merged type", representing our best-guess
1022 /// at the LUB of the expressions we've seen so far (if any). This
1023 /// isn't *final* until you call `self.final()`, which will return
1024 /// the merged type.
1025 pub fn merged_ty(&self) -> Ty<'tcx> {
1026 self.final_ty.unwrap_or(self.expected_ty)
1029 /// Indicates that the value generated by `expression`, which is
1030 /// of type `expression_ty`, is one of the possibility that we
1031 /// could coerce from. This will record `expression` and later
1032 /// calls to `coerce` may come back and add adjustments and things
1034 pub fn coerce<'a>(&mut self,
1035 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1036 cause: &ObligationCause<'tcx>,
1037 expression: &'gcx hir::Expr,
1038 expression_ty: Ty<'tcx>,
1039 expression_diverges: Diverges)
1041 self.coerce_inner(fcx,
1045 expression_diverges,
1049 /// Indicates that one of the inputs is a "forced unit". This
1050 /// occurs in a case like `if foo { ... };`, where the missing else
1051 /// generates a "forced unit". Another example is a `loop { break;
1052 /// }`, where the `break` has no argument expression. We treat
1053 /// these cases slightly differently for error-reporting
1054 /// purposes. Note that these tend to correspond to cases where
1055 /// the `()` expression is implicit in the source, and hence we do
1056 /// not take an expression argument.
1058 /// The `augment_error` gives you a chance to extend the error
1059 /// message, in case any results (e.g., we use this to suggest
1060 /// removing a `;`).
1061 pub fn coerce_forced_unit<'a>(&mut self,
1062 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1063 cause: &ObligationCause<'tcx>,
1064 augment_error: &mut FnMut(&mut DiagnosticBuilder),
1065 label_unit_as_expected: bool)
1067 self.coerce_inner(fcx,
1072 Some(augment_error),
1073 label_unit_as_expected)
1076 /// The inner coercion "engine". If `expression` is `None`, this
1077 /// is a forced-unit case, and hence `expression_ty` must be
1079 fn coerce_inner<'a>(&mut self,
1080 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1081 cause: &ObligationCause<'tcx>,
1082 expression: Option<&'gcx hir::Expr>,
1083 mut expression_ty: Ty<'tcx>,
1084 expression_diverges: Diverges,
1085 augment_error: Option<&mut FnMut(&mut DiagnosticBuilder)>,
1086 label_expression_as_expected: bool)
1088 // Incorporate whatever type inference information we have
1089 // until now; in principle we might also want to process
1090 // pending obligations, but doing so should only improve
1091 // compatibility (hopefully that is true) by helping us
1092 // uncover never types better.
1093 if expression_ty.is_ty_var() {
1094 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1097 // If we see any error types, just propagate that error
1099 if expression_ty.references_error() || self.merged_ty().references_error() {
1100 self.final_ty = Some(fcx.tcx.types.err);
1104 // Handle the actual type unification etc.
1105 let result = if let Some(expression) = expression {
1106 if self.pushed == 0 {
1107 // Special-case the first expression we are coercing.
1108 // To be honest, I'm not entirely sure why we do this.
1109 fcx.try_coerce(expression, expression_ty, expression_diverges, self.expected_ty)
1111 match self.expressions {
1112 Expressions::Dynamic(ref exprs) =>
1113 fcx.try_find_coercion_lub(cause,
1118 expression_diverges),
1119 Expressions::UpFront(ref coercion_sites) =>
1120 fcx.try_find_coercion_lub(cause,
1121 &coercion_sites[0..self.pushed],
1125 expression_diverges),
1129 // this is a hack for cases where we default to `()` because
1130 // the expression etc has been omitted from the source. An
1131 // example is an `if let` without an else:
1133 // if let Some(x) = ... { }
1135 // we wind up with a second match arm that is like `_ =>
1136 // ()`. That is the case we are considering here. We take
1137 // a different path to get the right "expected, found"
1138 // message and so forth (and because we know that
1139 // `expression_ty` will be unit).
1141 // Another example is `break` with no argument expression.
1142 assert!(expression_ty.is_nil());
1143 assert!(expression_ty.is_nil(), "if let hack without unit type");
1144 fcx.at(cause, fcx.param_env)
1145 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1147 fcx.register_infer_ok_obligations(infer_ok);
1154 self.final_ty = Some(v);
1155 if let Some(e) = expression {
1156 match self.expressions {
1157 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1158 Expressions::UpFront(coercion_sites) => {
1159 // if the user gave us an array to validate, check that we got
1160 // the next expression in the list, as expected
1161 assert_eq!(coercion_sites[self.pushed].as_coercion_site().id, e.id);
1168 let (expected, found) = if label_expression_as_expected {
1169 // In the case where this is a "forced unit", like
1170 // `break`, we want to call the `()` "expected"
1171 // since it is implied by the syntax.
1172 // (Note: not all force-units work this way.)"
1173 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1175 // Otherwise, the "expected" type for error
1176 // reporting is the current unification type,
1177 // which is basically the LUB of the expressions
1178 // we've seen so far (combined with the expected
1180 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1185 ObligationCauseCode::ReturnNoExpression => {
1186 db = struct_span_err!(
1187 fcx.tcx.sess, cause.span, E0069,
1188 "`return;` in a function whose return type is not `()`");
1189 db.span_label(cause.span, "return type is not ()");
1191 ObligationCauseCode::BlockTailExpression(blk_id) => {
1192 db = fcx.report_mismatched_types(cause, expected, found, err);
1194 let expr = expression.unwrap_or_else(|| {
1195 span_bug!(cause.span,
1196 "supposed to be part of a block tail expression, but the \
1197 expression is empty");
1199 fcx.suggest_mismatched_types_on_tail(&mut db, expr,
1201 cause.span, blk_id);
1204 db = fcx.report_mismatched_types(cause, expected, found, err);
1208 if let Some(augment_error) = augment_error {
1209 augment_error(&mut db);
1214 self.final_ty = Some(fcx.tcx.types.err);
1219 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1220 if let Some(final_ty) = self.final_ty {
1223 // If we only had inputs that were of type `!` (or no
1224 // inputs at all), then the final type is `!`.
1225 assert_eq!(self.pushed, 0);
1231 /// Something that can be converted into an expression to which we can
1232 /// apply a coercion.
1233 pub trait AsCoercionSite {
1234 fn as_coercion_site(&self) -> &hir::Expr;
1237 impl AsCoercionSite for hir::Expr {
1238 fn as_coercion_site(&self) -> &hir::Expr {
1243 impl AsCoercionSite for P<hir::Expr> {
1244 fn as_coercion_site(&self) -> &hir::Expr {
1249 impl<'a, T> AsCoercionSite for &'a T
1250 where T: AsCoercionSite
1252 fn as_coercion_site(&self) -> &hir::Expr {
1253 (**self).as_coercion_site()
1257 impl AsCoercionSite for ! {
1258 fn as_coercion_site(&self) -> &hir::Expr {
1263 impl AsCoercionSite for hir::Arm {
1264 fn as_coercion_site(&self) -> &hir::Expr {