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;
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(
179 TypeVariableOrigin::AdjustmentType(self.cause.span));
180 self.unify_and(&b, &diverging_ty, simple(Adjust::NeverToAny))
182 success(simple(Adjust::NeverToAny)(b), b, vec![])
186 // Consider coercing the subtype to a DST
188 // NOTE: this is wrapped in a `commit_if_ok` because it creates
189 // a "spurious" type variable, and we don't want to have that
190 // type variable in memory if the coercion fails.
191 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
193 debug!("coerce: unsize successful");
196 debug!("coerce: unsize failed");
198 // Examine the supertype and consider auto-borrowing.
200 // Note: does not attempt to resolve type variables we encounter.
201 // See above for details.
203 ty::RawPtr(mt_b) => {
204 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
207 ty::Ref(r_b, ty, mutbl) => {
208 let mt_b = ty::TypeAndMut { ty, mutbl };
209 return self.coerce_borrowed_pointer(a, b, r_b, mt_b);
217 // Function items are coercible to any closure
218 // type; function pointers are not (that would
219 // require double indirection).
220 // Additionally, we permit coercion of function
221 // items to drop the unsafe qualifier.
222 self.coerce_from_fn_item(a, b)
225 // We permit coercion of fn pointers to drop the
227 self.coerce_from_fn_pointer(a, a_f, b)
229 ty::Closure(def_id_a, substs_a) => {
230 // Non-capturing closures are coercible to
231 // function pointers or unsafe function pointers.
232 // It cannot convert closures that require unsafe.
233 self.coerce_closure_to_fn(a, def_id_a, substs_a, b)
236 // Otherwise, just use unification rules.
237 self.unify_and(a, b, identity)
242 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
243 /// To match `A` with `B`, autoderef will be performed,
244 /// calling `deref`/`deref_mut` where necessary.
245 fn coerce_borrowed_pointer(&self,
248 r_b: ty::Region<'tcx>,
249 mt_b: TypeAndMut<'tcx>)
250 -> CoerceResult<'tcx>
252 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
254 // If we have a parameter of type `&M T_a` and the value
255 // provided is `expr`, we will be adding an implicit borrow,
256 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
257 // to type check, we will construct the type that `&M*expr` would
260 let (r_a, mt_a) = match a.sty {
261 ty::Ref(r_a, ty, mutbl) => {
262 let mt_a = ty::TypeAndMut { ty, mutbl };
263 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
266 _ => return self.unify_and(a, b, identity),
269 let span = self.cause.span;
271 let mut first_error = None;
272 let mut r_borrow_var = None;
273 let mut autoderef = self.autoderef(span, a);
274 let mut found = None;
276 for (referent_ty, autoderefs) in autoderef.by_ref() {
278 // Don't let this pass, otherwise it would cause
279 // &T to autoref to &&T.
283 // At this point, we have deref'd `a` to `referent_ty`. So
284 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
285 // In the autoderef loop for `&'a mut Vec<T>`, we would get
288 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
289 // - `Vec<T>` -- 1 deref
290 // - `[T]` -- 2 deref
292 // At each point after the first callback, we want to
293 // check to see whether this would match out target type
294 // (`&'b mut [T]`) if we autoref'd it. We can't just
295 // compare the referent types, though, because we still
296 // have to consider the mutability. E.g., in the case
297 // we've been considering, we have an `&mut` reference, so
298 // the `T` in `[T]` needs to be unified with equality.
300 // Therefore, we construct reference types reflecting what
301 // the types will be after we do the final auto-ref and
302 // compare those. Note that this means we use the target
303 // mutability [1], since it may be that we are coercing
304 // from `&mut T` to `&U`.
306 // One fine point concerns the region that we use. We
307 // choose the region such that the region of the final
308 // type that results from `unify` will be the region we
309 // want for the autoref:
311 // - if in sub mode, that means we want to use `'b` (the
312 // region from the target reference) for both
313 // pointers [2]. This is because sub mode (somewhat
314 // arbitrarily) returns the subtype region. In the case
315 // where we are coercing to a target type, we know we
316 // want to use that target type region (`'b`) because --
317 // for the program to type-check -- it must be the
318 // smaller of the two.
319 // - One fine point. It may be surprising that we can
320 // use `'b` without relating `'a` and `'b`. The reason
321 // that this is ok is that what we produce is
322 // effectively a `&'b *x` expression (if you could
323 // annotate the region of a borrow), and regionck has
324 // code that adds edges from the region of a borrow
325 // (`'b`, here) into the regions in the borrowed
326 // expression (`*x`, here). (Search for "link".)
327 // - if in lub mode, things can get fairly complicated. The
328 // easiest thing is just to make a fresh
329 // region variable [4], which effectively means we defer
330 // the decision to region inference (and regionck, which will add
331 // some more edges to this variable). However, this can wind up
332 // creating a crippling number of variables in some cases --
333 // e.g., #32278 -- so we optimize one particular case [3].
334 // Let me try to explain with some examples:
335 // - The "running example" above represents the simple case,
336 // where we have one `&` reference at the outer level and
337 // ownership all the rest of the way down. In this case,
338 // we want `LUB('a, 'b)` as the resulting region.
339 // - However, if there are nested borrows, that region is
340 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
341 // `&'b T`. In this case, `'a` is actually irrelevant.
342 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
343 // we get spurious errors (`run-pass/regions-lub-ref-ref-rc.rs`).
344 // (The errors actually show up in borrowck, typically, because
345 // this extra edge causes the region `'a` to be inferred to something
346 // too big, which then results in borrowck errors.)
347 // - We could track the innermost shared reference, but there is already
348 // code in regionck that has the job of creating links between
349 // the region of a borrow and the regions in the thing being
350 // borrowed (here, `'a` and `'x`), and it knows how to handle
351 // all the various cases. So instead we just make a region variable
352 // and let regionck figure it out.
353 let r = if !self.use_lub {
355 } else if autoderefs == 1 {
358 if r_borrow_var.is_none() {
359 // create var lazilly, at most once
360 let coercion = Coercion(span);
361 let r = self.next_region_var(coercion);
362 r_borrow_var = Some(r); // [4] above
364 r_borrow_var.unwrap()
366 let derefd_ty_a = self.tcx.mk_ref(r,
369 mutbl: mt_b.mutbl, // [1] above
371 match self.unify(derefd_ty_a, b) {
377 if first_error.is_none() {
378 first_error = Some(err);
384 // Extract type or return an error. We return the first error
385 // we got, which should be from relating the "base" type
386 // (e.g., in example above, the failure from relating `Vec<T>`
387 // to the target type), since that should be the least
389 let InferOk { value: ty, mut obligations } = match found {
392 let err = first_error.expect("coerce_borrowed_pointer had no error");
393 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
398 if ty == a && mt_a.mutbl == hir::MutImmutable && autoderef.step_count() == 1 {
399 // As a special case, if we would produce `&'a *x`, that's
400 // a total no-op. We end up with the type `&'a T` just as
401 // we started with. In that case, just skip it
402 // altogether. This is just an optimization.
404 // Note that for `&mut`, we DO want to reborrow --
405 // otherwise, this would be a move, which might be an
406 // error. For example `foo(self.x)` where `self` and
407 // `self.x` both have `&mut `type would be a move of
408 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
409 // which is a borrow.
410 assert_eq!(mt_b.mutbl, hir::MutImmutable); // can only coerce &T -> &U
411 return success(vec![], ty, obligations);
414 let needs = Needs::maybe_mut_place(mt_b.mutbl);
415 let InferOk { value: mut adjustments, obligations: o }
416 = autoderef.adjust_steps_as_infer_ok(self, needs);
417 obligations.extend(o);
418 obligations.extend(autoderef.into_obligations());
420 // Now apply the autoref. We have to extract the region out of
421 // the final ref type we got.
422 let r_borrow = match ty.sty {
423 ty::Ref(r_borrow, _, _) => r_borrow,
424 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
426 let mutbl = match mt_b.mutbl {
427 hir::MutImmutable => AutoBorrowMutability::Immutable,
428 hir::MutMutable => AutoBorrowMutability::Mutable {
429 allow_two_phase_borrow: self.allow_two_phase,
432 adjustments.push(Adjustment {
433 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
437 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}",
441 success(adjustments, ty, obligations)
445 // &[T; n] or &mut [T; n] -> &[T]
446 // or &mut [T; n] -> &mut [T]
447 // or &Concrete -> &Trait, etc.
448 fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
449 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
451 let traits = (self.tcx.lang_items().unsize_trait(),
452 self.tcx.lang_items().coerce_unsized_trait());
453 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
456 debug!("Missing Unsize or CoerceUnsized traits");
457 return Err(TypeError::Mismatch);
460 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
461 // a DST unless we have to. This currently comes out in the wash since
462 // we can't unify [T] with U. But to properly support DST, we need to allow
463 // that, at which point we will need extra checks on the target here.
465 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
466 let reborrow = match (&source.sty, &target.sty) {
467 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
468 coerce_mutbls(mutbl_a, mutbl_b)?;
470 let coercion = Coercion(self.cause.span);
471 let r_borrow = self.next_region_var(coercion);
472 let mutbl = match mutbl_b {
473 hir::MutImmutable => AutoBorrowMutability::Immutable,
474 hir::MutMutable => AutoBorrowMutability::Mutable {
475 // We don't allow two-phase borrows here, at least for initial
476 // implementation. If it happens that this coercion is a function argument,
477 // the reborrow in coerce_borrowed_ptr will pick it up.
478 allow_two_phase_borrow: AllowTwoPhase::No,
482 kind: Adjust::Deref(None),
485 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
486 target: self.tcx.mk_ref(r_borrow, ty::TypeAndMut {
492 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
493 coerce_mutbls(mt_a, mt_b)?;
496 kind: Adjust::Deref(None),
499 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
500 target: self.tcx.mk_ptr(ty::TypeAndMut {
508 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
510 // Setup either a subtyping or a LUB relationship between
511 // the `CoerceUnsized` target type and the expected type.
512 // We only have the latter, so we use an inference variable
513 // for the former and let type inference do the rest.
514 let origin = TypeVariableOrigin::MiscVariable(self.cause.span);
515 let coerce_target = self.next_ty_var(origin);
516 let mut coercion = self.unify_and(coerce_target, target, |target| {
517 let unsize = Adjustment {
518 kind: Adjust::Pointer(PointerCast::Unsize),
522 None => vec![unsize],
523 Some((ref deref, ref autoref)) => {
524 vec![deref.clone(), autoref.clone(), unsize]
529 let mut selcx = traits::SelectionContext::new(self);
531 // Create an obligation for `Source: CoerceUnsized<Target>`.
532 let cause = ObligationCause::misc(self.cause.span, self.body_id);
534 // Use a FIFO queue for this custom fulfillment procedure.
536 // A Vec (or SmallVec) is not a natural choice for a queue. However,
537 // this code path is hot, and this queue usually has a max length of 1
538 // and almost never more than 3. By using a SmallVec we avoid an
539 // allocation, at the (very small) cost of (occasionally) having to
540 // shift subsequent elements down when removing the front element.
541 let mut queue: SmallVec<[_; 4]> =
542 smallvec![self.tcx.predicate_for_trait_def(self.fcx.param_env,
547 &[coerce_target.into()])];
549 let mut has_unsized_tuple_coercion = false;
551 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
552 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
553 // inference might unify those two inner type variables later.
554 let traits = [coerce_unsized_did, unsize_did];
555 while !queue.is_empty() {
556 let obligation = queue.remove(0);
557 debug!("coerce_unsized resolve step: {:?}", obligation);
558 let trait_ref = match obligation.predicate {
559 ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => {
560 if unsize_did == tr.def_id() {
561 let sty = &tr.skip_binder().input_types().nth(1).unwrap().sty;
562 if let ty::Tuple(..) = sty {
563 debug!("coerce_unsized: found unsized tuple coercion");
564 has_unsized_tuple_coercion = true;
570 coercion.obligations.push(obligation);
574 match selcx.select(&obligation.with(trait_ref)) {
575 // Uncertain or unimplemented.
577 if trait_ref.def_id() == unsize_did {
578 let trait_ref = self.resolve_type_vars_if_possible(&trait_ref);
579 let self_ty = trait_ref.skip_binder().self_ty();
580 let unsize_ty = trait_ref.skip_binder().input_types().nth(1).unwrap();
581 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_ref);
582 match (&self_ty.sty, &unsize_ty.sty) {
583 (ty::Infer(ty::TyVar(v)),
584 ty::Dynamic(..)) if self.type_var_is_sized(*v) => {
585 debug!("coerce_unsized: have sized infer {:?}", v);
586 coercion.obligations.push(obligation);
587 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
591 // Some other case for `$0: Unsize<Something>`. Note that we
592 // hit this case even if `Something` is a sized type, so just
593 // don't do the coercion.
594 debug!("coerce_unsized: ambiguous unsize");
595 return Err(TypeError::Mismatch);
599 debug!("coerce_unsized: early return - ambiguous");
600 return Err(TypeError::Mismatch);
603 Err(traits::Unimplemented) => {
604 debug!("coerce_unsized: early return - can't prove obligation");
605 return Err(TypeError::Mismatch);
608 // Object safety violations or miscellaneous.
610 self.report_selection_error(&obligation, &err, false);
611 // Treat this like an obligation and follow through
612 // with the unsizing - the lack of a coercion should
613 // be silent, as it causes a type mismatch later.
616 Ok(Some(vtable)) => {
617 queue.extend(vtable.nested_obligations())
622 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
623 feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
624 sym::unsized_tuple_coercion,
626 feature_gate::GateIssue::Language,
627 feature_gate::EXPLAIN_UNSIZED_TUPLE_COERCION);
633 fn coerce_from_safe_fn<F, G>(&self,
635 fn_ty_a: ty::PolyFnSig<'tcx>,
639 -> CoerceResult<'tcx>
640 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
641 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
643 if let ty::FnPtr(fn_ty_b) = b.sty {
644 if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe)
645 = (fn_ty_a.unsafety(), fn_ty_b.unsafety())
647 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
648 return self.unify_and(unsafe_a, b, to_unsafe);
651 self.unify_and(a, b, normal)
654 fn coerce_from_fn_pointer(&self,
656 fn_ty_a: ty::PolyFnSig<'tcx>,
658 -> CoerceResult<'tcx> {
659 //! Attempts to coerce from the type of a Rust function item
660 //! into a closure or a `proc`.
663 let b = self.shallow_resolve(b);
664 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
666 self.coerce_from_safe_fn(a, fn_ty_a, b,
667 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)), identity)
670 fn coerce_from_fn_item(&self,
673 -> CoerceResult<'tcx> {
674 //! Attempts to coerce from the type of a Rust function item
675 //! into a closure or a `proc`.
677 let b = self.shallow_resolve(b);
678 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
682 let a_sig = a.fn_sig(self.tcx);
683 let InferOk { value: a_sig, mut obligations } =
684 self.normalize_associated_types_in_as_infer_ok(self.cause.span, &a_sig);
686 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
687 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
694 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
698 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
703 simple(Adjust::Pointer(PointerCast::ReifyFnPointer))
706 obligations.extend(o2);
707 Ok(InferOk { value, obligations })
709 _ => self.unify_and(a, b, identity),
713 fn coerce_closure_to_fn(&self,
716 substs_a: ClosureSubsts<'tcx>,
718 -> CoerceResult<'tcx> {
719 //! Attempts to coerce from the type of a non-capturing closure
720 //! into a function pointer.
723 let b = self.shallow_resolve(b);
726 ty::FnPtr(fn_ty) if self.tcx.upvars(def_id_a).map_or(true, |v| v.is_empty()) => {
727 // We coerce the closure, which has fn type
728 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
730 // `fn(arg0,arg1,...) -> _`
732 // `unsafe fn(arg0,arg1,...) -> _`
733 let sig = self.closure_sig(def_id_a, substs_a);
734 let unsafety = fn_ty.unsafety();
735 let pointer_ty = self.tcx.coerce_closure_fn_ty(sig, unsafety);
736 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})",
738 self.unify_and(pointer_ty, b, simple(
739 Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))
742 _ => self.unify_and(a, b, identity),
746 fn coerce_unsafe_ptr(&self,
749 mutbl_b: hir::Mutability)
750 -> CoerceResult<'tcx> {
751 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
753 let (is_ref, mt_a) = match a.sty {
754 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
755 ty::RawPtr(mt) => (false, mt),
756 _ => return self.unify_and(a, b, identity)
759 // Check that the types which they point at are compatible.
760 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut {
764 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
765 // Although references and unsafe ptrs have the same
766 // representation, we still register an Adjust::DerefRef so that
767 // regionck knows that the region for `a` must be valid here.
769 self.unify_and(a_unsafe, b, |target| {
771 kind: Adjust::Deref(None),
774 kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
778 } else if mt_a.mutbl != mutbl_b {
780 a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer))
783 self.unify_and(a_unsafe, b, identity)
788 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
789 /// Attempt to coerce an expression to a type, and return the
790 /// adjusted type of the expression, if successful.
791 /// Adjustments are only recorded if the coercion succeeded.
792 /// The expressions *must not* have any pre-existing adjustments.
793 pub fn try_coerce(&self,
797 allow_two_phase: AllowTwoPhase)
798 -> RelateResult<'tcx, Ty<'tcx>> {
799 let source = self.resolve_type_vars_with_obligations(expr_ty);
800 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
802 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
803 let coerce = Coerce::new(self, cause, allow_two_phase);
804 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
806 let (adjustments, _) = self.register_infer_ok_obligations(ok);
807 self.apply_adjustments(expr, adjustments);
811 /// Same as `try_coerce()`, but without side-effects.
812 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
813 let source = self.resolve_type_vars_with_obligations(expr_ty);
814 debug!("coercion::can({:?} -> {:?})", source, target);
816 let cause = self.cause(syntax_pos::DUMMY_SP, ObligationCauseCode::ExprAssignable);
817 // We don't ever need two-phase here since we throw out the result of the coercion
818 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
819 self.probe(|_| coerce.coerce(source, target)).is_ok()
822 /// Given some expressions, their known unified type and another expression,
823 /// tries to unify the types, potentially inserting coercions on any of the
824 /// provided expressions and returns their LUB (aka "common supertype").
826 /// This is really an internal helper. From outside the coercion
827 /// module, you should instantiate a `CoerceMany` instance.
828 fn try_find_coercion_lub<E>(&self,
829 cause: &ObligationCause<'tcx>,
834 -> RelateResult<'tcx, Ty<'tcx>>
835 where E: AsCoercionSite
837 let prev_ty = self.resolve_type_vars_with_obligations(prev_ty);
838 let new_ty = self.resolve_type_vars_with_obligations(new_ty);
839 debug!("coercion::try_find_coercion_lub({:?}, {:?})", prev_ty, new_ty);
841 // Special-case that coercion alone cannot handle:
842 // Two function item types of differing IDs or InternalSubsts.
843 if let (&ty::FnDef(..), &ty::FnDef(..)) = (&prev_ty.sty, &new_ty.sty) {
844 // Don't reify if the function types have a LUB, i.e., they
845 // are the same function and their parameters have a LUB.
846 let lub_ty = self.commit_if_ok(|_| {
847 self.at(cause, self.param_env)
848 .lub(prev_ty, new_ty)
849 }).map(|ok| self.register_infer_ok_obligations(ok));
852 // We have a LUB of prev_ty and new_ty, just return it.
856 // The signature must match.
857 let a_sig = prev_ty.fn_sig(self.tcx);
858 let a_sig = self.normalize_associated_types_in(new.span, &a_sig);
859 let b_sig = new_ty.fn_sig(self.tcx);
860 let b_sig = self.normalize_associated_types_in(new.span, &b_sig);
861 let sig = self.at(cause, self.param_env)
862 .trace(prev_ty, new_ty)
864 .map(|ok| self.register_infer_ok_obligations(ok))?;
866 // Reify both sides and return the reified fn pointer type.
867 let fn_ptr = self.tcx.mk_fn_ptr(sig);
868 for expr in exprs.iter().map(|e| e.as_coercion_site()).chain(Some(new)) {
869 // The only adjustment that can produce an fn item is
870 // `NeverToAny`, so this should always be valid.
871 self.apply_adjustments(expr, vec![Adjustment {
872 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
879 // Configure a Coerce instance to compute the LUB.
880 // We don't allow two-phase borrows on any autorefs this creates since we
881 // probably aren't processing function arguments here and even if we were,
882 // they're going to get autorefed again anyway and we can apply 2-phase borrows
884 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
885 coerce.use_lub = true;
887 // First try to coerce the new expression to the type of the previous ones,
888 // but only if the new expression has no coercion already applied to it.
889 let mut first_error = None;
890 if !self.tables.borrow().adjustments().contains_key(new.hir_id) {
891 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
894 let (adjustments, target) = self.register_infer_ok_obligations(ok);
895 self.apply_adjustments(new, adjustments);
898 Err(e) => first_error = Some(e),
902 // Then try to coerce the previous expressions to the type of the new one.
903 // This requires ensuring there are no coercions applied to *any* of the
904 // previous expressions, other than noop reborrows (ignoring lifetimes).
906 let expr = expr.as_coercion_site();
907 let noop = match self.tables.borrow().expr_adjustments(expr) {
909 Adjustment { kind: Adjust::Deref(_), .. },
910 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }
912 match self.node_ty(expr.hir_id).sty {
913 ty::Ref(_, _, mt_orig) => {
914 let mutbl_adj: hir::Mutability = mutbl_adj.into();
915 // Reborrow that we can safely ignore, because
916 // the next adjustment can only be a Deref
917 // which will be merged into it.
923 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
928 return self.commit_if_ok(|_|
929 self.at(cause, self.param_env)
930 .lub(prev_ty, new_ty)
931 ).map(|ok| self.register_infer_ok_obligations(ok));
935 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
937 // Avoid giving strange errors on failed attempts.
938 if let Some(e) = first_error {
941 self.commit_if_ok(|_|
942 self.at(cause, self.param_env)
943 .lub(prev_ty, new_ty)
944 ).map(|ok| self.register_infer_ok_obligations(ok))
948 let (adjustments, target) = self.register_infer_ok_obligations(ok);
950 let expr = expr.as_coercion_site();
951 self.apply_adjustments(expr, adjustments.clone());
959 /// CoerceMany encapsulates the pattern you should use when you have
960 /// many expressions that are all getting coerced to a common
961 /// type. This arises, for example, when you have a match (the result
962 /// of each arm is coerced to a common type). It also arises in less
963 /// obvious places, such as when you have many `break foo` expressions
964 /// that target the same loop, or the various `return` expressions in
967 /// The basic protocol is as follows:
969 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
970 /// This will also serve as the "starting LUB". The expectation is
971 /// that this type is something which all of the expressions *must*
972 /// be coercible to. Use a fresh type variable if needed.
973 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
974 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
975 /// unit. This happens for example if you have a `break` with no expression,
976 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
977 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
978 /// from you so that you don't have to worry your pretty head about it.
979 /// But if an error is reported, the final type will be `err`.
980 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
981 /// previously coerced expressions.
982 /// - When all done, invoke `complete()`. This will return the LUB of
983 /// all your expressions.
984 /// - WARNING: I don't believe this final type is guaranteed to be
985 /// related to your initial `expected_ty` in any particular way,
986 /// although it will typically be a subtype, so you should check it.
987 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
988 /// previously coerced expressions.
993 /// let mut coerce = CoerceMany::new(expected_ty);
994 /// for expr in exprs {
995 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
996 /// coerce.coerce(fcx, &cause, expr, expr_ty);
998 /// let final_ty = coerce.complete(fcx);
1000 pub struct CoerceMany<'gcx, 'tcx, 'exprs, E>
1001 where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
1003 expected_ty: Ty<'tcx>,
1004 final_ty: Option<Ty<'tcx>>,
1005 expressions: Expressions<'gcx, 'exprs, E>,
1009 /// The type of a `CoerceMany` that is storing up the expressions into
1010 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1011 pub type DynamicCoerceMany<'gcx, 'tcx> = CoerceMany<'gcx, 'tcx, 'gcx, P<hir::Expr>>;
1013 enum Expressions<'gcx, 'exprs, E>
1014 where E: 'exprs + AsCoercionSite,
1016 Dynamic(Vec<&'gcx hir::Expr>),
1017 UpFront(&'exprs [E]),
1020 impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E>
1021 where 'gcx: 'tcx, E: 'exprs + AsCoercionSite,
1023 /// The usual case; collect the set of expressions dynamically.
1024 /// If the full set of coercion sites is known before hand,
1025 /// consider `with_coercion_sites()` instead to avoid allocation.
1026 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1027 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1030 /// As an optimization, you can create a `CoerceMany` with a
1031 /// pre-existing slice of expressions. In this case, you are
1032 /// expected to pass each element in the slice to `coerce(...)` in
1033 /// order. This is used with arrays in particular to avoid
1034 /// needlessly cloning the slice.
1035 pub fn with_coercion_sites(expected_ty: Ty<'tcx>,
1036 coercion_sites: &'exprs [E])
1038 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1041 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'gcx, 'exprs, E>) -> Self {
1050 /// Returns the "expected type" with which this coercion was
1051 /// constructed. This represents the "downward propagated" type
1052 /// that was given to us at the start of typing whatever construct
1053 /// we are typing (e.g., the match expression).
1055 /// Typically, this is used as the expected type when
1056 /// type-checking each of the alternative expressions whose types
1057 /// we are trying to merge.
1058 pub fn expected_ty(&self) -> Ty<'tcx> {
1062 /// Returns the current "merged type", representing our best-guess
1063 /// at the LUB of the expressions we've seen so far (if any). This
1064 /// isn't *final* until you call `self.final()`, which will return
1065 /// the merged type.
1066 pub fn merged_ty(&self) -> Ty<'tcx> {
1067 self.final_ty.unwrap_or(self.expected_ty)
1070 /// Indicates that the value generated by `expression`, which is
1071 /// of type `expression_ty`, is one of the possibilities that we
1072 /// could coerce from. This will record `expression`, and later
1073 /// calls to `coerce` may come back and add adjustments and things
1075 pub fn coerce<'a>(&mut self,
1076 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1077 cause: &ObligationCause<'tcx>,
1078 expression: &'gcx hir::Expr,
1079 expression_ty: Ty<'tcx>)
1081 self.coerce_inner(fcx,
1088 /// Indicates that one of the inputs is a "forced unit". This
1089 /// occurs in a case like `if foo { ... };`, where the missing else
1090 /// generates a "forced unit". Another example is a `loop { break;
1091 /// }`, where the `break` has no argument expression. We treat
1092 /// these cases slightly differently for error-reporting
1093 /// purposes. Note that these tend to correspond to cases where
1094 /// the `()` expression is implicit in the source, and hence we do
1095 /// not take an expression argument.
1097 /// The `augment_error` gives you a chance to extend the error
1098 /// message, in case any results (e.g., we use this to suggest
1099 /// removing a `;`).
1100 pub fn coerce_forced_unit<'a>(&mut self,
1101 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1102 cause: &ObligationCause<'tcx>,
1103 augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1104 label_unit_as_expected: bool)
1106 self.coerce_inner(fcx,
1110 Some(augment_error),
1111 label_unit_as_expected)
1114 /// The inner coercion "engine". If `expression` is `None`, this
1115 /// is a forced-unit case, and hence `expression_ty` must be
1117 fn coerce_inner<'a>(&mut self,
1118 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1119 cause: &ObligationCause<'tcx>,
1120 expression: Option<&'gcx hir::Expr>,
1121 mut expression_ty: Ty<'tcx>,
1122 augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1123 label_expression_as_expected: bool)
1125 // Incorporate whatever type inference information we have
1126 // until now; in principle we might also want to process
1127 // pending obligations, but doing so should only improve
1128 // compatibility (hopefully that is true) by helping us
1129 // uncover never types better.
1130 if expression_ty.is_ty_var() {
1131 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1134 // If we see any error types, just propagate that error
1136 if expression_ty.references_error() || self.merged_ty().references_error() {
1137 self.final_ty = Some(fcx.tcx.types.err);
1141 // Handle the actual type unification etc.
1142 let result = if let Some(expression) = expression {
1143 if self.pushed == 0 {
1144 // Special-case the first expression we are coercing.
1145 // To be honest, I'm not entirely sure why we do this.
1146 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1147 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1149 match self.expressions {
1150 Expressions::Dynamic(ref exprs) =>
1151 fcx.try_find_coercion_lub(cause,
1156 Expressions::UpFront(ref coercion_sites) =>
1157 fcx.try_find_coercion_lub(cause,
1158 &coercion_sites[0..self.pushed],
1165 // this is a hack for cases where we default to `()` because
1166 // the expression etc has been omitted from the source. An
1167 // example is an `if let` without an else:
1169 // if let Some(x) = ... { }
1171 // we wind up with a second match arm that is like `_ =>
1172 // ()`. That is the case we are considering here. We take
1173 // a different path to get the right "expected, found"
1174 // message and so forth (and because we know that
1175 // `expression_ty` will be unit).
1177 // Another example is `break` with no argument expression.
1178 assert!(expression_ty.is_unit(), "if let hack without unit type");
1179 fcx.at(cause, fcx.param_env)
1180 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1182 fcx.register_infer_ok_obligations(infer_ok);
1189 self.final_ty = Some(v);
1190 if let Some(e) = expression {
1191 match self.expressions {
1192 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1193 Expressions::UpFront(coercion_sites) => {
1194 // if the user gave us an array to validate, check that we got
1195 // the next expression in the list, as expected
1196 assert_eq!(coercion_sites[self.pushed].as_coercion_site().hir_id,
1204 let (expected, found) = if label_expression_as_expected {
1205 // In the case where this is a "forced unit", like
1206 // `break`, we want to call the `()` "expected"
1207 // since it is implied by the syntax.
1208 // (Note: not all force-units work this way.)"
1209 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1211 // Otherwise, the "expected" type for error
1212 // reporting is the current unification type,
1213 // which is basically the LUB of the expressions
1214 // we've seen so far (combined with the expected
1216 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1221 ObligationCauseCode::ReturnNoExpression => {
1222 db = struct_span_err!(
1223 fcx.tcx.sess, cause.span, E0069,
1224 "`return;` in a function whose return type is not `()`");
1225 db.span_label(cause.span, "return type is not `()`");
1227 ObligationCauseCode::BlockTailExpression(blk_id) => {
1228 let parent_id = fcx.tcx.hir().get_parent_node_by_hir_id(blk_id);
1229 db = self.report_return_mismatched_types(
1236 expression.map(|expr| (expr, blk_id)),
1239 ObligationCauseCode::ReturnType(id) => {
1240 db = self.report_return_mismatched_types(
1241 cause, expected, found, err, fcx, id, None);
1244 db = fcx.report_mismatched_types(cause, expected, found, err);
1248 if let Some(augment_error) = augment_error {
1249 augment_error(&mut db);
1252 // Error possibly reported in `check_assign` so avoid emitting error again.
1253 db.emit_unless(expression.filter(|e| fcx.is_assign_to_bool(e, expected)).is_some());
1255 self.final_ty = Some(fcx.tcx.types.err);
1260 fn report_return_mismatched_types<'a>(
1262 cause: &ObligationCause<'tcx>,
1265 err: TypeError<'tcx>,
1266 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1268 expression: Option<(&'gcx hir::Expr, hir::HirId)>,
1269 ) -> DiagnosticBuilder<'a> {
1270 let mut db = fcx.report_mismatched_types(cause, expected, found, err);
1272 let mut pointing_at_return_type = false;
1273 let mut return_sp = None;
1275 // Verify that this is a tail expression of a function, otherwise the
1276 // label pointing out the cause for the type coercion will be wrong
1277 // as prior return coercions would not be relevant (#57664).
1278 let parent_id = fcx.tcx.hir().get_parent_node_by_hir_id(id);
1279 let fn_decl = if let Some((expr, blk_id)) = expression {
1280 pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1288 let parent = fcx.tcx.hir().get_by_hir_id(parent_id);
1289 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1291 fcx.get_fn_decl(parent_id)
1294 if let (Some((fn_decl, can_suggest)), _) = (fn_decl, pointing_at_return_type) {
1295 if expression.is_none() {
1296 pointing_at_return_type |= fcx.suggest_missing_return_type(
1297 &mut db, &fn_decl, expected, found, can_suggest);
1299 if !pointing_at_return_type {
1300 return_sp = Some(fn_decl.output.span()); // `impl Trait` return type
1303 if let (Some(sp), Some(return_sp)) = (fcx.ret_coercion_span.borrow().as_ref(), return_sp) {
1304 db.span_label(return_sp, "expected because this return type...");
1305 db.span_label( *sp, format!(
1306 "...is found to be `{}` here",
1307 fcx.resolve_type_vars_with_obligations(expected),
1313 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
1314 if let Some(final_ty) = self.final_ty {
1317 // If we only had inputs that were of type `!` (or no
1318 // inputs at all), then the final type is `!`.
1319 assert_eq!(self.pushed, 0);
1325 /// Something that can be converted into an expression to which we can
1326 /// apply a coercion.
1327 pub trait AsCoercionSite {
1328 fn as_coercion_site(&self) -> &hir::Expr;
1331 impl AsCoercionSite for hir::Expr {
1332 fn as_coercion_site(&self) -> &hir::Expr {
1337 impl AsCoercionSite for P<hir::Expr> {
1338 fn as_coercion_site(&self) -> &hir::Expr {
1343 impl<'a, T> AsCoercionSite for &'a T
1344 where T: AsCoercionSite
1346 fn as_coercion_site(&self) -> &hir::Expr {
1347 (**self).as_coercion_site()
1351 impl AsCoercionSite for ! {
1352 fn as_coercion_site(&self) -> &hir::Expr {
1357 impl AsCoercionSite for hir::Arm {
1358 fn as_coercion_site(&self) -> &hir::Expr {