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, 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,
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;
82 use std::collections::VecDeque;
85 struct Coerce<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
86 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
87 cause: ObligationCause<'tcx>,
91 impl<'a, 'gcx, 'tcx> Deref for Coerce<'a, 'gcx, 'tcx> {
92 type Target = FnCtxt<'a, 'gcx, 'tcx>;
93 fn deref(&self) -> &Self::Target {
98 type CoerceResult<'tcx> = InferResult<'tcx, Adjustment<'tcx>>;
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),
111 fn identity<'tcx>() -> Adjust<'tcx> {
119 fn success<'tcx>(kind: Adjust<'tcx>,
121 obligations: traits::PredicateObligations<'tcx>)
122 -> CoerceResult<'tcx> {
132 impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> {
133 fn new(fcx: &'f FnCtxt<'f, 'gcx, 'tcx>, cause: ObligationCause<'tcx>) -> Self {
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);
145 self.lub(false, trace, &a, &b)
147 self.sub(false, trace, &a, &b)
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)
164 -> CoerceResult<'tcx>
165 where E: AsCoercionSite
167 let a = self.shallow_resolve(a);
168 debug!("Coerce.tys({:?} => {:?})", a, b);
170 // Just ignore error types.
171 if a.references_error() || b.references_error() {
172 return success(identity(), b, vec![]);
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:
180 // let _: Option<?T> = Some({ return; });
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)
191 success(Adjust::NeverToAny, b, vec![])
195 // Consider coercing the subtype to a DST
196 let unsize = self.coerce_unsized(a, b);
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(exprs, a, b, r_b, mt_b);
218 ty::TyFnDef(.., a_f) => {
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, a_f, 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<E>(&self,
250 r_b: &'tcx ty::Region,
251 mt_b: TypeAndMut<'tcx>)
252 -> CoerceResult<'tcx>
253 where E: AsCoercionSite
256 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
258 // If we have a parameter of type `&M T_a` and the value
259 // provided is `expr`, we will be adding an implicit borrow,
260 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
261 // to type check, we will construct the type that `&M*expr` would
264 let (r_a, mt_a) = match a.sty {
265 ty::TyRef(r_a, mt_a) => {
266 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
269 _ => return self.unify_and(a, b, identity()),
272 let span = self.cause.span;
274 let mut first_error = None;
275 let mut r_borrow_var = None;
276 let mut autoderef = self.autoderef(span, a);
277 let mut found = None;
279 for (referent_ty, autoderefs) in autoderef.by_ref() {
281 // Don't let this pass, otherwise it would cause
282 // &T to autoref to &&T.
286 // At this point, we have deref'd `a` to `referent_ty`. So
287 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
288 // In the autoderef loop for `&'a mut Vec<T>`, we would get
291 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
292 // - `Vec<T>` -- 1 deref
293 // - `[T]` -- 2 deref
295 // At each point after the first callback, we want to
296 // check to see whether this would match out target type
297 // (`&'b mut [T]`) if we autoref'd it. We can't just
298 // compare the referent types, though, because we still
299 // have to consider the mutability. E.g., in the case
300 // we've been considering, we have an `&mut` reference, so
301 // the `T` in `[T]` needs to be unified with equality.
303 // Therefore, we construct reference types reflecting what
304 // the types will be after we do the final auto-ref and
305 // compare those. Note that this means we use the target
306 // mutability [1], since it may be that we are coercing
307 // from `&mut T` to `&U`.
309 // One fine point concerns the region that we use. We
310 // choose the region such that the region of the final
311 // type that results from `unify` will be the region we
312 // want for the autoref:
314 // - if in sub mode, that means we want to use `'b` (the
315 // region from the target reference) for both
316 // pointers [2]. This is because sub mode (somewhat
317 // arbitrarily) returns the subtype region. In the case
318 // where we are coercing to a target type, we know we
319 // want to use that target type region (`'b`) because --
320 // for the program to type-check -- it must be the
321 // smaller of the two.
322 // - One fine point. It may be surprising that we can
323 // use `'b` without relating `'a` and `'b`. The reason
324 // that this is ok is that what we produce is
325 // effectively a `&'b *x` expression (if you could
326 // annotate the region of a borrow), and regionck has
327 // code that adds edges from the region of a borrow
328 // (`'b`, here) into the regions in the borrowed
329 // expression (`*x`, here). (Search for "link".)
330 // - if in lub mode, things can get fairly complicated. The
331 // easiest thing is just to make a fresh
332 // region variable [4], which effectively means we defer
333 // the decision to region inference (and regionck, which will add
334 // some more edges to this variable). However, this can wind up
335 // creating a crippling number of variables in some cases --
336 // e.g. #32278 -- so we optimize one particular case [3].
337 // Let me try to explain with some examples:
338 // - The "running example" above represents the simple case,
339 // where we have one `&` reference at the outer level and
340 // ownership all the rest of the way down. In this case,
341 // we want `LUB('a, 'b)` as the resulting region.
342 // - However, if there are nested borrows, that region is
343 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
344 // `&'b T`. In this case, `'a` is actually irrelevant.
345 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
346 // we get spurious errors (`run-pass/regions-lub-ref-ref-rc.rs`).
347 // (The errors actually show up in borrowck, typically, because
348 // this extra edge causes the region `'a` to be inferred to something
349 // too big, which then results in borrowck errors.)
350 // - We could track the innermost shared reference, but there is already
351 // code in regionck that has the job of creating links between
352 // the region of a borrow and the regions in the thing being
353 // borrowed (here, `'a` and `'x`), and it knows how to handle
354 // all the various cases. So instead we just make a region variable
355 // and let regionck figure it out.
356 let r = if !self.use_lub {
358 } else if autoderefs == 1 {
361 if r_borrow_var.is_none() {
362 // create var lazilly, at most once
363 let coercion = Coercion(span);
364 let r = self.next_region_var(coercion);
365 r_borrow_var = Some(r); // [4] above
367 r_borrow_var.unwrap()
369 let derefd_ty_a = self.tcx.mk_ref(r,
372 mutbl: mt_b.mutbl, // [1] above
374 match self.unify(derefd_ty_a, b) {
376 found = Some((ok, autoderefs));
380 if first_error.is_none() {
381 first_error = Some(err);
387 // Extract type or return an error. We return the first error
388 // we got, which should be from relating the "base" type
389 // (e.g., in example above, the failure from relating `Vec<T>`
390 // to the target type), since that should be the least
392 let (InferOk { value: ty, mut obligations }, autoderefs) = match found {
395 let err = first_error.expect("coerce_borrowed_pointer had no error");
396 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
401 if ty == a && mt_a.mutbl == hir::MutImmutable && autoderefs == 1 {
402 // As a special case, if we would produce `&'a *x`, that's
403 // a total no-op. We end up with the type `&'a T` just as
404 // we started with. In that case, just skip it
405 // altogether. This is just an optimization.
407 // Note that for `&mut`, we DO want to reborrow --
408 // otherwise, this would be a move, which might be an
409 // error. For example `foo(self.x)` where `self` and
410 // `self.x` both have `&mut `type would be a move of
411 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
412 // which is a borrow.
413 assert_eq!(mt_b.mutbl, hir::MutImmutable); // can only coerce &T -> &U
414 return success(identity(), ty, obligations);
417 // Now apply the autoref. We have to extract the region out of
418 // the final ref type we got.
419 let r_borrow = match ty.sty {
420 ty::TyRef(r_borrow, _) => r_borrow,
421 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
423 let autoref = Some(AutoBorrow::Ref(r_borrow, mt_b.mutbl));
424 debug!("coerce_borrowed_pointer: succeeded ty={:?} autoderefs={:?} autoref={:?}",
429 let pref = LvaluePreference::from_mutbl(mt_b.mutbl);
430 obligations.extend(autoderef.finalize_as_infer_ok(pref, exprs).obligations);
432 success(Adjust::DerefRef {
433 autoderefs: autoderefs,
440 // &[T; n] or &mut [T; n] -> &[T]
441 // or &mut [T; n] -> &mut [T]
442 // or &Concrete -> &Trait, etc.
443 fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
444 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
446 let traits = (self.tcx.lang_items.unsize_trait(),
447 self.tcx.lang_items.coerce_unsized_trait());
448 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
451 debug!("Missing Unsize or CoerceUnsized traits");
452 return Err(TypeError::Mismatch);
455 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
456 // a DST unless we have to. This currently comes out in the wash since
457 // we can't unify [T] with U. But to properly support DST, we need to allow
458 // that, at which point we will need extra checks on the target here.
460 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
461 let (source, reborrow) = match (&source.sty, &target.sty) {
462 (&ty::TyRef(_, mt_a), &ty::TyRef(_, mt_b)) => {
463 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
465 let coercion = Coercion(self.cause.span);
466 let r_borrow = self.next_region_var(coercion);
467 (mt_a.ty, Some(AutoBorrow::Ref(r_borrow, mt_b.mutbl)))
469 (&ty::TyRef(_, mt_a), &ty::TyRawPtr(mt_b)) => {
470 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
471 (mt_a.ty, Some(AutoBorrow::RawPtr(mt_b.mutbl)))
475 let coerce_source = source.adjust_for_autoref(self.tcx, reborrow);
477 let adjust = Adjust::DerefRef {
478 autoderefs: if reborrow.is_some() { 1 } else { 0 },
483 // Setup either a subtyping or a LUB relationship between
484 // the `CoerceUnsized` target type and the expected type.
485 // We only have the latter, so we use an inference variable
486 // for the former and let type inference do the rest.
487 let origin = TypeVariableOrigin::MiscVariable(self.cause.span);
488 let coerce_target = self.next_ty_var(origin);
489 let mut coercion = self.unify_and(coerce_target, target, adjust)?;
491 let mut selcx = traits::SelectionContext::new(self);
493 // Use a FIFO queue for this custom fulfillment procedure.
494 let mut queue = VecDeque::new();
496 // Create an obligation for `Source: CoerceUnsized<Target>`.
497 let cause = ObligationCause::misc(self.cause.span, self.body_id);
498 queue.push_back(self.tcx
499 .predicate_for_trait_def(cause, coerce_unsized_did, 0,
500 coerce_source, &[coerce_target]));
502 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
503 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
504 // inference might unify those two inner type variables later.
505 let traits = [coerce_unsized_did, unsize_did];
506 while let Some(obligation) = queue.pop_front() {
507 debug!("coerce_unsized resolve step: {:?}", obligation);
508 let trait_ref = match obligation.predicate {
509 ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => tr.clone(),
511 coercion.obligations.push(obligation);
515 match selcx.select(&obligation.with(trait_ref)) {
516 // Uncertain or unimplemented.
518 Err(traits::Unimplemented) => {
519 debug!("coerce_unsized: early return - can't prove obligation");
520 return Err(TypeError::Mismatch);
523 // Object safety violations or miscellaneous.
525 self.report_selection_error(&obligation, &err);
526 // Treat this like an obligation and follow through
527 // with the unsizing - the lack of a coercion should
528 // be silent, as it causes a type mismatch later.
531 Ok(Some(vtable)) => {
532 for obligation in vtable.nested_obligations() {
533 queue.push_back(obligation);
542 fn coerce_from_safe_fn(&self,
544 fn_ty_a: ty::PolyFnSig<'tcx>,
546 to_unsafe: Adjust<'tcx>,
547 normal: Adjust<'tcx>)
548 -> CoerceResult<'tcx> {
549 if let ty::TyFnPtr(fn_ty_b) = b.sty {
550 match (fn_ty_a.unsafety(), fn_ty_b.unsafety()) {
551 (hir::Unsafety::Normal, hir::Unsafety::Unsafe) => {
552 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
553 return self.unify_and(unsafe_a, b, to_unsafe);
558 self.unify_and(a, b, normal)
561 fn coerce_from_fn_pointer(&self,
563 fn_ty_a: ty::PolyFnSig<'tcx>,
565 -> CoerceResult<'tcx> {
566 //! Attempts to coerce from the type of a Rust function item
567 //! into a closure or a `proc`.
570 let b = self.shallow_resolve(b);
571 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
573 self.coerce_from_safe_fn(a, fn_ty_a, b,
574 Adjust::UnsafeFnPointer, identity())
577 fn coerce_from_fn_item(&self,
579 fn_ty_a: ty::PolyFnSig<'tcx>,
581 -> CoerceResult<'tcx> {
582 //! Attempts to coerce from the type of a Rust function item
583 //! into a closure or a `proc`.
586 let b = self.shallow_resolve(b);
587 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
591 let a_fn_pointer = self.tcx.mk_fn_ptr(fn_ty_a);
592 self.coerce_from_safe_fn(a_fn_pointer, fn_ty_a, b,
593 Adjust::ReifyFnPointer, Adjust::ReifyFnPointer)
595 _ => self.unify_and(a, b, identity()),
599 fn coerce_closure_to_fn(&self,
602 substs_a: ClosureSubsts<'tcx>,
604 -> CoerceResult<'tcx> {
605 //! Attempts to coerce from the type of a non-capturing closure
606 //! into a function pointer.
609 let b = self.shallow_resolve(b);
611 let node_id_a = self.tcx.hir.as_local_node_id(def_id_a).unwrap();
613 ty::TyFnPtr(_) if self.tcx.with_freevars(node_id_a, |v| v.is_empty()) => {
614 if !self.tcx.sess.features.borrow().closure_to_fn_coercion {
615 feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
616 "closure_to_fn_coercion",
618 feature_gate::GateIssue::Language,
619 feature_gate::CLOSURE_TO_FN_COERCION);
620 return self.unify_and(a, b, identity());
622 // We coerce the closure, which has fn type
623 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
625 // `fn(arg0,arg1,...) -> _`
626 let sig = self.closure_type(def_id_a).subst(self.tcx, substs_a.substs);
627 let converted_sig = sig.map_bound(|s| {
628 let params_iter = match s.inputs()[0].sty {
629 ty::TyTuple(params, _) => {
630 params.into_iter().cloned()
638 hir::Unsafety::Normal,
642 let pointer_ty = self.tcx.mk_fn_ptr(converted_sig);
643 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})",
645 self.unify_and(pointer_ty, b, Adjust::ClosureFnPointer)
647 _ => self.unify_and(a, b, identity()),
651 fn coerce_unsafe_ptr(&self,
654 mutbl_b: hir::Mutability)
655 -> CoerceResult<'tcx> {
656 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
658 let (is_ref, mt_a) = match a.sty {
659 ty::TyRef(_, mt) => (true, mt),
660 ty::TyRawPtr(mt) => (false, mt),
662 return self.unify_and(a, b, identity());
666 // Check that the types which they point at are compatible.
667 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut {
671 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
672 // Although references and unsafe ptrs have the same
673 // representation, we still register an Adjust::DerefRef so that
674 // regionck knows that the region for `a` must be valid here.
675 self.unify_and(a_unsafe, b, if is_ref {
678 autoref: Some(AutoBorrow::RawPtr(mutbl_b)),
681 } else if mt_a.mutbl != mutbl_b {
682 Adjust::MutToConstPointer
689 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
690 /// Attempt to coerce an expression to a type, and return the
691 /// adjusted type of the expression, if successful.
692 /// Adjustments are only recorded if the coercion succeeded.
693 /// The expressions *must not* have any pre-existing adjustments.
694 pub fn try_coerce(&self,
697 expr_diverges: Diverges,
699 -> RelateResult<'tcx, Ty<'tcx>> {
700 let source = self.resolve_type_vars_with_obligations(expr_ty);
701 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
703 // Special-ish case: we can coerce any type `T` into the `!`
704 // type, but only if the source expression diverges.
705 if target.is_never() && expr_diverges.always() {
706 debug!("permit coercion to `!` because expr diverges");
710 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
711 let coerce = Coerce::new(self, cause);
712 self.commit_if_ok(|_| {
713 let ok = coerce.coerce(&[expr], source, target)?;
714 let adjustment = self.register_infer_ok_obligations(ok);
715 if !adjustment.is_identity() {
716 debug!("Success, coerced with {:?}", adjustment);
717 if self.tables.borrow().adjustments.get(&expr.id).is_some() {
718 bug!("expr already has an adjustment on it!");
720 self.write_adjustment(expr.id, adjustment);
723 // We should now have added sufficient adjustments etc to
724 // ensure that the type of expression, post-adjustment, is
725 // a subtype of target.
730 /// Given some expressions, their known unified type and another expression,
731 /// tries to unify the types, potentially inserting coercions on any of the
732 /// provided expressions and returns their LUB (aka "common supertype").
734 /// This is really an internal helper. From outside the coercion
735 /// module, you should instantiate a `CoerceMany` instance.
736 fn try_find_coercion_lub<E>(&self,
737 cause: &ObligationCause<'tcx>,
742 new_diverges: Diverges)
743 -> RelateResult<'tcx, Ty<'tcx>>
744 where E: AsCoercionSite
746 let prev_ty = self.resolve_type_vars_with_obligations(prev_ty);
747 let new_ty = self.resolve_type_vars_with_obligations(new_ty);
748 debug!("coercion::try_find_lub({:?}, {:?})", prev_ty, new_ty);
750 // Special-ish case: we can coerce any type `T` into the `!`
751 // type, but only if the source expression diverges.
752 if prev_ty.is_never() && new_diverges.always() {
753 debug!("permit coercion to `!` because expr diverges");
757 let trace = TypeTrace::types(cause, true, prev_ty, new_ty);
759 // Special-case that coercion alone cannot handle:
760 // Two function item types of differing IDs or Substs.
761 match (&prev_ty.sty, &new_ty.sty) {
762 (&ty::TyFnDef(a_def_id, a_substs, a_fty), &ty::TyFnDef(b_def_id, b_substs, b_fty)) => {
763 // The signature must always match.
764 let fty = self.lub(true, trace.clone(), &a_fty, &b_fty)
765 .map(|ok| self.register_infer_ok_obligations(ok))?;
767 if a_def_id == b_def_id {
768 // Same function, maybe the parameters match.
769 let substs = self.commit_if_ok(|_| {
770 self.lub(true, trace.clone(), &a_substs, &b_substs)
771 .map(|ok| self.register_infer_ok_obligations(ok))
774 if let Ok(substs) = substs {
775 // We have a LUB of prev_ty and new_ty, just return it.
776 return Ok(self.tcx.mk_fn_def(a_def_id, substs, fty));
780 // Reify both sides and return the reified fn pointer type.
781 let fn_ptr = self.tcx.mk_fn_ptr(fty);
782 for expr in exprs.iter().map(|e| e.as_coercion_site()).chain(Some(new)) {
783 // No adjustments can produce a fn item, so this should never trip.
784 assert!(!self.tables.borrow().adjustments.contains_key(&expr.id));
785 self.write_adjustment(expr.id, Adjustment {
786 kind: Adjust::ReifyFnPointer,
795 let mut coerce = Coerce::new(self, cause.clone());
796 coerce.use_lub = true;
798 // First try to coerce the new expression to the type of the previous ones,
799 // but only if the new expression has no coercion already applied to it.
800 let mut first_error = None;
801 if !self.tables.borrow().adjustments.contains_key(&new.id) {
802 let result = self.commit_if_ok(|_| coerce.coerce(&[new], new_ty, prev_ty));
805 let adjustment = self.register_infer_ok_obligations(ok);
806 if !adjustment.is_identity() {
807 self.write_adjustment(new.id, adjustment);
809 return Ok(adjustment.target);
811 Err(e) => first_error = Some(e),
815 // Then try to coerce the previous expressions to the type of the new one.
816 // This requires ensuring there are no coercions applied to *any* of the
817 // previous expressions, other than noop reborrows (ignoring lifetimes).
819 let expr = expr.as_coercion_site();
820 let noop = match self.tables.borrow().adjustments.get(&expr.id).map(|adj| adj.kind) {
821 Some(Adjust::DerefRef {
823 autoref: Some(AutoBorrow::Ref(_, mutbl_adj)),
826 match self.node_ty(expr.id).sty {
827 ty::TyRef(_, mt_orig) => {
828 // Reborrow that we can safely ignore.
829 mutbl_adj == mt_orig.mutbl
834 Some(Adjust::NeverToAny) => true,
840 return self.commit_if_ok(|_| {
841 self.lub(true, trace.clone(), &prev_ty, &new_ty)
842 .map(|ok| self.register_infer_ok_obligations(ok))
847 match self.commit_if_ok(|_| coerce.coerce(&exprs, prev_ty, new_ty)) {
849 // Avoid giving strange errors on failed attempts.
850 if let Some(e) = first_error {
853 self.commit_if_ok(|_| {
854 self.lub(true, trace, &prev_ty, &new_ty)
855 .map(|ok| self.register_infer_ok_obligations(ok))
860 let adjustment = self.register_infer_ok_obligations(ok);
861 if !adjustment.is_identity() {
862 let mut tables = self.tables.borrow_mut();
864 let expr = expr.as_coercion_site();
865 if let Some(&mut Adjustment {
866 kind: Adjust::NeverToAny,
868 }) = tables.adjustments.get_mut(&expr.id) {
869 *target = adjustment.target;
872 tables.adjustments.insert(expr.id, adjustment);
875 Ok(adjustment.target)
881 /// CoerceMany encapsulates the pattern you should use when you have
882 /// many expressions that are all getting coerced to a common
883 /// type. This arises, for example, when you have a match (the result
884 /// of each arm is coerced to a common type). It also arises in less
885 /// obvious places, such as when you have many `break foo` expressions
886 /// that target the same loop, or the various `return` expressions in
889 /// The basic protocol is as follows:
891 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
892 /// This will also serve as the "starting LUB". The expectation is
893 /// that this type is something which all of the expressions *must*
894 /// be coercible to. Use a fresh type variable if needed.
895 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
896 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
897 /// unit. This happens for example if you have a `break` with no expression,
898 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
899 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
900 /// from you so that you don't have to worry your pretty head about it.
901 /// But if an error is reported, the final type will be `err`.
902 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
903 /// previously coerced expressions.
904 /// - When all done, invoke `complete()`. This will return the LUB of
905 /// all your expressions.
906 /// - WARNING: I don't believe this final type is guaranteed to be
907 /// related to your initial `expected_ty` in any particular way,
908 /// although it will typically be a subtype, so you should check it.
909 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
910 /// previously coerced expressions.
915 /// let mut coerce = CoerceMany::new(expected_ty);
916 /// for expr in exprs {
917 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
918 /// coerce.coerce(fcx, &cause, expr, expr_ty);
920 /// let final_ty = coerce.complete(fcx);
922 pub struct CoerceMany<'gcx, 'tcx, 'exprs, E>
923 where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
925 expected_ty: Ty<'tcx>,
926 final_ty: Option<Ty<'tcx>>,
927 expressions: Expressions<'gcx, 'exprs, E>,
931 /// The type of a `CoerceMany` that is storing up the expressions into
932 /// a buffer. We use this in `check/mod.rs` for things like `break`.
933 pub type DynamicCoerceMany<'gcx, 'tcx> = CoerceMany<'gcx, 'tcx, 'gcx, P<hir::Expr>>;
935 enum Expressions<'gcx, 'exprs, E>
936 where E: 'exprs + AsCoercionSite,
938 Dynamic(Vec<&'gcx hir::Expr>),
939 UpFront(&'exprs [E]),
942 impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E>
943 where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
945 /// The usual case; collect the set of expressions dynamically.
946 /// If the full set of coercion sites is known before hand,
947 /// consider `with_coercion_sites()` instead to avoid allocation.
948 pub fn new(expected_ty: Ty<'tcx>) -> Self {
949 Self::make(expected_ty, Expressions::Dynamic(vec![]))
952 /// As an optimization, you can create a `CoerceMany` with a
953 /// pre-existing slice of expressions. In this case, you are
954 /// expected to pass each element in the slice to `coerce(...)` in
955 /// order. This is used with arrays in particular to avoid
956 /// needlessly cloning the slice.
957 pub fn with_coercion_sites(expected_ty: Ty<'tcx>,
958 coercion_sites: &'exprs [E])
960 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
963 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'gcx, 'exprs, E>) -> Self {
972 pub fn is_empty(&self) -> bool {
976 /// Return the "expected type" with which this coercion was
977 /// constructed. This represents the "downward propagated" type
978 /// that was given to us at the start of typing whatever construct
979 /// we are typing (e.g., the match expression).
981 /// Typically, this is used as the expected type when
982 /// type-checking each of the alternative expressions whose types
983 /// we are trying to merge.
984 pub fn expected_ty(&self) -> Ty<'tcx> {
988 /// Returns the current "merged type", representing our best-guess
989 /// at the LUB of the expressions we've seen so far (if any). This
990 /// isn't *final* until you call `self.final()`, which will return
992 pub fn merged_ty(&self) -> Ty<'tcx> {
993 self.final_ty.unwrap_or(self.expected_ty)
996 /// Indicates that the value generated by `expression`, which is
997 /// of type `expression_ty`, is one of the possibility that we
998 /// could coerce from. This will record `expression` and later
999 /// calls to `coerce` may come back and add adjustments and things
1001 pub fn coerce<'a>(&mut self,
1002 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1003 cause: &ObligationCause<'tcx>,
1004 expression: &'gcx hir::Expr,
1005 expression_ty: Ty<'tcx>,
1006 expression_diverges: Diverges)
1008 self.coerce_inner(fcx, cause, Some(expression), expression_ty, expression_diverges, None)
1011 /// Indicates that one of the inputs is a "forced unit". This
1012 /// occurs in a case like `if foo { ... };`, where the issing else
1013 /// generates a "forced unit". Another example is a `loop { break;
1014 /// }`, where the `break` has no argument expression. We treat
1015 /// these cases slightly differently for error-reporting
1016 /// purposes. Note that these tend to correspond to cases where
1017 /// the `()` expression is implicit in the source, and hence we do
1018 /// not take an expression argument.
1020 /// The `augment_error` gives you a chance to extend the error
1021 /// message, in case any results (e.g., we use this to suggest
1022 /// removing a `;`).
1023 pub fn coerce_forced_unit<'a>(&mut self,
1024 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1025 cause: &ObligationCause<'tcx>,
1026 augment_error: &mut FnMut(&mut DiagnosticBuilder))
1028 self.coerce_inner(fcx,
1033 Some(augment_error))
1036 /// The inner coercion "engine". If `expression` is `None`, this
1037 /// is a forced-unit case, and hence `expression_ty` must be
1039 fn coerce_inner<'a>(&mut self,
1040 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1041 cause: &ObligationCause<'tcx>,
1042 expression: Option<&'gcx hir::Expr>,
1043 mut expression_ty: Ty<'tcx>,
1044 expression_diverges: Diverges,
1045 augment_error: Option<&mut FnMut(&mut DiagnosticBuilder)>)
1047 // Incorporate whatever type inference information we have
1048 // until now; in principle we might also want to process
1049 // pending obligations, but doing so should only improve
1050 // compatibility (hopefully that is true) by helping us
1051 // uncover never types better.
1052 if expression_ty.is_ty_var() {
1053 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1056 // If we see any error types, just propagate that error
1058 if expression_ty.references_error() || self.merged_ty().references_error() {
1059 self.final_ty = Some(fcx.tcx.types.err);
1063 // Handle the actual type unification etc.
1064 let result = if let Some(expression) = expression {
1065 if self.pushed == 0 {
1066 // Special-case the first expression we are coercing.
1067 // To be honest, I'm not entirely sure why we do this.
1068 fcx.try_coerce(expression, expression_ty, expression_diverges, self.expected_ty)
1070 match self.expressions {
1071 Expressions::Dynamic(ref exprs) =>
1072 fcx.try_find_coercion_lub(cause,
1077 expression_diverges),
1078 Expressions::UpFront(ref coercion_sites) =>
1079 fcx.try_find_coercion_lub(cause,
1080 &coercion_sites[0..self.pushed],
1084 expression_diverges),
1088 // this is a hack for cases where we default to `()` because
1089 // the expression etc has been omitted from the source. An
1090 // example is an `if let` without an else:
1092 // if let Some(x) = ... { }
1094 // we wind up with a second match arm that is like `_ =>
1095 // ()`. That is the case we are considering here. We take
1096 // a different path to get the right "expected, found"
1097 // message and so forth (and because we know that
1098 // `expression_ty` will be unit).
1100 // Another example is `break` with no argument expression.
1101 assert!(expression_ty.is_nil());
1102 assert!(expression_ty.is_nil(), "if let hack without unit type");
1103 fcx.eq_types(true, cause, expression_ty, self.merged_ty())
1105 fcx.register_infer_ok_obligations(infer_ok);
1112 self.final_ty = Some(v);
1113 if let Some(e) = expression {
1114 match self.expressions {
1115 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1116 Expressions::UpFront(coercion_sites) => {
1117 // if the user gave us an array to validate, check that we got
1118 // the next expression in the list, as expected
1119 assert_eq!(coercion_sites[self.pushed].as_coercion_site().id, e.id);
1126 let (expected, found) = if expression.is_none() {
1127 // In the case where this is a "forced unit", like
1128 // `break`, we want to call the `()` "expected"
1129 // since it is implied by the syntax.
1130 assert!(expression_ty.is_nil());
1131 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1133 // Otherwise, the "expected" type for error
1134 // reporting is the current unification type,
1135 // which is basically the LUB of the expressions
1136 // we've seen so far (combined with the expected
1138 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1143 ObligationCauseCode::ReturnNoExpression => {
1144 db = struct_span_err!(
1145 fcx.tcx.sess, cause.span, E0069,
1146 "`return;` in a function whose return type is not `()`");
1147 db.span_label(cause.span, &format!("return type is not ()"));
1150 db = fcx.report_mismatched_types(cause, expected, found, err);
1154 if let Some(mut augment_error) = augment_error {
1155 augment_error(&mut db);
1160 self.final_ty = Some(fcx.tcx.types.err);
1165 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1166 if let Some(final_ty) = self.final_ty {
1169 // If we only had inputs that were of type `!` (or no
1170 // inputs at all), then the final type is `!`.
1171 assert_eq!(self.pushed, 0);
1177 /// Something that can be converted into an expression to which we can
1178 /// apply a coercion.
1179 pub trait AsCoercionSite {
1180 fn as_coercion_site(&self) -> &hir::Expr;
1183 impl AsCoercionSite for hir::Expr {
1184 fn as_coercion_site(&self) -> &hir::Expr {
1189 impl AsCoercionSite for P<hir::Expr> {
1190 fn as_coercion_site(&self) -> &hir::Expr {
1195 impl<'a, T> AsCoercionSite for &'a T
1196 where T: AsCoercionSite
1198 fn as_coercion_site(&self) -> &hir::Expr {
1199 (**self).as_coercion_site()
1203 impl AsCoercionSite for ! {
1204 fn as_coercion_site(&self) -> &hir::Expr {
1209 impl AsCoercionSite for hir::Arm {
1210 fn as_coercion_site(&self) -> &hir::Expr {