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/run-pass/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::infer::{Coercion, InferResult, InferOk};
58 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
59 use rustc::traits::{self, ObligationCause, ObligationCauseCode};
60 use rustc::ty::adjustment::{
61 Adjustment, Adjust, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast
63 use rustc::ty::{self, TypeAndMut, Ty, ClosureSubsts};
64 use rustc::ty::fold::TypeFoldable;
65 use rustc::ty::error::TypeError;
66 use rustc::ty::relate::RelateResult;
67 use smallvec::{smallvec, SmallVec};
69 use syntax::feature_gate;
71 use syntax::symbol::sym;
74 struct Coerce<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
75 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
76 cause: ObligationCause<'tcx>,
78 /// Determines whether or not allow_two_phase_borrow is set on any
79 /// autoref adjustments we create while coercing. We don't want to
80 /// allow deref coercions to create two-phase borrows, at least initially,
81 /// but we do need two-phase borrows for function argument reborrows.
82 /// See #47489 and #48598
83 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
84 allow_two_phase: AllowTwoPhase,
87 impl<'a, 'gcx, 'tcx> Deref for Coerce<'a, 'gcx, 'tcx> {
88 type Target = FnCtxt<'a, 'gcx, 'tcx>;
89 fn deref(&self) -> &Self::Target {
94 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
96 fn coerce_mutbls<'tcx>(from_mutbl: hir::Mutability,
97 to_mutbl: hir::Mutability)
98 -> RelateResult<'tcx, ()> {
99 match (from_mutbl, to_mutbl) {
100 (hir::MutMutable, hir::MutMutable) |
101 (hir::MutImmutable, hir::MutImmutable) |
102 (hir::MutMutable, hir::MutImmutable) => Ok(()),
103 (hir::MutImmutable, hir::MutMutable) => Err(TypeError::Mutability),
107 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> { vec![] }
109 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
110 move |target| vec![Adjustment { kind, target }]
113 fn success<'tcx>(adj: Vec<Adjustment<'tcx>>,
115 obligations: traits::PredicateObligations<'tcx>)
116 -> CoerceResult<'tcx> {
118 value: (adj, target),
123 impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> {
124 fn new(fcx: &'f FnCtxt<'f, 'gcx, 'tcx>,
125 cause: ObligationCause<'tcx>,
126 allow_two_phase: AllowTwoPhase) -> Self {
135 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
136 self.commit_if_ok(|_| {
138 self.at(&self.cause, self.fcx.param_env).lub(b, a)
140 self.at(&self.cause, self.fcx.param_env)
142 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
147 /// Unify two types (using sub or lub) and produce a specific coercion.
148 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F)
149 -> CoerceResult<'tcx>
150 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
152 self.unify(&a, &b).and_then(|InferOk { value: ty, obligations }| {
153 success(f(ty), ty, obligations)
157 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
158 let a = self.shallow_resolve(a);
159 debug!("Coerce.tys({:?} => {:?})", a, b);
161 // Just ignore error types.
162 if a.references_error() || b.references_error() {
163 return success(vec![], b, vec![]);
167 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
168 // type variable, we want `?T` to fallback to `!` if not
169 // otherwise constrained. An example where this arises:
171 // let _: Option<?T> = Some({ return; });
173 // here, we would coerce from `!` to `?T`.
174 let b = self.shallow_resolve(b);
175 return if self.shallow_resolve(b).is_ty_var() {
176 // Micro-optimization: no need for this if `b` is
177 // already resolved in some way.
178 let diverging_ty = self.next_diverging_ty_var(
180 kind: TypeVariableOriginKind::AdjustmentType,
181 span: self.cause.span,
184 self.unify_and(&b, &diverging_ty, simple(Adjust::NeverToAny))
186 success(simple(Adjust::NeverToAny)(b), b, vec![])
190 // Consider coercing the subtype to a DST
192 // NOTE: this is wrapped in a `commit_if_ok` because it creates
193 // a "spurious" type variable, and we don't want to have that
194 // type variable in memory if the coercion fails.
195 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
197 debug!("coerce: unsize successful");
200 debug!("coerce: unsize failed");
202 // Examine the supertype and consider auto-borrowing.
204 // Note: does not attempt to resolve type variables we encounter.
205 // See above for details.
207 ty::RawPtr(mt_b) => {
208 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
211 ty::Ref(r_b, ty, mutbl) => {
212 let mt_b = ty::TypeAndMut { ty, mutbl };
213 return self.coerce_borrowed_pointer(a, b, r_b, mt_b);
221 // Function items are coercible to any closure
222 // type; function pointers are not (that would
223 // require double indirection).
224 // Additionally, we permit coercion of function
225 // items to drop the unsafe qualifier.
226 self.coerce_from_fn_item(a, b)
229 // We permit coercion of fn pointers to drop the
231 self.coerce_from_fn_pointer(a, a_f, b)
233 ty::Closure(def_id_a, substs_a) => {
234 // Non-capturing closures are coercible to
235 // function pointers or unsafe function pointers.
236 // It cannot convert closures that require unsafe.
237 self.coerce_closure_to_fn(a, def_id_a, substs_a, b)
240 // Otherwise, just use unification rules.
241 self.unify_and(a, b, identity)
246 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
247 /// To match `A` with `B`, autoderef will be performed,
248 /// calling `deref`/`deref_mut` where necessary.
249 fn coerce_borrowed_pointer(&self,
252 r_b: ty::Region<'tcx>,
253 mt_b: TypeAndMut<'tcx>)
254 -> CoerceResult<'tcx>
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::Ref(r_a, ty, mutbl) => {
266 let mt_a = ty::TypeAndMut { ty, mutbl };
267 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
270 _ => return self.unify_and(a, b, identity),
273 let span = self.cause.span;
275 let mut first_error = None;
276 let mut r_borrow_var = None;
277 let mut autoderef = self.autoderef(span, a);
278 let mut found = None;
280 for (referent_ty, autoderefs) in autoderef.by_ref() {
282 // Don't let this pass, otherwise it would cause
283 // &T to autoref to &&T.
287 // At this point, we have deref'd `a` to `referent_ty`. So
288 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
289 // In the autoderef loop for `&'a mut Vec<T>`, we would get
292 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
293 // - `Vec<T>` -- 1 deref
294 // - `[T]` -- 2 deref
296 // At each point after the first callback, we want to
297 // check to see whether this would match out target type
298 // (`&'b mut [T]`) if we autoref'd it. We can't just
299 // compare the referent types, though, because we still
300 // have to consider the mutability. E.g., in the case
301 // we've been considering, we have an `&mut` reference, so
302 // the `T` in `[T]` needs to be unified with equality.
304 // Therefore, we construct reference types reflecting what
305 // the types will be after we do the final auto-ref and
306 // compare those. Note that this means we use the target
307 // mutability [1], since it may be that we are coercing
308 // from `&mut T` to `&U`.
310 // One fine point concerns the region that we use. We
311 // choose the region such that the region of the final
312 // type that results from `unify` will be the region we
313 // want for the autoref:
315 // - if in sub mode, that means we want to use `'b` (the
316 // region from the target reference) for both
317 // pointers [2]. This is because sub mode (somewhat
318 // arbitrarily) returns the subtype region. In the case
319 // where we are coercing to a target type, we know we
320 // want to use that target type region (`'b`) because --
321 // for the program to type-check -- it must be the
322 // smaller of the two.
323 // - One fine point. It may be surprising that we can
324 // use `'b` without relating `'a` and `'b`. The reason
325 // that this is ok is that what we produce is
326 // effectively a `&'b *x` expression (if you could
327 // annotate the region of a borrow), and regionck has
328 // code that adds edges from the region of a borrow
329 // (`'b`, here) into the regions in the borrowed
330 // expression (`*x`, here). (Search for "link".)
331 // - if in lub mode, things can get fairly complicated. The
332 // easiest thing is just to make a fresh
333 // region variable [4], which effectively means we defer
334 // the decision to region inference (and regionck, which will add
335 // some more edges to this variable). However, this can wind up
336 // creating a crippling number of variables in some cases --
337 // e.g., #32278 -- so we optimize one particular case [3].
338 // Let me try to explain with some examples:
339 // - The "running example" above represents the simple case,
340 // where we have one `&` reference at the outer level and
341 // ownership all the rest of the way down. In this case,
342 // we want `LUB('a, 'b)` as the resulting region.
343 // - However, if there are nested borrows, that region is
344 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
345 // `&'b T`. In this case, `'a` is actually irrelevant.
346 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
347 // we get spurious errors (`run-pass/regions-lub-ref-ref-rc.rs`).
348 // (The errors actually show up in borrowck, typically, because
349 // this extra edge causes the region `'a` to be inferred to something
350 // too big, which then results in borrowck errors.)
351 // - We could track the innermost shared reference, but there is already
352 // code in regionck that has the job of creating links between
353 // the region of a borrow and the regions in the thing being
354 // borrowed (here, `'a` and `'x`), and it knows how to handle
355 // all the various cases. So instead we just make a region variable
356 // and let regionck figure it out.
357 let r = if !self.use_lub {
359 } else if autoderefs == 1 {
362 if r_borrow_var.is_none() {
363 // create var lazilly, at most once
364 let coercion = Coercion(span);
365 let r = self.next_region_var(coercion);
366 r_borrow_var = Some(r); // [4] above
368 r_borrow_var.unwrap()
370 let derefd_ty_a = self.tcx.mk_ref(r,
373 mutbl: mt_b.mutbl, // [1] above
375 match self.unify(derefd_ty_a, b) {
381 if first_error.is_none() {
382 first_error = Some(err);
388 // Extract type or return an error. We return the first error
389 // we got, which should be from relating the "base" type
390 // (e.g., in example above, the failure from relating `Vec<T>`
391 // to the target type), since that should be the least
393 let InferOk { value: ty, mut obligations } = match found {
396 let err = first_error.expect("coerce_borrowed_pointer had no error");
397 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
402 if ty == a && mt_a.mutbl == hir::MutImmutable && autoderef.step_count() == 1 {
403 // As a special case, if we would produce `&'a *x`, that's
404 // a total no-op. We end up with the type `&'a T` just as
405 // we started with. In that case, just skip it
406 // altogether. This is just an optimization.
408 // Note that for `&mut`, we DO want to reborrow --
409 // otherwise, this would be a move, which might be an
410 // error. For example `foo(self.x)` where `self` and
411 // `self.x` both have `&mut `type would be a move of
412 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
413 // which is a borrow.
414 assert_eq!(mt_b.mutbl, hir::MutImmutable); // can only coerce &T -> &U
415 return success(vec![], ty, obligations);
418 let needs = Needs::maybe_mut_place(mt_b.mutbl);
419 let InferOk { value: mut adjustments, obligations: o }
420 = autoderef.adjust_steps_as_infer_ok(self, needs);
421 obligations.extend(o);
422 obligations.extend(autoderef.into_obligations());
424 // Now apply the autoref. We have to extract the region out of
425 // the final ref type we got.
426 let r_borrow = match ty.sty {
427 ty::Ref(r_borrow, _, _) => r_borrow,
428 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
430 let mutbl = match mt_b.mutbl {
431 hir::MutImmutable => AutoBorrowMutability::Immutable,
432 hir::MutMutable => AutoBorrowMutability::Mutable {
433 allow_two_phase_borrow: self.allow_two_phase,
436 adjustments.push(Adjustment {
437 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
441 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}",
445 success(adjustments, ty, obligations)
449 // &[T; n] or &mut [T; n] -> &[T]
450 // or &mut [T; n] -> &mut [T]
451 // or &Concrete -> &Trait, etc.
452 fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
453 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
455 let traits = (self.tcx.lang_items().unsize_trait(),
456 self.tcx.lang_items().coerce_unsized_trait());
457 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
460 debug!("Missing Unsize or CoerceUnsized traits");
461 return Err(TypeError::Mismatch);
464 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
465 // a DST unless we have to. This currently comes out in the wash since
466 // we can't unify [T] with U. But to properly support DST, we need to allow
467 // that, at which point we will need extra checks on the target here.
469 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
470 let reborrow = match (&source.sty, &target.sty) {
471 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
472 coerce_mutbls(mutbl_a, mutbl_b)?;
474 let coercion = Coercion(self.cause.span);
475 let r_borrow = self.next_region_var(coercion);
476 let mutbl = match mutbl_b {
477 hir::MutImmutable => AutoBorrowMutability::Immutable,
478 hir::MutMutable => AutoBorrowMutability::Mutable {
479 // We don't allow two-phase borrows here, at least for initial
480 // implementation. If it happens that this coercion is a function argument,
481 // the reborrow in coerce_borrowed_ptr will pick it up.
482 allow_two_phase_borrow: AllowTwoPhase::No,
486 kind: Adjust::Deref(None),
489 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
490 target: self.tcx.mk_ref(r_borrow, ty::TypeAndMut {
496 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
497 coerce_mutbls(mt_a, mt_b)?;
500 kind: Adjust::Deref(None),
503 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
504 target: self.tcx.mk_ptr(ty::TypeAndMut {
512 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
514 // Setup either a subtyping or a LUB relationship between
515 // the `CoerceUnsized` target type and the expected type.
516 // We only have the latter, so we use an inference variable
517 // for the former and let type inference do the rest.
518 let origin = TypeVariableOrigin {
519 kind: TypeVariableOriginKind::MiscVariable,
520 span: self.cause.span,
522 let coerce_target = self.next_ty_var(origin);
523 let mut coercion = self.unify_and(coerce_target, target, |target| {
524 let unsize = Adjustment {
525 kind: Adjust::Pointer(PointerCast::Unsize),
529 None => vec![unsize],
530 Some((ref deref, ref autoref)) => {
531 vec![deref.clone(), autoref.clone(), unsize]
536 let mut selcx = traits::SelectionContext::new(self);
538 // Create an obligation for `Source: CoerceUnsized<Target>`.
539 let cause = ObligationCause::misc(self.cause.span, self.body_id);
541 // Use a FIFO queue for this custom fulfillment procedure.
543 // A Vec (or SmallVec) is not a natural choice for a queue. However,
544 // this code path is hot, and this queue usually has a max length of 1
545 // and almost never more than 3. By using a SmallVec we avoid an
546 // allocation, at the (very small) cost of (occasionally) having to
547 // shift subsequent elements down when removing the front element.
548 let mut queue: SmallVec<[_; 4]> =
549 smallvec![self.tcx.predicate_for_trait_def(self.fcx.param_env,
554 &[coerce_target.into()])];
556 let mut has_unsized_tuple_coercion = false;
558 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
559 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
560 // inference might unify those two inner type variables later.
561 let traits = [coerce_unsized_did, unsize_did];
562 while !queue.is_empty() {
563 let obligation = queue.remove(0);
564 debug!("coerce_unsized resolve step: {:?}", obligation);
565 let trait_ref = match obligation.predicate {
566 ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => {
567 if unsize_did == tr.def_id() {
568 let sty = &tr.skip_binder().input_types().nth(1).unwrap().sty;
569 if let ty::Tuple(..) = sty {
570 debug!("coerce_unsized: found unsized tuple coercion");
571 has_unsized_tuple_coercion = true;
577 coercion.obligations.push(obligation);
581 match selcx.select(&obligation.with(trait_ref)) {
582 // Uncertain or unimplemented.
584 if trait_ref.def_id() == unsize_did {
585 let trait_ref = self.resolve_vars_if_possible(&trait_ref);
586 let self_ty = trait_ref.skip_binder().self_ty();
587 let unsize_ty = trait_ref.skip_binder().input_types().nth(1).unwrap();
588 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_ref);
589 match (&self_ty.sty, &unsize_ty.sty) {
590 (ty::Infer(ty::TyVar(v)),
591 ty::Dynamic(..)) if self.type_var_is_sized(*v) => {
592 debug!("coerce_unsized: have sized infer {:?}", v);
593 coercion.obligations.push(obligation);
594 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
598 // Some other case for `$0: Unsize<Something>`. Note that we
599 // hit this case even if `Something` is a sized type, so just
600 // don't do the coercion.
601 debug!("coerce_unsized: ambiguous unsize");
602 return Err(TypeError::Mismatch);
606 debug!("coerce_unsized: early return - ambiguous");
607 return Err(TypeError::Mismatch);
610 Err(traits::Unimplemented) => {
611 debug!("coerce_unsized: early return - can't prove obligation");
612 return Err(TypeError::Mismatch);
615 // Object safety violations or miscellaneous.
617 self.report_selection_error(&obligation, &err, false);
618 // Treat this like an obligation and follow through
619 // with the unsizing - the lack of a coercion should
620 // be silent, as it causes a type mismatch later.
623 Ok(Some(vtable)) => {
624 queue.extend(vtable.nested_obligations())
629 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
630 feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
631 sym::unsized_tuple_coercion,
633 feature_gate::GateIssue::Language,
634 feature_gate::EXPLAIN_UNSIZED_TUPLE_COERCION);
640 fn coerce_from_safe_fn<F, G>(&self,
642 fn_ty_a: ty::PolyFnSig<'tcx>,
646 -> CoerceResult<'tcx>
647 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
648 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
650 if let ty::FnPtr(fn_ty_b) = b.sty {
651 if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe)
652 = (fn_ty_a.unsafety(), fn_ty_b.unsafety())
654 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
655 return self.unify_and(unsafe_a, b, to_unsafe);
658 self.unify_and(a, b, normal)
661 fn coerce_from_fn_pointer(&self,
663 fn_ty_a: ty::PolyFnSig<'tcx>,
665 -> CoerceResult<'tcx> {
666 //! Attempts to coerce from the type of a Rust function item
667 //! into a closure or a `proc`.
670 let b = self.shallow_resolve(b);
671 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
673 self.coerce_from_safe_fn(a, fn_ty_a, b,
674 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)), identity)
677 fn coerce_from_fn_item(&self,
680 -> CoerceResult<'tcx> {
681 //! Attempts to coerce from the type of a Rust function item
682 //! into a closure or a `proc`.
684 let b = self.shallow_resolve(b);
685 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
689 let a_sig = a.fn_sig(self.tcx);
690 let InferOk { value: a_sig, mut obligations } =
691 self.normalize_associated_types_in_as_infer_ok(self.cause.span, &a_sig);
693 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
694 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
701 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
705 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
710 simple(Adjust::Pointer(PointerCast::ReifyFnPointer))
713 obligations.extend(o2);
714 Ok(InferOk { value, obligations })
716 _ => self.unify_and(a, b, identity),
720 fn coerce_closure_to_fn(&self,
723 substs_a: ClosureSubsts<'tcx>,
725 -> CoerceResult<'tcx> {
726 //! Attempts to coerce from the type of a non-capturing closure
727 //! into a function pointer.
730 let b = self.shallow_resolve(b);
733 ty::FnPtr(fn_ty) if self.tcx.upvars(def_id_a).map_or(true, |v| v.is_empty()) => {
734 // We coerce the closure, which has fn type
735 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
737 // `fn(arg0,arg1,...) -> _`
739 // `unsafe fn(arg0,arg1,...) -> _`
740 let sig = self.closure_sig(def_id_a, substs_a);
741 let unsafety = fn_ty.unsafety();
742 let pointer_ty = self.tcx.coerce_closure_fn_ty(sig, unsafety);
743 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})",
745 self.unify_and(pointer_ty, b, simple(
746 Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))
749 _ => self.unify_and(a, b, identity),
753 fn coerce_unsafe_ptr(&self,
756 mutbl_b: hir::Mutability)
757 -> CoerceResult<'tcx> {
758 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
760 let (is_ref, mt_a) = match a.sty {
761 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
762 ty::RawPtr(mt) => (false, mt),
763 _ => return self.unify_and(a, b, identity)
766 // Check that the types which they point at are compatible.
767 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut {
771 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
772 // Although references and unsafe ptrs have the same
773 // representation, we still register an Adjust::DerefRef so that
774 // regionck knows that the region for `a` must be valid here.
776 self.unify_and(a_unsafe, b, |target| {
778 kind: Adjust::Deref(None),
781 kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
785 } else if mt_a.mutbl != mutbl_b {
787 a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer))
790 self.unify_and(a_unsafe, b, identity)
795 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
796 /// Attempt to coerce an expression to a type, and return the
797 /// adjusted type of the expression, if successful.
798 /// Adjustments are only recorded if the coercion succeeded.
799 /// The expressions *must not* have any pre-existing adjustments.
800 pub fn try_coerce(&self,
804 allow_two_phase: AllowTwoPhase)
805 -> RelateResult<'tcx, Ty<'tcx>> {
806 let source = self.resolve_type_vars_with_obligations(expr_ty);
807 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
809 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
810 let coerce = Coerce::new(self, cause, allow_two_phase);
811 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
813 let (adjustments, _) = self.register_infer_ok_obligations(ok);
814 self.apply_adjustments(expr, adjustments);
818 /// Same as `try_coerce()`, but without side-effects.
819 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
820 let source = self.resolve_type_vars_with_obligations(expr_ty);
821 debug!("coercion::can({:?} -> {:?})", source, target);
823 let cause = self.cause(syntax_pos::DUMMY_SP, ObligationCauseCode::ExprAssignable);
824 // We don't ever need two-phase here since we throw out the result of the coercion
825 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
826 self.probe(|_| coerce.coerce(source, target)).is_ok()
829 /// Given some expressions, their known unified type and another expression,
830 /// tries to unify the types, potentially inserting coercions on any of the
831 /// provided expressions and returns their LUB (aka "common supertype").
833 /// This is really an internal helper. From outside the coercion
834 /// module, you should instantiate a `CoerceMany` instance.
835 fn try_find_coercion_lub<E>(&self,
836 cause: &ObligationCause<'tcx>,
841 -> RelateResult<'tcx, Ty<'tcx>>
842 where E: AsCoercionSite
844 let prev_ty = self.resolve_type_vars_with_obligations(prev_ty);
845 let new_ty = self.resolve_type_vars_with_obligations(new_ty);
846 debug!("coercion::try_find_coercion_lub({:?}, {:?})", prev_ty, new_ty);
848 // Special-case that coercion alone cannot handle:
849 // Two function item types of differing IDs or InternalSubsts.
850 if let (&ty::FnDef(..), &ty::FnDef(..)) = (&prev_ty.sty, &new_ty.sty) {
851 // Don't reify if the function types have a LUB, i.e., they
852 // are the same function and their parameters have a LUB.
853 let lub_ty = self.commit_if_ok(|_| {
854 self.at(cause, self.param_env)
855 .lub(prev_ty, new_ty)
856 }).map(|ok| self.register_infer_ok_obligations(ok));
859 // We have a LUB of prev_ty and new_ty, just return it.
863 // The signature must match.
864 let a_sig = prev_ty.fn_sig(self.tcx);
865 let a_sig = self.normalize_associated_types_in(new.span, &a_sig);
866 let b_sig = new_ty.fn_sig(self.tcx);
867 let b_sig = self.normalize_associated_types_in(new.span, &b_sig);
868 let sig = self.at(cause, self.param_env)
869 .trace(prev_ty, new_ty)
871 .map(|ok| self.register_infer_ok_obligations(ok))?;
873 // Reify both sides and return the reified fn pointer type.
874 let fn_ptr = self.tcx.mk_fn_ptr(sig);
875 for expr in exprs.iter().map(|e| e.as_coercion_site()).chain(Some(new)) {
876 // The only adjustment that can produce an fn item is
877 // `NeverToAny`, so this should always be valid.
878 self.apply_adjustments(expr, vec![Adjustment {
879 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
886 // Configure a Coerce instance to compute the LUB.
887 // We don't allow two-phase borrows on any autorefs this creates since we
888 // probably aren't processing function arguments here and even if we were,
889 // they're going to get autorefed again anyway and we can apply 2-phase borrows
891 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
892 coerce.use_lub = true;
894 // First try to coerce the new expression to the type of the previous ones,
895 // but only if the new expression has no coercion already applied to it.
896 let mut first_error = None;
897 if !self.tables.borrow().adjustments().contains_key(new.hir_id) {
898 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
901 let (adjustments, target) = self.register_infer_ok_obligations(ok);
902 self.apply_adjustments(new, adjustments);
905 Err(e) => first_error = Some(e),
909 // Then try to coerce the previous expressions to the type of the new one.
910 // This requires ensuring there are no coercions applied to *any* of the
911 // previous expressions, other than noop reborrows (ignoring lifetimes).
913 let expr = expr.as_coercion_site();
914 let noop = match self.tables.borrow().expr_adjustments(expr) {
916 Adjustment { kind: Adjust::Deref(_), .. },
917 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }
919 match self.node_ty(expr.hir_id).sty {
920 ty::Ref(_, _, mt_orig) => {
921 let mutbl_adj: hir::Mutability = mutbl_adj.into();
922 // Reborrow that we can safely ignore, because
923 // the next adjustment can only be a Deref
924 // which will be merged into it.
930 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
935 return self.commit_if_ok(|_|
936 self.at(cause, self.param_env)
937 .lub(prev_ty, new_ty)
938 ).map(|ok| self.register_infer_ok_obligations(ok));
942 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
944 // Avoid giving strange errors on failed attempts.
945 if let Some(e) = first_error {
948 self.commit_if_ok(|_|
949 self.at(cause, self.param_env)
950 .lub(prev_ty, new_ty)
951 ).map(|ok| self.register_infer_ok_obligations(ok))
955 let (adjustments, target) = self.register_infer_ok_obligations(ok);
957 let expr = expr.as_coercion_site();
958 self.apply_adjustments(expr, adjustments.clone());
966 /// CoerceMany encapsulates the pattern you should use when you have
967 /// many expressions that are all getting coerced to a common
968 /// type. This arises, for example, when you have a match (the result
969 /// of each arm is coerced to a common type). It also arises in less
970 /// obvious places, such as when you have many `break foo` expressions
971 /// that target the same loop, or the various `return` expressions in
974 /// The basic protocol is as follows:
976 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
977 /// This will also serve as the "starting LUB". The expectation is
978 /// that this type is something which all of the expressions *must*
979 /// be coercible to. Use a fresh type variable if needed.
980 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
981 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
982 /// unit. This happens for example if you have a `break` with no expression,
983 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
984 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
985 /// from you so that you don't have to worry your pretty head about it.
986 /// But if an error is reported, the final type will be `err`.
987 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
988 /// previously coerced expressions.
989 /// - When all done, invoke `complete()`. This will return the LUB of
990 /// all your expressions.
991 /// - WARNING: I don't believe this final type is guaranteed to be
992 /// related to your initial `expected_ty` in any particular way,
993 /// although it will typically be a subtype, so you should check it.
994 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
995 /// previously coerced expressions.
1000 /// let mut coerce = CoerceMany::new(expected_ty);
1001 /// for expr in exprs {
1002 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1003 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1005 /// let final_ty = coerce.complete(fcx);
1007 pub struct CoerceMany<'gcx, 'tcx, 'exprs, E>
1008 where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
1010 expected_ty: Ty<'tcx>,
1011 final_ty: Option<Ty<'tcx>>,
1012 expressions: Expressions<'gcx, 'exprs, E>,
1016 /// The type of a `CoerceMany` that is storing up the expressions into
1017 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1018 pub type DynamicCoerceMany<'gcx, 'tcx> = CoerceMany<'gcx, 'tcx, 'gcx, P<hir::Expr>>;
1020 enum Expressions<'gcx, 'exprs, E>
1021 where E: 'exprs + AsCoercionSite,
1023 Dynamic(Vec<&'gcx hir::Expr>),
1024 UpFront(&'exprs [E]),
1027 impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E>
1028 where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
1030 /// The usual case; collect the set of expressions dynamically.
1031 /// If the full set of coercion sites is known before hand,
1032 /// consider `with_coercion_sites()` instead to avoid allocation.
1033 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1034 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1037 /// As an optimization, you can create a `CoerceMany` with a
1038 /// pre-existing slice of expressions. In this case, you are
1039 /// expected to pass each element in the slice to `coerce(...)` in
1040 /// order. This is used with arrays in particular to avoid
1041 /// needlessly cloning the slice.
1042 pub fn with_coercion_sites(expected_ty: Ty<'tcx>,
1043 coercion_sites: &'exprs [E])
1045 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1048 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'gcx, 'exprs, E>) -> Self {
1057 /// Returns the "expected type" with which this coercion was
1058 /// constructed. This represents the "downward propagated" type
1059 /// that was given to us at the start of typing whatever construct
1060 /// we are typing (e.g., the match expression).
1062 /// Typically, this is used as the expected type when
1063 /// type-checking each of the alternative expressions whose types
1064 /// we are trying to merge.
1065 pub fn expected_ty(&self) -> Ty<'tcx> {
1069 /// Returns the current "merged type", representing our best-guess
1070 /// at the LUB of the expressions we've seen so far (if any). This
1071 /// isn't *final* until you call `self.final()`, which will return
1072 /// the merged type.
1073 pub fn merged_ty(&self) -> Ty<'tcx> {
1074 self.final_ty.unwrap_or(self.expected_ty)
1077 /// Indicates that the value generated by `expression`, which is
1078 /// of type `expression_ty`, is one of the possibilities that we
1079 /// could coerce from. This will record `expression`, and later
1080 /// calls to `coerce` may come back and add adjustments and things
1082 pub fn coerce<'a>(&mut self,
1083 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1084 cause: &ObligationCause<'tcx>,
1085 expression: &'gcx hir::Expr,
1086 expression_ty: Ty<'tcx>)
1088 self.coerce_inner(fcx,
1095 /// Indicates that one of the inputs is a "forced unit". This
1096 /// occurs in a case like `if foo { ... };`, where the missing else
1097 /// generates a "forced unit". Another example is a `loop { break;
1098 /// }`, where the `break` has no argument expression. We treat
1099 /// these cases slightly differently for error-reporting
1100 /// purposes. Note that these tend to correspond to cases where
1101 /// the `()` expression is implicit in the source, and hence we do
1102 /// not take an expression argument.
1104 /// The `augment_error` gives you a chance to extend the error
1105 /// message, in case any results (e.g., we use this to suggest
1106 /// removing a `;`).
1107 pub fn coerce_forced_unit<'a>(&mut self,
1108 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1109 cause: &ObligationCause<'tcx>,
1110 augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1111 label_unit_as_expected: bool)
1113 self.coerce_inner(fcx,
1117 Some(augment_error),
1118 label_unit_as_expected)
1121 /// The inner coercion "engine". If `expression` is `None`, this
1122 /// is a forced-unit case, and hence `expression_ty` must be
1124 fn coerce_inner<'a>(&mut self,
1125 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1126 cause: &ObligationCause<'tcx>,
1127 expression: Option<&'gcx hir::Expr>,
1128 mut expression_ty: Ty<'tcx>,
1129 augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1130 label_expression_as_expected: bool)
1132 // Incorporate whatever type inference information we have
1133 // until now; in principle we might also want to process
1134 // pending obligations, but doing so should only improve
1135 // compatibility (hopefully that is true) by helping us
1136 // uncover never types better.
1137 if expression_ty.is_ty_var() {
1138 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1141 // If we see any error types, just propagate that error
1143 if expression_ty.references_error() || self.merged_ty().references_error() {
1144 self.final_ty = Some(fcx.tcx.types.err);
1148 // Handle the actual type unification etc.
1149 let result = if let Some(expression) = expression {
1150 if self.pushed == 0 {
1151 // Special-case the first expression we are coercing.
1152 // To be honest, I'm not entirely sure why we do this.
1153 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1154 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1156 match self.expressions {
1157 Expressions::Dynamic(ref exprs) =>
1158 fcx.try_find_coercion_lub(cause,
1163 Expressions::UpFront(ref coercion_sites) =>
1164 fcx.try_find_coercion_lub(cause,
1165 &coercion_sites[0..self.pushed],
1172 // this is a hack for cases where we default to `()` because
1173 // the expression etc has been omitted from the source. An
1174 // example is an `if let` without an else:
1176 // if let Some(x) = ... { }
1178 // we wind up with a second match arm that is like `_ =>
1179 // ()`. That is the case we are considering here. We take
1180 // a different path to get the right "expected, found"
1181 // message and so forth (and because we know that
1182 // `expression_ty` will be unit).
1184 // Another example is `break` with no argument expression.
1185 assert!(expression_ty.is_unit(), "if let hack without unit type");
1186 fcx.at(cause, fcx.param_env)
1187 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1189 fcx.register_infer_ok_obligations(infer_ok);
1196 self.final_ty = Some(v);
1197 if let Some(e) = expression {
1198 match self.expressions {
1199 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1200 Expressions::UpFront(coercion_sites) => {
1201 // if the user gave us an array to validate, check that we got
1202 // the next expression in the list, as expected
1203 assert_eq!(coercion_sites[self.pushed].as_coercion_site().hir_id,
1211 let (expected, found) = if label_expression_as_expected {
1212 // In the case where this is a "forced unit", like
1213 // `break`, we want to call the `()` "expected"
1214 // since it is implied by the syntax.
1215 // (Note: not all force-units work this way.)"
1216 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1218 // Otherwise, the "expected" type for error
1219 // reporting is the current unification type,
1220 // which is basically the LUB of the expressions
1221 // we've seen so far (combined with the expected
1223 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1228 ObligationCauseCode::ReturnNoExpression => {
1229 db = struct_span_err!(
1230 fcx.tcx.sess, cause.span, E0069,
1231 "`return;` in a function whose return type is not `()`");
1232 db.span_label(cause.span, "return type is not `()`");
1234 ObligationCauseCode::BlockTailExpression(blk_id) => {
1235 let parent_id = fcx.tcx.hir().get_parent_node_by_hir_id(blk_id);
1236 db = self.report_return_mismatched_types(
1243 expression.map(|expr| (expr, blk_id)),
1246 ObligationCauseCode::ReturnType(id) => {
1247 db = self.report_return_mismatched_types(
1248 cause, expected, found, err, fcx, id, None);
1251 db = fcx.report_mismatched_types(cause, expected, found, err);
1255 if let Some(augment_error) = augment_error {
1256 augment_error(&mut db);
1259 // Error possibly reported in `check_assign` so avoid emitting error again.
1260 db.emit_unless(expression.filter(|e| fcx.is_assign_to_bool(e, expected)).is_some());
1262 self.final_ty = Some(fcx.tcx.types.err);
1267 fn report_return_mismatched_types<'a>(
1269 cause: &ObligationCause<'tcx>,
1272 err: TypeError<'tcx>,
1273 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1275 expression: Option<(&'gcx hir::Expr, hir::HirId)>,
1276 ) -> DiagnosticBuilder<'a> {
1277 let mut db = fcx.report_mismatched_types(cause, expected, found, err);
1279 let mut pointing_at_return_type = false;
1280 let mut return_sp = None;
1282 // Verify that this is a tail expression of a function, otherwise the
1283 // label pointing out the cause for the type coercion will be wrong
1284 // as prior return coercions would not be relevant (#57664).
1285 let parent_id = fcx.tcx.hir().get_parent_node_by_hir_id(id);
1286 let fn_decl = if let Some((expr, blk_id)) = expression {
1287 pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1295 let parent = fcx.tcx.hir().get_by_hir_id(parent_id);
1296 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1298 fcx.get_fn_decl(parent_id)
1301 if let (Some((fn_decl, can_suggest)), _) = (fn_decl, pointing_at_return_type) {
1302 if expression.is_none() {
1303 pointing_at_return_type |= fcx.suggest_missing_return_type(
1304 &mut db, &fn_decl, expected, found, can_suggest);
1306 if !pointing_at_return_type {
1307 return_sp = Some(fn_decl.output.span()); // `impl Trait` return type
1310 if let (Some(sp), Some(return_sp)) = (fcx.ret_coercion_span.borrow().as_ref(), return_sp) {
1311 db.span_label(return_sp, "expected because this return type...");
1312 db.span_label( *sp, format!(
1313 "...is found to be `{}` here",
1314 fcx.resolve_type_vars_with_obligations(expected),
1320 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1321 if let Some(final_ty) = self.final_ty {
1324 // If we only had inputs that were of type `!` (or no
1325 // inputs at all), then the final type is `!`.
1326 assert_eq!(self.pushed, 0);
1332 /// Something that can be converted into an expression to which we can
1333 /// apply a coercion.
1334 pub trait AsCoercionSite {
1335 fn as_coercion_site(&self) -> &hir::Expr;
1338 impl AsCoercionSite for hir::Expr {
1339 fn as_coercion_site(&self) -> &hir::Expr {
1344 impl AsCoercionSite for P<hir::Expr> {
1345 fn as_coercion_site(&self) -> &hir::Expr {
1350 impl<'a, T> AsCoercionSite for &'a T
1351 where T: AsCoercionSite
1353 fn as_coercion_site(&self) -> &hir::Expr {
1354 (**self).as_coercion_site()
1358 impl AsCoercionSite for ! {
1359 fn as_coercion_site(&self) -> &hir::Expr {
1364 impl AsCoercionSite for hir::Arm {
1365 fn as_coercion_site(&self) -> &hir::Expr {