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::{FnCtxt, Needs};
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, AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
71 use rustc::ty::{self, TypeAndMut, Ty, ClosureSubsts};
72 use rustc::ty::fold::TypeFoldable;
73 use rustc::ty::error::TypeError;
74 use rustc::ty::relate::RelateResult;
75 use errors::DiagnosticBuilder;
76 use syntax::feature_gate;
80 use std::collections::VecDeque;
83 struct Coerce<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
84 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
85 cause: ObligationCause<'tcx>,
87 /// Determines whether or not allow_two_phase_borrow is set on any
88 /// autoref adjustments we create while coercing. We don't want to
89 /// allow deref coercions to create two-phase borrows, at least initially,
90 /// but we do need two-phase borrows for function argument reborrows.
91 /// See #47489 and #48598
92 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
93 allow_two_phase: AllowTwoPhase,
96 impl<'a, 'gcx, 'tcx> Deref for Coerce<'a, 'gcx, 'tcx> {
97 type Target = FnCtxt<'a, 'gcx, 'tcx>;
98 fn deref(&self) -> &Self::Target {
103 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
105 fn coerce_mutbls<'tcx>(from_mutbl: hir::Mutability,
106 to_mutbl: hir::Mutability)
107 -> RelateResult<'tcx, ()> {
108 match (from_mutbl, to_mutbl) {
109 (hir::MutMutable, hir::MutMutable) |
110 (hir::MutImmutable, hir::MutImmutable) |
111 (hir::MutMutable, hir::MutImmutable) => Ok(()),
112 (hir::MutImmutable, hir::MutMutable) => Err(TypeError::Mutability),
116 fn identity(_: Ty) -> Vec<Adjustment> { vec![] }
118 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
119 move |target| vec![Adjustment { kind, target }]
122 fn success<'tcx>(adj: Vec<Adjustment<'tcx>>,
124 obligations: traits::PredicateObligations<'tcx>)
125 -> CoerceResult<'tcx> {
127 value: (adj, target),
132 impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> {
133 fn new(fcx: &'f FnCtxt<'f, 'gcx, 'tcx>,
134 cause: ObligationCause<'tcx>,
135 allow_two_phase: AllowTwoPhase) -> Self {
144 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
145 self.commit_if_ok(|_| {
147 self.at(&self.cause, self.fcx.param_env)
150 self.at(&self.cause, self.fcx.param_env)
152 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
157 /// Unify two types (using sub or lub) and produce a specific coercion.
158 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F)
159 -> CoerceResult<'tcx>
160 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
162 self.unify(&a, &b).and_then(|InferOk { value: ty, obligations }| {
163 success(f(ty), ty, obligations)
167 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
168 let a = self.shallow_resolve(a);
169 debug!("Coerce.tys({:?} => {:?})", a, b);
171 // Just ignore error types.
172 if a.references_error() || b.references_error() {
173 return success(vec![], b, vec![]);
177 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
178 // type variable, we want `?T` to fallback to `!` if not
179 // otherwise constrained. An example where this arises:
181 // let _: Option<?T> = Some({ return; });
183 // here, we would coerce from `!` to `?T`.
184 let b = self.shallow_resolve(b);
185 return if self.shallow_resolve(b).is_ty_var() {
186 // micro-optimization: no need for this if `b` is
187 // already resolved in some way.
188 let diverging_ty = self.next_diverging_ty_var(
189 TypeVariableOrigin::AdjustmentType(self.cause.span));
190 self.unify_and(&b, &diverging_ty, simple(Adjust::NeverToAny))
192 success(simple(Adjust::NeverToAny)(b), b, vec![])
196 // Consider coercing the subtype to a DST
198 // NOTE: this is wrapped in a `commit_if_ok` because it creates
199 // a "spurious" type variable, and we don't want to have that
200 // type variable in memory if the coercion fails.
201 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
203 debug!("coerce: unsize successful");
206 debug!("coerce: unsize failed");
208 // Examine the supertype and consider auto-borrowing.
210 // Note: does not attempt to resolve type variables we encounter.
211 // See above for details.
213 ty::TyRawPtr(mt_b) => {
214 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
217 ty::TyRef(r_b, ty, mutbl) => {
218 let mt_b = ty::TypeAndMut { ty, mutbl };
219 return self.coerce_borrowed_pointer(a, b, r_b, mt_b);
227 // Function items are coercible to any closure
228 // type; function pointers are not (that would
229 // require double indirection).
230 // Additionally, we permit coercion of function
231 // items to drop the unsafe qualifier.
232 self.coerce_from_fn_item(a, b)
234 ty::TyFnPtr(a_f) => {
235 // We permit coercion of fn pointers to drop the
237 self.coerce_from_fn_pointer(a, a_f, b)
239 ty::TyClosure(def_id_a, substs_a) => {
240 // Non-capturing closures are coercible to
242 self.coerce_closure_to_fn(a, def_id_a, substs_a, b)
245 // Otherwise, just use unification rules.
246 self.unify_and(a, b, identity)
251 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
252 /// To match `A` with `B`, autoderef will be performed,
253 /// calling `deref`/`deref_mut` where necessary.
254 fn coerce_borrowed_pointer(&self,
257 r_b: ty::Region<'tcx>,
258 mt_b: TypeAndMut<'tcx>)
259 -> CoerceResult<'tcx> {
261 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
263 // If we have a parameter of type `&M T_a` and the value
264 // provided is `expr`, we will be adding an implicit borrow,
265 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
266 // to type check, we will construct the type that `&M*expr` would
269 let (r_a, mt_a) = match a.sty {
270 ty::TyRef(r_a, ty, mutbl) => {
271 let mt_a = ty::TypeAndMut { ty, mutbl };
272 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
275 _ => return self.unify_and(a, b, identity),
278 let span = self.cause.span;
280 let mut first_error = None;
281 let mut r_borrow_var = None;
282 let mut autoderef = self.autoderef(span, a);
283 let mut found = None;
285 for (referent_ty, autoderefs) in autoderef.by_ref() {
287 // Don't let this pass, otherwise it would cause
288 // &T to autoref to &&T.
292 // At this point, we have deref'd `a` to `referent_ty`. So
293 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
294 // In the autoderef loop for `&'a mut Vec<T>`, we would get
297 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
298 // - `Vec<T>` -- 1 deref
299 // - `[T]` -- 2 deref
301 // At each point after the first callback, we want to
302 // check to see whether this would match out target type
303 // (`&'b mut [T]`) if we autoref'd it. We can't just
304 // compare the referent types, though, because we still
305 // have to consider the mutability. E.g., in the case
306 // we've been considering, we have an `&mut` reference, so
307 // the `T` in `[T]` needs to be unified with equality.
309 // Therefore, we construct reference types reflecting what
310 // the types will be after we do the final auto-ref and
311 // compare those. Note that this means we use the target
312 // mutability [1], since it may be that we are coercing
313 // from `&mut T` to `&U`.
315 // One fine point concerns the region that we use. We
316 // choose the region such that the region of the final
317 // type that results from `unify` will be the region we
318 // want for the autoref:
320 // - if in sub mode, that means we want to use `'b` (the
321 // region from the target reference) for both
322 // pointers [2]. This is because sub mode (somewhat
323 // arbitrarily) returns the subtype region. In the case
324 // where we are coercing to a target type, we know we
325 // want to use that target type region (`'b`) because --
326 // for the program to type-check -- it must be the
327 // smaller of the two.
328 // - One fine point. It may be surprising that we can
329 // use `'b` without relating `'a` and `'b`. The reason
330 // that this is ok is that what we produce is
331 // effectively a `&'b *x` expression (if you could
332 // annotate the region of a borrow), and regionck has
333 // code that adds edges from the region of a borrow
334 // (`'b`, here) into the regions in the borrowed
335 // expression (`*x`, here). (Search for "link".)
336 // - if in lub mode, things can get fairly complicated. The
337 // easiest thing is just to make a fresh
338 // region variable [4], which effectively means we defer
339 // the decision to region inference (and regionck, which will add
340 // some more edges to this variable). However, this can wind up
341 // creating a crippling number of variables in some cases --
342 // e.g. #32278 -- so we optimize one particular case [3].
343 // Let me try to explain with some examples:
344 // - The "running example" above represents the simple case,
345 // where we have one `&` reference at the outer level and
346 // ownership all the rest of the way down. In this case,
347 // we want `LUB('a, 'b)` as the resulting region.
348 // - However, if there are nested borrows, that region is
349 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
350 // `&'b T`. In this case, `'a` is actually irrelevant.
351 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
352 // we get spurious errors (`run-pass/regions-lub-ref-ref-rc.rs`).
353 // (The errors actually show up in borrowck, typically, because
354 // this extra edge causes the region `'a` to be inferred to something
355 // too big, which then results in borrowck errors.)
356 // - We could track the innermost shared reference, but there is already
357 // code in regionck that has the job of creating links between
358 // the region of a borrow and the regions in the thing being
359 // borrowed (here, `'a` and `'x`), and it knows how to handle
360 // all the various cases. So instead we just make a region variable
361 // and let regionck figure it out.
362 let r = if !self.use_lub {
364 } else if autoderefs == 1 {
367 if r_borrow_var.is_none() {
368 // create var lazilly, at most once
369 let coercion = Coercion(span);
370 let r = self.next_region_var(coercion);
371 r_borrow_var = Some(r); // [4] above
373 r_borrow_var.unwrap()
375 let derefd_ty_a = self.tcx.mk_ref(r,
378 mutbl: mt_b.mutbl, // [1] above
380 match self.unify(derefd_ty_a, b) {
386 if first_error.is_none() {
387 first_error = Some(err);
393 // Extract type or return an error. We return the first error
394 // we got, which should be from relating the "base" type
395 // (e.g., in example above, the failure from relating `Vec<T>`
396 // to the target type), since that should be the least
398 let InferOk { value: ty, mut obligations } = match found {
401 let err = first_error.expect("coerce_borrowed_pointer had no error");
402 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
407 if ty == a && mt_a.mutbl == hir::MutImmutable && autoderef.step_count() == 1 {
408 // As a special case, if we would produce `&'a *x`, that's
409 // a total no-op. We end up with the type `&'a T` just as
410 // we started with. In that case, just skip it
411 // altogether. This is just an optimization.
413 // Note that for `&mut`, we DO want to reborrow --
414 // otherwise, this would be a move, which might be an
415 // error. For example `foo(self.x)` where `self` and
416 // `self.x` both have `&mut `type would be a move of
417 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
418 // which is a borrow.
419 assert_eq!(mt_b.mutbl, hir::MutImmutable); // can only coerce &T -> &U
420 return success(vec![], ty, obligations);
423 let needs = Needs::maybe_mut_place(mt_b.mutbl);
424 let InferOk { value: mut adjustments, obligations: o }
425 = autoderef.adjust_steps_as_infer_ok(needs);
426 obligations.extend(o);
427 obligations.extend(autoderef.into_obligations());
429 // Now apply the autoref. We have to extract the region out of
430 // the final ref type we got.
431 let r_borrow = match ty.sty {
432 ty::TyRef(r_borrow, _, _) => r_borrow,
433 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
435 let mutbl = match mt_b.mutbl {
436 hir::MutImmutable => AutoBorrowMutability::Immutable,
437 hir::MutMutable => AutoBorrowMutability::Mutable {
438 allow_two_phase_borrow: self.allow_two_phase,
441 adjustments.push(Adjustment {
442 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
446 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}",
450 success(adjustments, ty, obligations)
454 // &[T; n] or &mut [T; n] -> &[T]
455 // or &mut [T; n] -> &mut [T]
456 // or &Concrete -> &Trait, etc.
457 fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
458 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
460 let traits = (self.tcx.lang_items().unsize_trait(),
461 self.tcx.lang_items().coerce_unsized_trait());
462 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
465 debug!("Missing Unsize or CoerceUnsized traits");
466 return Err(TypeError::Mismatch);
469 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
470 // a DST unless we have to. This currently comes out in the wash since
471 // we can't unify [T] with U. But to properly support DST, we need to allow
472 // that, at which point we will need extra checks on the target here.
474 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
475 let reborrow = match (&source.sty, &target.sty) {
476 (&ty::TyRef(_, ty_a, mutbl_a), &ty::TyRef(_, _, mutbl_b)) => {
477 coerce_mutbls(mutbl_a, mutbl_b)?;
479 let coercion = Coercion(self.cause.span);
480 let r_borrow = self.next_region_var(coercion);
481 let mutbl = match mutbl_b {
482 hir::MutImmutable => AutoBorrowMutability::Immutable,
483 hir::MutMutable => AutoBorrowMutability::Mutable {
484 // We don't allow two-phase borrows here, at least for initial
485 // implementation. If it happens that this coercion is a function argument,
486 // the reborrow in coerce_borrowed_ptr will pick it up.
487 allow_two_phase_borrow: AllowTwoPhase::No,
491 kind: Adjust::Deref(None),
494 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
495 target: self.tcx.mk_ref(r_borrow, ty::TypeAndMut {
501 (&ty::TyRef(_, ty_a, mt_a), &ty::TyRawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
502 coerce_mutbls(mt_a, mt_b)?;
505 kind: Adjust::Deref(None),
508 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
509 target: self.tcx.mk_ptr(ty::TypeAndMut {
517 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
519 // Setup either a subtyping or a LUB relationship between
520 // the `CoerceUnsized` target type and the expected type.
521 // We only have the latter, so we use an inference variable
522 // for the former and let type inference do the rest.
523 let origin = TypeVariableOrigin::MiscVariable(self.cause.span);
524 let coerce_target = self.next_ty_var(origin);
525 let mut coercion = self.unify_and(coerce_target, target, |target| {
526 let unsize = Adjustment {
527 kind: Adjust::Unsize,
531 None => vec![unsize],
532 Some((ref deref, ref autoref)) => {
533 vec![deref.clone(), autoref.clone(), unsize]
538 let mut selcx = traits::SelectionContext::new(self);
540 // Use a FIFO queue for this custom fulfillment procedure. (The maximum
541 // length is almost always 1.)
542 let mut queue = VecDeque::with_capacity(1);
544 // Create an obligation for `Source: CoerceUnsized<Target>`.
545 let cause = ObligationCause::misc(self.cause.span, self.body_id);
546 queue.push_back(self.tcx.predicate_for_trait_def(self.fcx.param_env,
551 &[coerce_target.into()]));
553 let mut has_unsized_tuple_coercion = false;
555 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
556 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
557 // inference might unify those two inner type variables later.
558 let traits = [coerce_unsized_did, unsize_did];
559 while let Some(obligation) = queue.pop_front() {
560 debug!("coerce_unsized resolve step: {:?}", obligation);
561 let trait_ref = match obligation.predicate {
562 ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => {
563 if unsize_did == tr.def_id() {
564 let sty = &tr.skip_binder().input_types().nth(1).unwrap().sty;
565 if let ty::TyTuple(..) = sty {
566 debug!("coerce_unsized: found unsized tuple coercion");
567 has_unsized_tuple_coercion = true;
573 coercion.obligations.push(obligation);
577 match selcx.select(&obligation.with(trait_ref)) {
578 // Uncertain or unimplemented.
580 Err(traits::Unimplemented) => {
581 debug!("coerce_unsized: early return - can't prove obligation");
582 return Err(TypeError::Mismatch);
585 // Object safety violations or miscellaneous.
587 self.report_selection_error(&obligation, &err, false);
588 // Treat this like an obligation and follow through
589 // with the unsizing - the lack of a coercion should
590 // be silent, as it causes a type mismatch later.
593 Ok(Some(vtable)) => {
594 for obligation in vtable.nested_obligations() {
595 queue.push_back(obligation);
601 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
602 feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
603 "unsized_tuple_coercion",
605 feature_gate::GateIssue::Language,
606 feature_gate::EXPLAIN_UNSIZED_TUPLE_COERCION);
612 fn coerce_from_safe_fn<F, G>(&self,
614 fn_ty_a: ty::PolyFnSig<'tcx>,
618 -> CoerceResult<'tcx>
619 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
620 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
622 if let ty::TyFnPtr(fn_ty_b) = b.sty {
623 match (fn_ty_a.unsafety(), fn_ty_b.unsafety()) {
624 (hir::Unsafety::Normal, hir::Unsafety::Unsafe) => {
625 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
626 return self.unify_and(unsafe_a, b, to_unsafe);
631 self.unify_and(a, b, normal)
634 fn coerce_from_fn_pointer(&self,
636 fn_ty_a: ty::PolyFnSig<'tcx>,
638 -> CoerceResult<'tcx> {
639 //! Attempts to coerce from the type of a Rust function item
640 //! into a closure or a `proc`.
643 let b = self.shallow_resolve(b);
644 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
646 self.coerce_from_safe_fn(a, fn_ty_a, b,
647 simple(Adjust::UnsafeFnPointer), identity)
650 fn coerce_from_fn_item(&self,
653 -> CoerceResult<'tcx> {
654 //! Attempts to coerce from the type of a Rust function item
655 //! into a closure or a `proc`.
658 let b = self.shallow_resolve(b);
659 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
663 let a_sig = a.fn_sig(self.tcx);
664 let InferOk { value: a_sig, mut obligations } =
665 self.normalize_associated_types_in_as_infer_ok(self.cause.span, &a_sig);
667 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
668 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
674 Adjustment { kind: Adjust::ReifyFnPointer, target: a_fn_pointer },
675 Adjustment { kind: Adjust::UnsafeFnPointer, target: unsafe_ty },
678 simple(Adjust::ReifyFnPointer)
681 obligations.extend(o2);
682 Ok(InferOk { value, obligations })
684 _ => self.unify_and(a, b, identity),
688 fn coerce_closure_to_fn(&self,
691 substs_a: ClosureSubsts<'tcx>,
693 -> CoerceResult<'tcx> {
694 //! Attempts to coerce from the type of a non-capturing closure
695 //! into a function pointer.
698 let b = self.shallow_resolve(b);
700 let node_id_a = self.tcx.hir.as_local_node_id(def_id_a).unwrap();
702 ty::TyFnPtr(_) if self.tcx.with_freevars(node_id_a, |v| v.is_empty()) => {
703 // We coerce the closure, which has fn type
704 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
706 // `fn(arg0,arg1,...) -> _`
707 let sig = self.closure_sig(def_id_a, substs_a);
708 let pointer_ty = self.tcx.coerce_closure_fn_ty(sig);
709 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})",
711 self.unify_and(pointer_ty, b, simple(Adjust::ClosureFnPointer))
713 _ => self.unify_and(a, b, identity),
717 fn coerce_unsafe_ptr(&self,
720 mutbl_b: hir::Mutability)
721 -> CoerceResult<'tcx> {
722 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
724 let (is_ref, mt_a) = match a.sty {
725 ty::TyRef(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
726 ty::TyRawPtr(mt) => (false, mt),
728 return self.unify_and(a, b, identity);
732 // Check that the types which they point at are compatible.
733 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut {
737 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
738 // Although references and unsafe ptrs have the same
739 // representation, we still register an Adjust::DerefRef so that
740 // regionck knows that the region for `a` must be valid here.
742 self.unify_and(a_unsafe, b, |target| {
744 kind: Adjust::Deref(None),
747 kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
751 } else if mt_a.mutbl != mutbl_b {
752 self.unify_and(a_unsafe, b, simple(Adjust::MutToConstPointer))
754 self.unify_and(a_unsafe, b, identity)
759 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
760 /// Attempt to coerce an expression to a type, and return the
761 /// adjusted type of the expression, if successful.
762 /// Adjustments are only recorded if the coercion succeeded.
763 /// The expressions *must not* have any pre-existing adjustments.
764 pub fn try_coerce(&self,
768 allow_two_phase: AllowTwoPhase)
769 -> RelateResult<'tcx, Ty<'tcx>> {
770 let source = self.resolve_type_vars_with_obligations(expr_ty);
771 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
773 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
774 let coerce = Coerce::new(self, cause, allow_two_phase);
775 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
777 let (adjustments, _) = self.register_infer_ok_obligations(ok);
778 self.apply_adjustments(expr, adjustments);
782 /// Same as `try_coerce()`, but without side-effects.
783 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
784 let source = self.resolve_type_vars_with_obligations(expr_ty);
785 debug!("coercion::can({:?} -> {:?})", source, target);
787 let cause = self.cause(syntax_pos::DUMMY_SP, ObligationCauseCode::ExprAssignable);
788 // We don't ever need two-phase here since we throw out the result of the coercion
789 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
790 self.probe(|_| coerce.coerce(source, target)).is_ok()
793 /// Given some expressions, their known unified type and another expression,
794 /// tries to unify the types, potentially inserting coercions on any of the
795 /// provided expressions and returns their LUB (aka "common supertype").
797 /// This is really an internal helper. From outside the coercion
798 /// module, you should instantiate a `CoerceMany` instance.
799 fn try_find_coercion_lub<E>(&self,
800 cause: &ObligationCause<'tcx>,
805 -> RelateResult<'tcx, Ty<'tcx>>
806 where E: AsCoercionSite
808 let prev_ty = self.resolve_type_vars_with_obligations(prev_ty);
809 let new_ty = self.resolve_type_vars_with_obligations(new_ty);
810 debug!("coercion::try_find_coercion_lub({:?}, {:?})", prev_ty, new_ty);
812 // Special-case that coercion alone cannot handle:
813 // Two function item types of differing IDs or Substs.
814 if let (&ty::TyFnDef(..), &ty::TyFnDef(..)) = (&prev_ty.sty, &new_ty.sty) {
815 // Don't reify if the function types have a LUB, i.e. they
816 // are the same function and their parameters have a LUB.
817 let lub_ty = self.commit_if_ok(|_| {
818 self.at(cause, self.param_env)
819 .lub(prev_ty, new_ty)
820 }).map(|ok| self.register_infer_ok_obligations(ok));
823 // We have a LUB of prev_ty and new_ty, just return it.
827 // The signature must match.
828 let a_sig = prev_ty.fn_sig(self.tcx);
829 let a_sig = self.normalize_associated_types_in(new.span, &a_sig);
830 let b_sig = new_ty.fn_sig(self.tcx);
831 let b_sig = self.normalize_associated_types_in(new.span, &b_sig);
832 let sig = self.at(cause, self.param_env)
833 .trace(prev_ty, new_ty)
835 .map(|ok| self.register_infer_ok_obligations(ok))?;
837 // Reify both sides and return the reified fn pointer type.
838 let fn_ptr = self.tcx.mk_fn_ptr(sig);
839 for expr in exprs.iter().map(|e| e.as_coercion_site()).chain(Some(new)) {
840 // The only adjustment that can produce an fn item is
841 // `NeverToAny`, so this should always be valid.
842 self.apply_adjustments(expr, vec![Adjustment {
843 kind: Adjust::ReifyFnPointer,
850 // Configure a Coerce instance to compute the LUB.
851 // We don't allow two-phase borrows on any autorefs this creates since we
852 // probably aren't processing function arguments here and even if we were,
853 // they're going to get autorefed again anyway and we can apply 2-phase borrows
855 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
856 coerce.use_lub = true;
858 // First try to coerce the new expression to the type of the previous ones,
859 // but only if the new expression has no coercion already applied to it.
860 let mut first_error = None;
861 if !self.tables.borrow().adjustments().contains_key(new.hir_id) {
862 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
865 let (adjustments, target) = self.register_infer_ok_obligations(ok);
866 self.apply_adjustments(new, adjustments);
869 Err(e) => first_error = Some(e),
873 // Then try to coerce the previous expressions to the type of the new one.
874 // This requires ensuring there are no coercions applied to *any* of the
875 // previous expressions, other than noop reborrows (ignoring lifetimes).
877 let expr = expr.as_coercion_site();
878 let noop = match self.tables.borrow().expr_adjustments(expr) {
880 Adjustment { kind: Adjust::Deref(_), .. },
881 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }
883 match self.node_ty(expr.hir_id).sty {
884 ty::TyRef(_, _, mt_orig) => {
885 let mutbl_adj: hir::Mutability = mutbl_adj.into();
886 // Reborrow that we can safely ignore, because
887 // the next adjustment can only be a Deref
888 // which will be merged into it.
894 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
899 return self.commit_if_ok(|_| {
900 self.at(cause, self.param_env)
901 .lub(prev_ty, new_ty)
902 }).map(|ok| self.register_infer_ok_obligations(ok));
906 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
908 // Avoid giving strange errors on failed attempts.
909 if let Some(e) = first_error {
912 self.commit_if_ok(|_| {
913 self.at(cause, self.param_env)
914 .lub(prev_ty, new_ty)
915 }).map(|ok| self.register_infer_ok_obligations(ok))
919 let (adjustments, target) = self.register_infer_ok_obligations(ok);
921 let expr = expr.as_coercion_site();
922 self.apply_adjustments(expr, adjustments.clone());
930 /// CoerceMany encapsulates the pattern you should use when you have
931 /// many expressions that are all getting coerced to a common
932 /// type. This arises, for example, when you have a match (the result
933 /// of each arm is coerced to a common type). It also arises in less
934 /// obvious places, such as when you have many `break foo` expressions
935 /// that target the same loop, or the various `return` expressions in
938 /// The basic protocol is as follows:
940 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
941 /// This will also serve as the "starting LUB". The expectation is
942 /// that this type is something which all of the expressions *must*
943 /// be coercible to. Use a fresh type variable if needed.
944 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
945 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
946 /// unit. This happens for example if you have a `break` with no expression,
947 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
948 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
949 /// from you so that you don't have to worry your pretty head about it.
950 /// But if an error is reported, the final type will be `err`.
951 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
952 /// previously coerced expressions.
953 /// - When all done, invoke `complete()`. This will return the LUB of
954 /// all your expressions.
955 /// - WARNING: I don't believe this final type is guaranteed to be
956 /// related to your initial `expected_ty` in any particular way,
957 /// although it will typically be a subtype, so you should check it.
958 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
959 /// previously coerced expressions.
964 /// let mut coerce = CoerceMany::new(expected_ty);
965 /// for expr in exprs {
966 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
967 /// coerce.coerce(fcx, &cause, expr, expr_ty);
969 /// let final_ty = coerce.complete(fcx);
971 pub struct CoerceMany<'gcx, 'tcx, 'exprs, E>
972 where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
974 expected_ty: Ty<'tcx>,
975 final_ty: Option<Ty<'tcx>>,
976 expressions: Expressions<'gcx, 'exprs, E>,
980 /// The type of a `CoerceMany` that is storing up the expressions into
981 /// a buffer. We use this in `check/mod.rs` for things like `break`.
982 pub type DynamicCoerceMany<'gcx, 'tcx> = CoerceMany<'gcx, 'tcx, 'gcx, P<hir::Expr>>;
984 enum Expressions<'gcx, 'exprs, E>
985 where E: 'exprs + AsCoercionSite,
987 Dynamic(Vec<&'gcx hir::Expr>),
988 UpFront(&'exprs [E]),
991 impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E>
992 where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
994 /// The usual case; collect the set of expressions dynamically.
995 /// If the full set of coercion sites is known before hand,
996 /// consider `with_coercion_sites()` instead to avoid allocation.
997 pub fn new(expected_ty: Ty<'tcx>) -> Self {
998 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1001 /// As an optimization, you can create a `CoerceMany` with a
1002 /// pre-existing slice of expressions. In this case, you are
1003 /// expected to pass each element in the slice to `coerce(...)` in
1004 /// order. This is used with arrays in particular to avoid
1005 /// needlessly cloning the slice.
1006 pub fn with_coercion_sites(expected_ty: Ty<'tcx>,
1007 coercion_sites: &'exprs [E])
1009 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1012 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'gcx, 'exprs, E>) -> Self {
1021 /// Return the "expected type" with which this coercion was
1022 /// constructed. This represents the "downward propagated" type
1023 /// that was given to us at the start of typing whatever construct
1024 /// we are typing (e.g., the match expression).
1026 /// Typically, this is used as the expected type when
1027 /// type-checking each of the alternative expressions whose types
1028 /// we are trying to merge.
1029 pub fn expected_ty(&self) -> Ty<'tcx> {
1033 /// Returns the current "merged type", representing our best-guess
1034 /// at the LUB of the expressions we've seen so far (if any). This
1035 /// isn't *final* until you call `self.final()`, which will return
1036 /// the merged type.
1037 pub fn merged_ty(&self) -> Ty<'tcx> {
1038 self.final_ty.unwrap_or(self.expected_ty)
1041 /// Indicates that the value generated by `expression`, which is
1042 /// of type `expression_ty`, is one of the possibility that we
1043 /// could coerce from. This will record `expression` and later
1044 /// calls to `coerce` may come back and add adjustments and things
1046 pub fn coerce<'a>(&mut self,
1047 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1048 cause: &ObligationCause<'tcx>,
1049 expression: &'gcx hir::Expr,
1050 expression_ty: Ty<'tcx>)
1052 self.coerce_inner(fcx,
1059 /// Indicates that one of the inputs is a "forced unit". This
1060 /// occurs in a case like `if foo { ... };`, where the missing else
1061 /// generates a "forced unit". Another example is a `loop { break;
1062 /// }`, where the `break` has no argument expression. We treat
1063 /// these cases slightly differently for error-reporting
1064 /// purposes. Note that these tend to correspond to cases where
1065 /// the `()` expression is implicit in the source, and hence we do
1066 /// not take an expression argument.
1068 /// The `augment_error` gives you a chance to extend the error
1069 /// message, in case any results (e.g., we use this to suggest
1070 /// removing a `;`).
1071 pub fn coerce_forced_unit<'a>(&mut self,
1072 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1073 cause: &ObligationCause<'tcx>,
1074 augment_error: &mut dyn FnMut(&mut DiagnosticBuilder),
1075 label_unit_as_expected: bool)
1077 self.coerce_inner(fcx,
1081 Some(augment_error),
1082 label_unit_as_expected)
1085 /// The inner coercion "engine". If `expression` is `None`, this
1086 /// is a forced-unit case, and hence `expression_ty` must be
1088 fn coerce_inner<'a>(&mut self,
1089 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1090 cause: &ObligationCause<'tcx>,
1091 expression: Option<&'gcx hir::Expr>,
1092 mut expression_ty: Ty<'tcx>,
1093 augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder)>,
1094 label_expression_as_expected: bool)
1096 // Incorporate whatever type inference information we have
1097 // until now; in principle we might also want to process
1098 // pending obligations, but doing so should only improve
1099 // compatibility (hopefully that is true) by helping us
1100 // uncover never types better.
1101 if expression_ty.is_ty_var() {
1102 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1105 // If we see any error types, just propagate that error
1107 if expression_ty.references_error() || self.merged_ty().references_error() {
1108 self.final_ty = Some(fcx.tcx.types.err);
1112 // Handle the actual type unification etc.
1113 let result = if let Some(expression) = expression {
1114 if self.pushed == 0 {
1115 // Special-case the first expression we are coercing.
1116 // To be honest, I'm not entirely sure why we do this.
1117 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1118 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1120 match self.expressions {
1121 Expressions::Dynamic(ref exprs) =>
1122 fcx.try_find_coercion_lub(cause,
1127 Expressions::UpFront(ref coercion_sites) =>
1128 fcx.try_find_coercion_lub(cause,
1129 &coercion_sites[0..self.pushed],
1136 // this is a hack for cases where we default to `()` because
1137 // the expression etc has been omitted from the source. An
1138 // example is an `if let` without an else:
1140 // if let Some(x) = ... { }
1142 // we wind up with a second match arm that is like `_ =>
1143 // ()`. That is the case we are considering here. We take
1144 // a different path to get the right "expected, found"
1145 // message and so forth (and because we know that
1146 // `expression_ty` will be unit).
1148 // Another example is `break` with no argument expression.
1149 assert!(expression_ty.is_nil());
1150 assert!(expression_ty.is_nil(), "if let hack without unit type");
1151 fcx.at(cause, fcx.param_env)
1152 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1154 fcx.register_infer_ok_obligations(infer_ok);
1161 self.final_ty = Some(v);
1162 if let Some(e) = expression {
1163 match self.expressions {
1164 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1165 Expressions::UpFront(coercion_sites) => {
1166 // if the user gave us an array to validate, check that we got
1167 // the next expression in the list, as expected
1168 assert_eq!(coercion_sites[self.pushed].as_coercion_site().id, e.id);
1175 let (expected, found) = if label_expression_as_expected {
1176 // In the case where this is a "forced unit", like
1177 // `break`, we want to call the `()` "expected"
1178 // since it is implied by the syntax.
1179 // (Note: not all force-units work this way.)"
1180 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1182 // Otherwise, the "expected" type for error
1183 // reporting is the current unification type,
1184 // which is basically the LUB of the expressions
1185 // we've seen so far (combined with the expected
1187 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1192 ObligationCauseCode::ReturnNoExpression => {
1193 db = struct_span_err!(
1194 fcx.tcx.sess, cause.span, E0069,
1195 "`return;` in a function whose return type is not `()`");
1196 db.span_label(cause.span, "return type is not ()");
1198 ObligationCauseCode::BlockTailExpression(blk_id) => {
1199 db = fcx.report_mismatched_types(cause, expected, found, err);
1201 let expr = expression.unwrap_or_else(|| {
1202 span_bug!(cause.span,
1203 "supposed to be part of a block tail expression, but the \
1204 expression is empty");
1206 fcx.suggest_mismatched_types_on_tail(
1216 db = fcx.report_mismatched_types(cause, expected, found, err);
1220 if let Some(augment_error) = augment_error {
1221 augment_error(&mut db);
1226 self.final_ty = Some(fcx.tcx.types.err);
1231 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1232 if let Some(final_ty) = self.final_ty {
1235 // If we only had inputs that were of type `!` (or no
1236 // inputs at all), then the final type is `!`.
1237 assert_eq!(self.pushed, 0);
1243 /// Something that can be converted into an expression to which we can
1244 /// apply a coercion.
1245 pub trait AsCoercionSite {
1246 fn as_coercion_site(&self) -> &hir::Expr;
1249 impl AsCoercionSite for hir::Expr {
1250 fn as_coercion_site(&self) -> &hir::Expr {
1255 impl AsCoercionSite for P<hir::Expr> {
1256 fn as_coercion_site(&self) -> &hir::Expr {
1261 impl<'a, T> AsCoercionSite for &'a T
1262 where T: AsCoercionSite
1264 fn as_coercion_site(&self) -> &hir::Expr {
1265 (**self).as_coercion_site()
1269 impl AsCoercionSite for ! {
1270 fn as_coercion_site(&self) -> &hir::Expr {
1275 impl AsCoercionSite for hir::Arm {
1276 fn as_coercion_site(&self) -> &hir::Expr {