3 //! Under certain circumstances we will coerce from one type to another,
4 //! for example by auto-borrowing. This occurs in situations where the
5 //! compiler has a firm 'expected type' that was supplied from the user,
6 //! and where the actual type is similar to that expected type in purpose
7 //! but not in representation (so actual subtyping is inappropriate).
11 //! Note that if we are expecting a reference, we will *reborrow*
12 //! even if the argument provided was already a reference. This is
13 //! useful for freezing mut/const things (that is, when the expected is &T
14 //! but you have &const T or &mut T) and also for avoiding the linearity
15 //! of mut things (when the expected is &mut T and you have &mut T). See
16 //! the various `src/test/ui/coerce-reborrow-*.rs` tests for
17 //! examples of where this is useful.
21 //! When deciding what type coercions to consider, we do not attempt to
22 //! resolve any type variables we may encounter. This is because `b`
23 //! represents the expected type "as the user wrote it", meaning that if
24 //! the user defined a generic function like
26 //! fn foo<A>(a: A, b: A) { ... }
28 //! and then we wrote `foo(&1, @2)`, we will not auto-borrow
29 //! either argument. In older code we went to some lengths to
30 //! resolve the `b` variable, which could mean that we'd
31 //! auto-borrow later arguments but not earlier ones, which
32 //! seems very confusing.
36 //! However, right now, if the user manually specifies the
37 //! values for the type variables, as so:
39 //! foo::<&int>(@1, @2)
41 //! then we *will* auto-borrow, because we can't distinguish this from a
42 //! function that declared `&int`. This is inconsistent but it's easiest
43 //! at the moment. The right thing to do, I think, is to consider the
44 //! *unsubstituted* type when deciding whether to auto-borrow, but the
45 //! *substituted* type when considering the bounds and so forth. But most
46 //! of our methods don't give access to the unsubstituted type, and
47 //! rightly so because they'd be error-prone. So maybe the thing to do is
48 //! to actually determine the kind of coercions that should occur
49 //! separately and pass them in. Or maybe it's ok as is. Anyway, it's
50 //! sort of a minor point so I've opted to leave it for later -- after all,
51 //! we may want to adjust precisely when coercions occur.
53 use crate::check::{FnCtxt, Needs};
54 use errors::DiagnosticBuilder;
56 use rustc::hir::def_id::DefId;
57 use rustc::hir::ptr::P;
58 use rustc::infer::{Coercion, InferResult, InferOk};
59 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
60 use rustc::traits::{self, ObligationCause, ObligationCauseCode};
61 use rustc::ty::adjustment::{
62 Adjustment, Adjust, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast
64 use rustc::ty::{self, TypeAndMut, Ty};
65 use rustc::ty::fold::TypeFoldable;
66 use rustc::ty::error::TypeError;
67 use rustc::ty::relate::RelateResult;
68 use rustc::ty::subst::SubstsRef;
69 use smallvec::{smallvec, SmallVec};
71 use syntax::feature_gate;
72 use syntax::symbol::sym;
74 use rustc_target::spec::abi::Abi;
76 use rustc_error_codes::*;
78 struct Coerce<'a, 'tcx> {
79 fcx: &'a FnCtxt<'a, 'tcx>,
80 cause: ObligationCause<'tcx>,
82 /// Determines whether or not allow_two_phase_borrow is set on any
83 /// autoref adjustments we create while coercing. We don't want to
84 /// allow deref coercions to create two-phase borrows, at least initially,
85 /// but we do need two-phase borrows for function argument reborrows.
86 /// See #47489 and #48598
87 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
88 allow_two_phase: AllowTwoPhase,
91 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
92 type Target = FnCtxt<'a, 'tcx>;
93 fn deref(&self) -> &Self::Target {
98 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'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::Mutability::Mutable, hir::Mutability::Mutable) |
105 (hir::Mutability::Immutable, hir::Mutability::Immutable) |
106 (hir::Mutability::Mutable, hir::Mutability::Immutable) => Ok(()),
107 (hir::Mutability::Immutable, hir::Mutability::Mutable) => Err(TypeError::Mutability),
111 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> { vec![] }
113 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
114 move |target| vec![Adjustment { kind, target }]
117 fn success<'tcx>(adj: Vec<Adjustment<'tcx>>,
119 obligations: traits::PredicateObligations<'tcx>)
120 -> CoerceResult<'tcx> {
122 value: (adj, target),
127 impl<'f, 'tcx> Coerce<'f, 'tcx> {
129 fcx: &'f FnCtxt<'f, 'tcx>,
130 cause: ObligationCause<'tcx>,
131 allow_two_phase: AllowTwoPhase,
141 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
142 self.commit_if_ok(|_| {
144 self.at(&self.cause, self.fcx.param_env).lub(b, a)
146 self.at(&self.cause, self.fcx.param_env)
148 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
153 /// Unify two types (using sub or lub) and produce a specific coercion.
154 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F)
155 -> CoerceResult<'tcx>
156 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
158 self.unify(&a, &b).and_then(|InferOk { value: ty, obligations }| {
159 success(f(ty), ty, obligations)
163 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
164 let a = self.shallow_resolve(a);
165 debug!("Coerce.tys({:?} => {:?})", a, b);
167 // Just ignore error types.
168 if a.references_error() || b.references_error() {
169 return success(vec![], self.fcx.tcx.types.err, vec![]);
173 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
174 // type variable, we want `?T` to fallback to `!` if not
175 // otherwise constrained. An example where this arises:
177 // let _: Option<?T> = Some({ return; });
179 // here, we would coerce from `!` to `?T`.
180 let b = self.shallow_resolve(b);
181 return if self.shallow_resolve(b).is_ty_var() {
182 // Micro-optimization: no need for this if `b` is
183 // already resolved in some way.
184 let diverging_ty = self.next_diverging_ty_var(
186 kind: TypeVariableOriginKind::AdjustmentType,
187 span: 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));
204 debug!("coerce: unsize successful");
207 Err(TypeError::ObjectUnsafeCoercion(did)) => {
208 debug!("coerce: unsize not object safe");
209 return Err(TypeError::ObjectUnsafeCoercion(did));
213 debug!("coerce: unsize failed");
215 // Examine the supertype and consider auto-borrowing.
217 // Note: does not attempt to resolve type variables we encounter.
218 // See above for details.
220 ty::RawPtr(mt_b) => {
221 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
224 ty::Ref(r_b, ty, mutbl) => {
225 let mt_b = ty::TypeAndMut { ty, mutbl };
226 return self.coerce_borrowed_pointer(a, b, r_b, mt_b);
234 // Function items are coercible to any closure
235 // type; function pointers are not (that would
236 // require double indirection).
237 // Additionally, we permit coercion of function
238 // items to drop the unsafe qualifier.
239 self.coerce_from_fn_item(a, b)
242 // We permit coercion of fn pointers to drop the
244 self.coerce_from_fn_pointer(a, a_f, b)
246 ty::Closure(def_id_a, substs_a) => {
247 // Non-capturing closures are coercible to
248 // function pointers or unsafe function pointers.
249 // It cannot convert closures that require unsafe.
250 self.coerce_closure_to_fn(a, def_id_a, substs_a, b)
253 // Otherwise, just use unification rules.
254 self.unify_and(a, b, identity)
259 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
260 /// To match `A` with `B`, autoderef will be performed,
261 /// calling `deref`/`deref_mut` where necessary.
262 fn coerce_borrowed_pointer(&self,
265 r_b: ty::Region<'tcx>,
266 mt_b: TypeAndMut<'tcx>)
267 -> CoerceResult<'tcx>
269 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
271 // If we have a parameter of type `&M T_a` and the value
272 // provided is `expr`, we will be adding an implicit borrow,
273 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
274 // to type check, we will construct the type that `&M*expr` would
277 let (r_a, mt_a) = match a.kind {
278 ty::Ref(r_a, ty, mutbl) => {
279 let mt_a = ty::TypeAndMut { ty, mutbl };
280 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
283 _ => return self.unify_and(a, b, identity),
286 let span = self.cause.span;
288 let mut first_error = None;
289 let mut r_borrow_var = None;
290 let mut autoderef = self.autoderef(span, a);
291 let mut found = None;
293 for (referent_ty, autoderefs) in autoderef.by_ref() {
295 // Don't let this pass, otherwise it would cause
296 // &T to autoref to &&T.
300 // At this point, we have deref'd `a` to `referent_ty`. So
301 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
302 // In the autoderef loop for `&'a mut Vec<T>`, we would get
305 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
306 // - `Vec<T>` -- 1 deref
307 // - `[T]` -- 2 deref
309 // At each point after the first callback, we want to
310 // check to see whether this would match out target type
311 // (`&'b mut [T]`) if we autoref'd it. We can't just
312 // compare the referent types, though, because we still
313 // have to consider the mutability. E.g., in the case
314 // we've been considering, we have an `&mut` reference, so
315 // the `T` in `[T]` needs to be unified with equality.
317 // Therefore, we construct reference types reflecting what
318 // the types will be after we do the final auto-ref and
319 // compare those. Note that this means we use the target
320 // mutability [1], since it may be that we are coercing
321 // from `&mut T` to `&U`.
323 // One fine point concerns the region that we use. We
324 // choose the region such that the region of the final
325 // type that results from `unify` will be the region we
326 // want for the autoref:
328 // - if in sub mode, that means we want to use `'b` (the
329 // region from the target reference) for both
330 // pointers [2]. This is because sub mode (somewhat
331 // arbitrarily) returns the subtype region. In the case
332 // where we are coercing to a target type, we know we
333 // want to use that target type region (`'b`) because --
334 // for the program to type-check -- it must be the
335 // smaller of the two.
336 // - One fine point. It may be surprising that we can
337 // use `'b` without relating `'a` and `'b`. The reason
338 // that this is ok is that what we produce is
339 // effectively a `&'b *x` expression (if you could
340 // annotate the region of a borrow), and regionck has
341 // code that adds edges from the region of a borrow
342 // (`'b`, here) into the regions in the borrowed
343 // expression (`*x`, here). (Search for "link".)
344 // - if in lub mode, things can get fairly complicated. The
345 // easiest thing is just to make a fresh
346 // region variable [4], which effectively means we defer
347 // the decision to region inference (and regionck, which will add
348 // some more edges to this variable). However, this can wind up
349 // creating a crippling number of variables in some cases --
350 // e.g., #32278 -- so we optimize one particular case [3].
351 // Let me try to explain with some examples:
352 // - The "running example" above represents the simple case,
353 // where we have one `&` reference at the outer level and
354 // ownership all the rest of the way down. In this case,
355 // we want `LUB('a, 'b)` as the resulting region.
356 // - However, if there are nested borrows, that region is
357 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
358 // `&'b T`. In this case, `'a` is actually irrelevant.
359 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
360 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
361 // (The errors actually show up in borrowck, typically, because
362 // this extra edge causes the region `'a` to be inferred to something
363 // too big, which then results in borrowck errors.)
364 // - We could track the innermost shared reference, but there is already
365 // code in regionck that has the job of creating links between
366 // the region of a borrow and the regions in the thing being
367 // borrowed (here, `'a` and `'x`), and it knows how to handle
368 // all the various cases. So instead we just make a region variable
369 // and let regionck figure it out.
370 let r = if !self.use_lub {
372 } else if autoderefs == 1 {
375 if r_borrow_var.is_none() {
376 // create var lazilly, at most once
377 let coercion = Coercion(span);
378 let r = self.next_region_var(coercion);
379 r_borrow_var = Some(r); // [4] above
381 r_borrow_var.unwrap()
383 let derefd_ty_a = self.tcx.mk_ref(r,
386 mutbl: mt_b.mutbl, // [1] above
388 match self.unify(derefd_ty_a, b) {
394 if first_error.is_none() {
395 first_error = Some(err);
401 // Extract type or return an error. We return the first error
402 // we got, which should be from relating the "base" type
403 // (e.g., in example above, the failure from relating `Vec<T>`
404 // to the target type), since that should be the least
406 let InferOk { value: ty, mut obligations } = match found {
409 let err = first_error.expect("coerce_borrowed_pointer had no error");
410 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
415 if ty == a && mt_a.mutbl == hir::Mutability::Immutable && autoderef.step_count() == 1 {
416 // As a special case, if we would produce `&'a *x`, that's
417 // a total no-op. We end up with the type `&'a T` just as
418 // we started with. In that case, just skip it
419 // altogether. This is just an optimization.
421 // Note that for `&mut`, we DO want to reborrow --
422 // otherwise, this would be a move, which might be an
423 // error. For example `foo(self.x)` where `self` and
424 // `self.x` both have `&mut `type would be a move of
425 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
426 // which is a borrow.
427 assert_eq!(mt_b.mutbl, hir::Mutability::Immutable); // can only coerce &T -> &U
428 return success(vec![], ty, obligations);
431 let needs = Needs::maybe_mut_place(mt_b.mutbl);
432 let InferOk { value: mut adjustments, obligations: o }
433 = autoderef.adjust_steps_as_infer_ok(self, needs);
434 obligations.extend(o);
435 obligations.extend(autoderef.into_obligations());
437 // Now apply the autoref. We have to extract the region out of
438 // the final ref type we got.
439 let r_borrow = match ty.kind {
440 ty::Ref(r_borrow, _, _) => r_borrow,
441 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
443 let mutbl = match mt_b.mutbl {
444 hir::Mutability::Immutable => AutoBorrowMutability::Immutable,
445 hir::Mutability::Mutable => AutoBorrowMutability::Mutable {
446 allow_two_phase_borrow: self.allow_two_phase,
449 adjustments.push(Adjustment {
450 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
454 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}",
458 success(adjustments, ty, obligations)
462 // &[T; n] or &mut [T; n] -> &[T]
463 // or &mut [T; n] -> &mut [T]
464 // or &Concrete -> &Trait, etc.
465 fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
466 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
468 let traits = (self.tcx.lang_items().unsize_trait(),
469 self.tcx.lang_items().coerce_unsized_trait());
470 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
473 debug!("missing Unsize or CoerceUnsized traits");
474 return Err(TypeError::Mismatch);
477 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
478 // a DST unless we have to. This currently comes out in the wash since
479 // we can't unify [T] with U. But to properly support DST, we need to allow
480 // that, at which point we will need extra checks on the target here.
482 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
483 let reborrow = match (&source.kind, &target.kind) {
484 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
485 coerce_mutbls(mutbl_a, mutbl_b)?;
487 let coercion = Coercion(self.cause.span);
488 let r_borrow = self.next_region_var(coercion);
489 let mutbl = match mutbl_b {
490 hir::Mutability::Immutable => AutoBorrowMutability::Immutable,
491 hir::Mutability::Mutable => AutoBorrowMutability::Mutable {
492 // We don't allow two-phase borrows here, at least for initial
493 // implementation. If it happens that this coercion is a function argument,
494 // the reborrow in coerce_borrowed_ptr will pick it up.
495 allow_two_phase_borrow: AllowTwoPhase::No,
499 kind: Adjust::Deref(None),
502 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
503 target: self.tcx.mk_ref(r_borrow, ty::TypeAndMut {
509 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
510 coerce_mutbls(mt_a, mt_b)?;
513 kind: Adjust::Deref(None),
516 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
517 target: self.tcx.mk_ptr(ty::TypeAndMut {
525 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
527 // Setup either a subtyping or a LUB relationship between
528 // the `CoerceUnsized` target type and the expected type.
529 // We only have the latter, so we use an inference variable
530 // for the former and let type inference do the rest.
531 let origin = TypeVariableOrigin {
532 kind: TypeVariableOriginKind::MiscVariable,
533 span: self.cause.span,
535 let coerce_target = self.next_ty_var(origin);
536 let mut coercion = self.unify_and(coerce_target, target, |target| {
537 let unsize = Adjustment {
538 kind: Adjust::Pointer(PointerCast::Unsize),
542 None => vec![unsize],
543 Some((ref deref, ref autoref)) => {
544 vec![deref.clone(), autoref.clone(), unsize]
549 let mut selcx = traits::SelectionContext::new(self);
551 // Create an obligation for `Source: CoerceUnsized<Target>`.
552 let cause = ObligationCause::new(
555 ObligationCauseCode::Coercion { source, target },
558 // Use a FIFO queue for this custom fulfillment procedure.
560 // A Vec (or SmallVec) is not a natural choice for a queue. However,
561 // this code path is hot, and this queue usually has a max length of 1
562 // and almost never more than 3. By using a SmallVec we avoid an
563 // allocation, at the (very small) cost of (occasionally) having to
564 // shift subsequent elements down when removing the front element.
565 let mut queue: SmallVec<[_; 4]> =
566 smallvec![self.tcx.predicate_for_trait_def(self.fcx.param_env,
571 &[coerce_target.into()])];
573 let mut has_unsized_tuple_coercion = false;
575 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
576 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
577 // inference might unify those two inner type variables later.
578 let traits = [coerce_unsized_did, unsize_did];
579 while !queue.is_empty() {
580 let obligation = queue.remove(0);
581 debug!("coerce_unsized resolve step: {:?}", obligation);
582 let trait_ref = match obligation.predicate {
583 ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => {
584 if unsize_did == tr.def_id() {
585 let sty = &tr.skip_binder().input_types().nth(1).unwrap().kind;
586 if let ty::Tuple(..) = sty {
587 debug!("coerce_unsized: found unsized tuple coercion");
588 has_unsized_tuple_coercion = true;
594 coercion.obligations.push(obligation);
598 match selcx.select(&obligation.with(trait_ref)) {
599 // Uncertain or unimplemented.
601 if trait_ref.def_id() == unsize_did {
602 let trait_ref = self.resolve_vars_if_possible(&trait_ref);
603 let self_ty = trait_ref.skip_binder().self_ty();
604 let unsize_ty = trait_ref.skip_binder().input_types().nth(1).unwrap();
605 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_ref);
606 match (&self_ty.kind, &unsize_ty.kind) {
607 (ty::Infer(ty::TyVar(v)),
608 ty::Dynamic(..)) if self.type_var_is_sized(*v) => {
609 debug!("coerce_unsized: have sized infer {:?}", v);
610 coercion.obligations.push(obligation);
611 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
615 // Some other case for `$0: Unsize<Something>`. Note that we
616 // hit this case even if `Something` is a sized type, so just
617 // don't do the coercion.
618 debug!("coerce_unsized: ambiguous unsize");
619 return Err(TypeError::Mismatch);
623 debug!("coerce_unsized: early return - ambiguous");
624 return Err(TypeError::Mismatch);
627 Err(traits::Unimplemented) => {
628 debug!("coerce_unsized: early return - can't prove obligation");
629 return Err(TypeError::Mismatch);
632 // Object safety violations or miscellaneous.
634 self.report_selection_error(&obligation, &err, false, false);
635 // Treat this like an obligation and follow through
636 // with the unsizing - the lack of a coercion should
637 // be silent, as it causes a type mismatch later.
640 Ok(Some(vtable)) => {
641 queue.extend(vtable.nested_obligations())
646 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
647 feature_gate::feature_err(
648 &self.tcx.sess.parse_sess,
649 sym::unsized_tuple_coercion,
651 "unsized tuple coercion is not stable enough for use and is subject to change",
659 fn coerce_from_safe_fn<F, G>(&self,
661 fn_ty_a: ty::PolyFnSig<'tcx>,
665 -> CoerceResult<'tcx>
666 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
667 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
669 if let ty::FnPtr(fn_ty_b) = b.kind {
670 if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe)
671 = (fn_ty_a.unsafety(), fn_ty_b.unsafety())
673 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
674 return self.unify_and(unsafe_a, b, to_unsafe);
677 self.unify_and(a, b, normal)
680 fn coerce_from_fn_pointer(&self,
682 fn_ty_a: ty::PolyFnSig<'tcx>,
684 -> CoerceResult<'tcx> {
685 //! Attempts to coerce from the type of a Rust function item
686 //! into a closure or a `proc`.
689 let b = self.shallow_resolve(b);
690 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
692 self.coerce_from_safe_fn(a, fn_ty_a, b,
693 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)), identity)
696 fn coerce_from_fn_item(&self,
699 -> CoerceResult<'tcx> {
700 //! Attempts to coerce from the type of a Rust function item
701 //! into a closure or a `proc`.
703 let b = self.shallow_resolve(b);
704 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
708 let a_sig = a.fn_sig(self.tcx);
709 // Intrinsics are not coercible to function pointers
710 if a_sig.abi() == Abi::RustIntrinsic ||
711 a_sig.abi() == Abi::PlatformIntrinsic {
712 return Err(TypeError::IntrinsicCast);
714 let InferOk { value: a_sig, mut obligations } =
715 self.normalize_associated_types_in_as_infer_ok(self.cause.span, &a_sig);
717 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
718 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
725 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
729 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
734 simple(Adjust::Pointer(PointerCast::ReifyFnPointer))
737 obligations.extend(o2);
738 Ok(InferOk { value, obligations })
740 _ => self.unify_and(a, b, identity),
744 fn coerce_closure_to_fn(&self,
747 substs_a: SubstsRef<'tcx>,
749 -> CoerceResult<'tcx> {
750 //! Attempts to coerce from the type of a non-capturing closure
751 //! into a function pointer.
754 let b = self.shallow_resolve(b);
757 ty::FnPtr(fn_ty) if self.tcx.upvars(def_id_a).map_or(true, |v| v.is_empty()) => {
758 // We coerce the closure, which has fn type
759 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
761 // `fn(arg0,arg1,...) -> _`
763 // `unsafe fn(arg0,arg1,...) -> _`
764 let sig = self.closure_sig(def_id_a, substs_a);
765 let unsafety = fn_ty.unsafety();
766 let pointer_ty = self.tcx.coerce_closure_fn_ty(sig, unsafety);
767 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})",
769 self.unify_and(pointer_ty, b, simple(
770 Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))
773 _ => self.unify_and(a, b, identity),
777 fn coerce_unsafe_ptr(&self,
780 mutbl_b: hir::Mutability)
781 -> CoerceResult<'tcx> {
782 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
784 let (is_ref, mt_a) = match a.kind {
785 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
786 ty::RawPtr(mt) => (false, mt),
787 _ => return self.unify_and(a, b, identity)
790 // Check that the types which they point at are compatible.
791 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut {
795 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
796 // Although references and unsafe ptrs have the same
797 // representation, we still register an Adjust::DerefRef so that
798 // regionck knows that the region for `a` must be valid here.
800 self.unify_and(a_unsafe, b, |target| {
802 kind: Adjust::Deref(None),
805 kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
809 } else if mt_a.mutbl != mutbl_b {
811 a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer))
814 self.unify_and(a_unsafe, b, identity)
819 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
820 /// Attempt to coerce an expression to a type, and return the
821 /// adjusted type of the expression, if successful.
822 /// Adjustments are only recorded if the coercion succeeded.
823 /// The expressions *must not* have any pre-existing adjustments.
829 allow_two_phase: AllowTwoPhase,
830 ) -> RelateResult<'tcx, Ty<'tcx>> {
831 let source = self.resolve_vars_with_obligations(expr_ty);
832 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
834 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
835 let coerce = Coerce::new(self, cause, allow_two_phase);
836 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
838 let (adjustments, _) = self.register_infer_ok_obligations(ok);
839 self.apply_adjustments(expr, adjustments);
840 Ok(if expr_ty.references_error() {
847 /// Same as `try_coerce()`, but without side-effects.
848 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
849 let source = self.resolve_vars_with_obligations(expr_ty);
850 debug!("coercion::can({:?} -> {:?})", source, target);
852 let cause = self.cause(syntax_pos::DUMMY_SP, ObligationCauseCode::ExprAssignable);
853 // We don't ever need two-phase here since we throw out the result of the coercion
854 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
855 self.probe(|_| coerce.coerce(source, target)).is_ok()
858 /// Given some expressions, their known unified type and another expression,
859 /// tries to unify the types, potentially inserting coercions on any of the
860 /// provided expressions and returns their LUB (aka "common supertype").
862 /// This is really an internal helper. From outside the coercion
863 /// module, you should instantiate a `CoerceMany` instance.
864 fn try_find_coercion_lub<E>(&self,
865 cause: &ObligationCause<'tcx>,
870 -> RelateResult<'tcx, Ty<'tcx>>
871 where E: AsCoercionSite
873 let prev_ty = self.resolve_vars_with_obligations(prev_ty);
874 let new_ty = self.resolve_vars_with_obligations(new_ty);
875 debug!("coercion::try_find_coercion_lub({:?}, {:?})", prev_ty, new_ty);
877 // Special-case that coercion alone cannot handle:
878 // Two function item types of differing IDs or InternalSubsts.
879 if let (&ty::FnDef(..), &ty::FnDef(..)) = (&prev_ty.kind, &new_ty.kind) {
880 // Don't reify if the function types have a LUB, i.e., they
881 // are the same function and their parameters have a LUB.
882 let lub_ty = self.commit_if_ok(|_| {
883 self.at(cause, self.param_env)
884 .lub(prev_ty, new_ty)
885 }).map(|ok| self.register_infer_ok_obligations(ok));
888 // We have a LUB of prev_ty and new_ty, just return it.
892 // The signature must match.
893 let a_sig = prev_ty.fn_sig(self.tcx);
894 let a_sig = self.normalize_associated_types_in(new.span, &a_sig);
895 let b_sig = new_ty.fn_sig(self.tcx);
896 let b_sig = self.normalize_associated_types_in(new.span, &b_sig);
897 let sig = self.at(cause, self.param_env)
898 .trace(prev_ty, new_ty)
900 .map(|ok| self.register_infer_ok_obligations(ok))?;
902 // Reify both sides and return the reified fn pointer type.
903 let fn_ptr = self.tcx.mk_fn_ptr(sig);
904 for expr in exprs.iter().map(|e| e.as_coercion_site()).chain(Some(new)) {
905 // The only adjustment that can produce an fn item is
906 // `NeverToAny`, so this should always be valid.
907 self.apply_adjustments(expr, vec![Adjustment {
908 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
915 // Configure a Coerce instance to compute the LUB.
916 // We don't allow two-phase borrows on any autorefs this creates since we
917 // probably aren't processing function arguments here and even if we were,
918 // they're going to get autorefed again anyway and we can apply 2-phase borrows
920 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
921 coerce.use_lub = true;
923 // First try to coerce the new expression to the type of the previous ones,
924 // but only if the new expression has no coercion already applied to it.
925 let mut first_error = None;
926 if !self.tables.borrow().adjustments().contains_key(new.hir_id) {
927 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
930 let (adjustments, target) = self.register_infer_ok_obligations(ok);
931 self.apply_adjustments(new, adjustments);
934 Err(e) => first_error = Some(e),
938 // Then try to coerce the previous expressions to the type of the new one.
939 // This requires ensuring there are no coercions applied to *any* of the
940 // previous expressions, other than noop reborrows (ignoring lifetimes).
942 let expr = expr.as_coercion_site();
943 let noop = match self.tables.borrow().expr_adjustments(expr) {
945 Adjustment { kind: Adjust::Deref(_), .. },
946 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }
948 match self.node_ty(expr.hir_id).kind {
949 ty::Ref(_, _, mt_orig) => {
950 let mutbl_adj: hir::Mutability = mutbl_adj.into();
951 // Reborrow that we can safely ignore, because
952 // the next adjustment can only be a Deref
953 // which will be merged into it.
959 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
964 return self.commit_if_ok(|_|
965 self.at(cause, self.param_env)
966 .lub(prev_ty, new_ty)
967 ).map(|ok| self.register_infer_ok_obligations(ok));
971 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
973 // Avoid giving strange errors on failed attempts.
974 if let Some(e) = first_error {
977 self.commit_if_ok(|_|
978 self.at(cause, self.param_env)
979 .lub(prev_ty, new_ty)
980 ).map(|ok| self.register_infer_ok_obligations(ok))
984 let (adjustments, target) = self.register_infer_ok_obligations(ok);
986 let expr = expr.as_coercion_site();
987 self.apply_adjustments(expr, adjustments.clone());
995 /// CoerceMany encapsulates the pattern you should use when you have
996 /// many expressions that are all getting coerced to a common
997 /// type. This arises, for example, when you have a match (the result
998 /// of each arm is coerced to a common type). It also arises in less
999 /// obvious places, such as when you have many `break foo` expressions
1000 /// that target the same loop, or the various `return` expressions in
1003 /// The basic protocol is as follows:
1005 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1006 /// This will also serve as the "starting LUB". The expectation is
1007 /// that this type is something which all of the expressions *must*
1008 /// be coercible to. Use a fresh type variable if needed.
1009 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1010 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1011 /// unit. This happens for example if you have a `break` with no expression,
1012 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1013 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1014 /// from you so that you don't have to worry your pretty head about it.
1015 /// But if an error is reported, the final type will be `err`.
1016 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1017 /// previously coerced expressions.
1018 /// - When all done, invoke `complete()`. This will return the LUB of
1019 /// all your expressions.
1020 /// - WARNING: I don't believe this final type is guaranteed to be
1021 /// related to your initial `expected_ty` in any particular way,
1022 /// although it will typically be a subtype, so you should check it.
1023 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1024 /// previously coerced expressions.
1029 /// let mut coerce = CoerceMany::new(expected_ty);
1030 /// for expr in exprs {
1031 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1032 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1034 /// let final_ty = coerce.complete(fcx);
1036 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1037 expected_ty: Ty<'tcx>,
1038 final_ty: Option<Ty<'tcx>>,
1039 expressions: Expressions<'tcx, 'exprs, E>,
1043 /// The type of a `CoerceMany` that is storing up the expressions into
1044 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1045 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, P<hir::Expr>>;
1047 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1048 Dynamic(Vec<&'tcx hir::Expr>),
1049 UpFront(&'exprs [E]),
1052 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1053 /// The usual case; collect the set of expressions dynamically.
1054 /// If the full set of coercion sites is known before hand,
1055 /// consider `with_coercion_sites()` instead to avoid allocation.
1056 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1057 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1060 /// As an optimization, you can create a `CoerceMany` with a
1061 /// pre-existing slice of expressions. In this case, you are
1062 /// expected to pass each element in the slice to `coerce(...)` in
1063 /// order. This is used with arrays in particular to avoid
1064 /// needlessly cloning the slice.
1065 pub fn with_coercion_sites(expected_ty: Ty<'tcx>,
1066 coercion_sites: &'exprs [E])
1068 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1071 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1080 /// Returns the "expected type" with which this coercion was
1081 /// constructed. This represents the "downward propagated" type
1082 /// that was given to us at the start of typing whatever construct
1083 /// we are typing (e.g., the match expression).
1085 /// Typically, this is used as the expected type when
1086 /// type-checking each of the alternative expressions whose types
1087 /// we are trying to merge.
1088 pub fn expected_ty(&self) -> Ty<'tcx> {
1092 /// Returns the current "merged type", representing our best-guess
1093 /// at the LUB of the expressions we've seen so far (if any). This
1094 /// isn't *final* until you call `self.final()`, which will return
1095 /// the merged type.
1096 pub fn merged_ty(&self) -> Ty<'tcx> {
1097 self.final_ty.unwrap_or(self.expected_ty)
1100 /// Indicates that the value generated by `expression`, which is
1101 /// of type `expression_ty`, is one of the possibilities that we
1102 /// could coerce from. This will record `expression`, and later
1103 /// calls to `coerce` may come back and add adjustments and things
1107 fcx: &FnCtxt<'a, 'tcx>,
1108 cause: &ObligationCause<'tcx>,
1109 expression: &'tcx hir::Expr,
1110 expression_ty: Ty<'tcx>,
1112 self.coerce_inner(fcx,
1119 /// Indicates that one of the inputs is a "forced unit". This
1120 /// occurs in a case like `if foo { ... };`, where the missing else
1121 /// generates a "forced unit". Another example is a `loop { break;
1122 /// }`, where the `break` has no argument expression. We treat
1123 /// these cases slightly differently for error-reporting
1124 /// purposes. Note that these tend to correspond to cases where
1125 /// the `()` expression is implicit in the source, and hence we do
1126 /// not take an expression argument.
1128 /// The `augment_error` gives you a chance to extend the error
1129 /// message, in case any results (e.g., we use this to suggest
1130 /// removing a `;`).
1131 pub fn coerce_forced_unit<'a>(
1133 fcx: &FnCtxt<'a, 'tcx>,
1134 cause: &ObligationCause<'tcx>,
1135 augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1136 label_unit_as_expected: bool,
1138 self.coerce_inner(fcx,
1142 Some(augment_error),
1143 label_unit_as_expected)
1146 /// The inner coercion "engine". If `expression` is `None`, this
1147 /// is a forced-unit case, and hence `expression_ty` must be
1149 fn coerce_inner<'a>(
1151 fcx: &FnCtxt<'a, 'tcx>,
1152 cause: &ObligationCause<'tcx>,
1153 expression: Option<&'tcx hir::Expr>,
1154 mut expression_ty: Ty<'tcx>,
1155 augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1156 label_expression_as_expected: bool,
1158 // Incorporate whatever type inference information we have
1159 // until now; in principle we might also want to process
1160 // pending obligations, but doing so should only improve
1161 // compatibility (hopefully that is true) by helping us
1162 // uncover never types better.
1163 if expression_ty.is_ty_var() {
1164 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1167 // If we see any error types, just propagate that error
1169 if expression_ty.references_error() || self.merged_ty().references_error() {
1170 self.final_ty = Some(fcx.tcx.types.err);
1174 // Handle the actual type unification etc.
1175 let result = if let Some(expression) = expression {
1176 if self.pushed == 0 {
1177 // Special-case the first expression we are coercing.
1178 // To be honest, I'm not entirely sure why we do this.
1179 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1180 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1182 match self.expressions {
1183 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1190 Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1192 &coercion_sites[0..self.pushed],
1200 // this is a hack for cases where we default to `()` because
1201 // the expression etc has been omitted from the source. An
1202 // example is an `if let` without an else:
1204 // if let Some(x) = ... { }
1206 // we wind up with a second match arm that is like `_ =>
1207 // ()`. That is the case we are considering here. We take
1208 // a different path to get the right "expected, found"
1209 // message and so forth (and because we know that
1210 // `expression_ty` will be unit).
1212 // Another example is `break` with no argument expression.
1213 assert!(expression_ty.is_unit(), "if let hack without unit type");
1214 fcx.at(cause, fcx.param_env)
1215 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1217 fcx.register_infer_ok_obligations(infer_ok);
1224 self.final_ty = Some(v);
1225 if let Some(e) = expression {
1226 match self.expressions {
1227 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1228 Expressions::UpFront(coercion_sites) => {
1229 // if the user gave us an array to validate, check that we got
1230 // the next expression in the list, as expected
1231 assert_eq!(coercion_sites[self.pushed].as_coercion_site().hir_id,
1238 Err(coercion_error) => {
1239 let (expected, found) = if label_expression_as_expected {
1240 // In the case where this is a "forced unit", like
1241 // `break`, we want to call the `()` "expected"
1242 // since it is implied by the syntax.
1243 // (Note: not all force-units work this way.)"
1244 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1246 // Otherwise, the "expected" type for error
1247 // reporting is the current unification type,
1248 // which is basically the LUB of the expressions
1249 // we've seen so far (combined with the expected
1251 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1256 ObligationCauseCode::ReturnNoExpression => {
1257 err = struct_span_err!(
1258 fcx.tcx.sess, cause.span, E0069,
1259 "`return;` in a function whose return type is not `()`");
1260 err.span_label(cause.span, "return type is not `()`");
1262 ObligationCauseCode::BlockTailExpression(blk_id) => {
1263 let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1264 err = self.report_return_mismatched_types(
1271 expression.map(|expr| (expr, blk_id)),
1274 ObligationCauseCode::ReturnValue(id) => {
1275 err = self.report_return_mismatched_types(
1276 cause, expected, found, coercion_error, fcx, id, None);
1279 err = fcx.report_mismatched_types(cause, expected, found, coercion_error);
1283 if let Some(augment_error) = augment_error {
1284 augment_error(&mut err);
1287 if let Some(expr) = expression {
1288 fcx.emit_coerce_suggestions(&mut err, expr, found, expected);
1291 // Error possibly reported in `check_assign` so avoid emitting error again.
1292 err.emit_unless(expression.filter(|e| fcx.is_assign_to_bool(e, expected))
1295 self.final_ty = Some(fcx.tcx.types.err);
1300 fn report_return_mismatched_types<'a>(
1302 cause: &ObligationCause<'tcx>,
1305 ty_err: TypeError<'tcx>,
1306 fcx: &FnCtxt<'a, 'tcx>,
1308 expression: Option<(&'tcx hir::Expr, hir::HirId)>,
1309 ) -> DiagnosticBuilder<'a> {
1310 let mut err = fcx.report_mismatched_types(cause, expected, found, ty_err);
1312 let mut pointing_at_return_type = false;
1313 let mut return_sp = None;
1315 // Verify that this is a tail expression of a function, otherwise the
1316 // label pointing out the cause for the type coercion will be wrong
1317 // as prior return coercions would not be relevant (#57664).
1318 let parent_id = fcx.tcx.hir().get_parent_node(id);
1319 let fn_decl = if let Some((expr, blk_id)) = expression {
1320 pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1328 let parent = fcx.tcx.hir().get(parent_id);
1329 if let (Some(match_expr), true, false) = (
1330 fcx.tcx.hir().get_match_if_cause(expr.hir_id),
1332 pointing_at_return_type,
1334 if match_expr.span.desugaring_kind().is_none() {
1335 err.span_label(match_expr.span, "expected this to be `()`");
1336 fcx.suggest_semicolon_at_end(match_expr.span, &mut err);
1339 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1341 fcx.get_fn_decl(parent_id)
1344 if let (Some((fn_decl, can_suggest)), _) = (fn_decl, pointing_at_return_type) {
1345 if expression.is_none() {
1346 pointing_at_return_type |= fcx.suggest_missing_return_type(
1347 &mut err, &fn_decl, expected, found, can_suggest);
1349 if !pointing_at_return_type {
1350 return_sp = Some(fn_decl.output.span()); // `impl Trait` return type
1353 if let (Some(sp), Some(return_sp)) = (fcx.ret_coercion_span.borrow().as_ref(), return_sp) {
1354 err.span_label(return_sp, "expected because this return type...");
1355 err.span_label( *sp, format!(
1356 "...is found to be `{}` here",
1357 fcx.resolve_vars_with_obligations(expected),
1363 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1364 if let Some(final_ty) = self.final_ty {
1367 // If we only had inputs that were of type `!` (or no
1368 // inputs at all), then the final type is `!`.
1369 assert_eq!(self.pushed, 0);
1375 /// Something that can be converted into an expression to which we can
1376 /// apply a coercion.
1377 pub trait AsCoercionSite {
1378 fn as_coercion_site(&self) -> &hir::Expr;
1381 impl AsCoercionSite for hir::Expr {
1382 fn as_coercion_site(&self) -> &hir::Expr {
1387 impl AsCoercionSite for P<hir::Expr> {
1388 fn as_coercion_site(&self) -> &hir::Expr {
1393 impl<'a, T> AsCoercionSite for &'a T
1394 where T: AsCoercionSite
1396 fn as_coercion_site(&self) -> &hir::Expr {
1397 (**self).as_coercion_site()
1401 impl AsCoercionSite for ! {
1402 fn as_coercion_site(&self) -> &hir::Expr {
1407 impl AsCoercionSite for hir::Arm {
1408 fn as_coercion_site(&self) -> &hir::Expr {