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, ClosureSubsts};
65 use rustc::ty::fold::TypeFoldable;
66 use rustc::ty::error::TypeError;
67 use rustc::ty::relate::RelateResult;
68 use smallvec::{smallvec, SmallVec};
70 use syntax::feature_gate;
71 use syntax::symbol::sym;
73 use rustc_target::spec::abi::Abi;
75 struct Coerce<'a, 'tcx> {
76 fcx: &'a FnCtxt<'a, 'tcx>,
77 cause: ObligationCause<'tcx>,
79 /// Determines whether or not allow_two_phase_borrow is set on any
80 /// autoref adjustments we create while coercing. We don't want to
81 /// allow deref coercions to create two-phase borrows, at least initially,
82 /// but we do need two-phase borrows for function argument reborrows.
83 /// See #47489 and #48598
84 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
85 allow_two_phase: AllowTwoPhase,
88 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
89 type Target = FnCtxt<'a, 'tcx>;
90 fn deref(&self) -> &Self::Target {
95 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
97 fn coerce_mutbls<'tcx>(from_mutbl: hir::Mutability,
98 to_mutbl: hir::Mutability)
99 -> RelateResult<'tcx, ()> {
100 match (from_mutbl, to_mutbl) {
101 (hir::MutMutable, hir::MutMutable) |
102 (hir::MutImmutable, hir::MutImmutable) |
103 (hir::MutMutable, hir::MutImmutable) => Ok(()),
104 (hir::MutImmutable, hir::MutMutable) => Err(TypeError::Mutability),
108 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> { vec![] }
110 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
111 move |target| vec![Adjustment { kind, target }]
114 fn success<'tcx>(adj: Vec<Adjustment<'tcx>>,
116 obligations: traits::PredicateObligations<'tcx>)
117 -> CoerceResult<'tcx> {
119 value: (adj, target),
124 impl<'f, 'tcx> Coerce<'f, 'tcx> {
126 fcx: &'f FnCtxt<'f, 'tcx>,
127 cause: ObligationCause<'tcx>,
128 allow_two_phase: AllowTwoPhase,
138 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
139 self.commit_if_ok(|_| {
141 self.at(&self.cause, self.fcx.param_env).lub(b, a)
143 self.at(&self.cause, self.fcx.param_env)
145 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
150 /// Unify two types (using sub or lub) and produce a specific coercion.
151 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F)
152 -> CoerceResult<'tcx>
153 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
155 self.unify(&a, &b).and_then(|InferOk { value: ty, obligations }| {
156 success(f(ty), ty, obligations)
160 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
161 let a = self.shallow_resolve(a);
162 debug!("Coerce.tys({:?} => {:?})", a, b);
164 // Just ignore error types.
165 if a.references_error() || b.references_error() {
166 return success(vec![], b, vec![]);
170 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
171 // type variable, we want `?T` to fallback to `!` if not
172 // otherwise constrained. An example where this arises:
174 // let _: Option<?T> = Some({ return; });
176 // here, we would coerce from `!` to `?T`.
177 let b = self.shallow_resolve(b);
178 return if self.shallow_resolve(b).is_ty_var() {
179 // Micro-optimization: no need for this if `b` is
180 // already resolved in some way.
181 let diverging_ty = self.next_diverging_ty_var(
183 kind: TypeVariableOriginKind::AdjustmentType,
184 span: self.cause.span,
187 self.unify_and(&b, &diverging_ty, simple(Adjust::NeverToAny))
189 success(simple(Adjust::NeverToAny)(b), b, vec![])
193 // Consider coercing the subtype to a DST
195 // NOTE: this is wrapped in a `commit_if_ok` because it creates
196 // a "spurious" type variable, and we don't want to have that
197 // type variable in memory if the coercion fails.
198 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
200 debug!("coerce: unsize successful");
203 debug!("coerce: unsize failed");
205 // Examine the supertype and consider auto-borrowing.
207 // Note: does not attempt to resolve type variables we encounter.
208 // See above for details.
210 ty::RawPtr(mt_b) => {
211 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
214 ty::Ref(r_b, ty, mutbl) => {
215 let mt_b = ty::TypeAndMut { ty, mutbl };
216 return self.coerce_borrowed_pointer(a, b, r_b, mt_b);
224 // Function items are coercible to any closure
225 // type; function pointers are not (that would
226 // require double indirection).
227 // Additionally, we permit coercion of function
228 // items to drop the unsafe qualifier.
229 self.coerce_from_fn_item(a, b)
232 // We permit coercion of fn pointers to drop the
234 self.coerce_from_fn_pointer(a, a_f, b)
236 ty::Closure(def_id_a, substs_a) => {
237 // Non-capturing closures are coercible to
238 // function pointers or unsafe function pointers.
239 // It cannot convert closures that require unsafe.
240 self.coerce_closure_to_fn(a, def_id_a, substs_a, b)
243 // Otherwise, just use unification rules.
244 self.unify_and(a, b, identity)
249 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
250 /// To match `A` with `B`, autoderef will be performed,
251 /// calling `deref`/`deref_mut` where necessary.
252 fn coerce_borrowed_pointer(&self,
255 r_b: ty::Region<'tcx>,
256 mt_b: TypeAndMut<'tcx>)
257 -> CoerceResult<'tcx>
259 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
261 // If we have a parameter of type `&M T_a` and the value
262 // provided is `expr`, we will be adding an implicit borrow,
263 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
264 // to type check, we will construct the type that `&M*expr` would
267 let (r_a, mt_a) = match a.sty {
268 ty::Ref(r_a, ty, mutbl) => {
269 let mt_a = ty::TypeAndMut { ty, mutbl };
270 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
273 _ => return self.unify_and(a, b, identity),
276 let span = self.cause.span;
278 let mut first_error = None;
279 let mut r_borrow_var = None;
280 let mut autoderef = self.autoderef(span, a);
281 let mut found = None;
283 for (referent_ty, autoderefs) in autoderef.by_ref() {
285 // Don't let this pass, otherwise it would cause
286 // &T to autoref to &&T.
290 // At this point, we have deref'd `a` to `referent_ty`. So
291 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
292 // In the autoderef loop for `&'a mut Vec<T>`, we would get
295 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
296 // - `Vec<T>` -- 1 deref
297 // - `[T]` -- 2 deref
299 // At each point after the first callback, we want to
300 // check to see whether this would match out target type
301 // (`&'b mut [T]`) if we autoref'd it. We can't just
302 // compare the referent types, though, because we still
303 // have to consider the mutability. E.g., in the case
304 // we've been considering, we have an `&mut` reference, so
305 // the `T` in `[T]` needs to be unified with equality.
307 // Therefore, we construct reference types reflecting what
308 // the types will be after we do the final auto-ref and
309 // compare those. Note that this means we use the target
310 // mutability [1], since it may be that we are coercing
311 // from `&mut T` to `&U`.
313 // One fine point concerns the region that we use. We
314 // choose the region such that the region of the final
315 // type that results from `unify` will be the region we
316 // want for the autoref:
318 // - if in sub mode, that means we want to use `'b` (the
319 // region from the target reference) for both
320 // pointers [2]. This is because sub mode (somewhat
321 // arbitrarily) returns the subtype region. In the case
322 // where we are coercing to a target type, we know we
323 // want to use that target type region (`'b`) because --
324 // for the program to type-check -- it must be the
325 // smaller of the two.
326 // - One fine point. It may be surprising that we can
327 // use `'b` without relating `'a` and `'b`. The reason
328 // that this is ok is that what we produce is
329 // effectively a `&'b *x` expression (if you could
330 // annotate the region of a borrow), and regionck has
331 // code that adds edges from the region of a borrow
332 // (`'b`, here) into the regions in the borrowed
333 // expression (`*x`, here). (Search for "link".)
334 // - if in lub mode, things can get fairly complicated. The
335 // easiest thing is just to make a fresh
336 // region variable [4], which effectively means we defer
337 // the decision to region inference (and regionck, which will add
338 // some more edges to this variable). However, this can wind up
339 // creating a crippling number of variables in some cases --
340 // e.g., #32278 -- so we optimize one particular case [3].
341 // Let me try to explain with some examples:
342 // - The "running example" above represents the simple case,
343 // where we have one `&` reference at the outer level and
344 // ownership all the rest of the way down. In this case,
345 // we want `LUB('a, 'b)` as the resulting region.
346 // - However, if there are nested borrows, that region is
347 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
348 // `&'b T`. In this case, `'a` is actually irrelevant.
349 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
350 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
351 // (The errors actually show up in borrowck, typically, because
352 // this extra edge causes the region `'a` to be inferred to something
353 // too big, which then results in borrowck errors.)
354 // - We could track the innermost shared reference, but there is already
355 // code in regionck that has the job of creating links between
356 // the region of a borrow and the regions in the thing being
357 // borrowed (here, `'a` and `'x`), and it knows how to handle
358 // all the various cases. So instead we just make a region variable
359 // and let regionck figure it out.
360 let r = if !self.use_lub {
362 } else if autoderefs == 1 {
365 if r_borrow_var.is_none() {
366 // create var lazilly, at most once
367 let coercion = Coercion(span);
368 let r = self.next_region_var(coercion);
369 r_borrow_var = Some(r); // [4] above
371 r_borrow_var.unwrap()
373 let derefd_ty_a = self.tcx.mk_ref(r,
376 mutbl: mt_b.mutbl, // [1] above
378 match self.unify(derefd_ty_a, b) {
384 if first_error.is_none() {
385 first_error = Some(err);
391 // Extract type or return an error. We return the first error
392 // we got, which should be from relating the "base" type
393 // (e.g., in example above, the failure from relating `Vec<T>`
394 // to the target type), since that should be the least
396 let InferOk { value: ty, mut obligations } = match found {
399 let err = first_error.expect("coerce_borrowed_pointer had no error");
400 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
405 if ty == a && mt_a.mutbl == hir::MutImmutable && autoderef.step_count() == 1 {
406 // As a special case, if we would produce `&'a *x`, that's
407 // a total no-op. We end up with the type `&'a T` just as
408 // we started with. In that case, just skip it
409 // altogether. This is just an optimization.
411 // Note that for `&mut`, we DO want to reborrow --
412 // otherwise, this would be a move, which might be an
413 // error. For example `foo(self.x)` where `self` and
414 // `self.x` both have `&mut `type would be a move of
415 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
416 // which is a borrow.
417 assert_eq!(mt_b.mutbl, hir::MutImmutable); // can only coerce &T -> &U
418 return success(vec![], ty, obligations);
421 let needs = Needs::maybe_mut_place(mt_b.mutbl);
422 let InferOk { value: mut adjustments, obligations: o }
423 = autoderef.adjust_steps_as_infer_ok(self, needs);
424 obligations.extend(o);
425 obligations.extend(autoderef.into_obligations());
427 // Now apply the autoref. We have to extract the region out of
428 // the final ref type we got.
429 let r_borrow = match ty.sty {
430 ty::Ref(r_borrow, _, _) => r_borrow,
431 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
433 let mutbl = match mt_b.mutbl {
434 hir::MutImmutable => AutoBorrowMutability::Immutable,
435 hir::MutMutable => AutoBorrowMutability::Mutable {
436 allow_two_phase_borrow: self.allow_two_phase,
439 adjustments.push(Adjustment {
440 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
444 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}",
448 success(adjustments, ty, obligations)
452 // &[T; n] or &mut [T; n] -> &[T]
453 // or &mut [T; n] -> &mut [T]
454 // or &Concrete -> &Trait, etc.
455 fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
456 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
458 let traits = (self.tcx.lang_items().unsize_trait(),
459 self.tcx.lang_items().coerce_unsized_trait());
460 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
463 debug!("missing Unsize or CoerceUnsized traits");
464 return Err(TypeError::Mismatch);
467 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
468 // a DST unless we have to. This currently comes out in the wash since
469 // we can't unify [T] with U. But to properly support DST, we need to allow
470 // that, at which point we will need extra checks on the target here.
472 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
473 let reborrow = match (&source.sty, &target.sty) {
474 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
475 coerce_mutbls(mutbl_a, mutbl_b)?;
477 let coercion = Coercion(self.cause.span);
478 let r_borrow = self.next_region_var(coercion);
479 let mutbl = match mutbl_b {
480 hir::MutImmutable => AutoBorrowMutability::Immutable,
481 hir::MutMutable => AutoBorrowMutability::Mutable {
482 // We don't allow two-phase borrows here, at least for initial
483 // implementation. If it happens that this coercion is a function argument,
484 // the reborrow in coerce_borrowed_ptr will pick it up.
485 allow_two_phase_borrow: AllowTwoPhase::No,
489 kind: Adjust::Deref(None),
492 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
493 target: self.tcx.mk_ref(r_borrow, ty::TypeAndMut {
499 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
500 coerce_mutbls(mt_a, mt_b)?;
503 kind: Adjust::Deref(None),
506 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
507 target: self.tcx.mk_ptr(ty::TypeAndMut {
515 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
517 // Setup either a subtyping or a LUB relationship between
518 // the `CoerceUnsized` target type and the expected type.
519 // We only have the latter, so we use an inference variable
520 // for the former and let type inference do the rest.
521 let origin = TypeVariableOrigin {
522 kind: TypeVariableOriginKind::MiscVariable,
523 span: self.cause.span,
525 let coerce_target = self.next_ty_var(origin);
526 let mut coercion = self.unify_and(coerce_target, target, |target| {
527 let unsize = Adjustment {
528 kind: Adjust::Pointer(PointerCast::Unsize),
532 None => vec![unsize],
533 Some((ref deref, ref autoref)) => {
534 vec![deref.clone(), autoref.clone(), unsize]
539 let mut selcx = traits::SelectionContext::new(self);
541 // Create an obligation for `Source: CoerceUnsized<Target>`.
542 let cause = ObligationCause::misc(self.cause.span, self.body_id);
544 // Use a FIFO queue for this custom fulfillment procedure.
546 // A Vec (or SmallVec) is not a natural choice for a queue. However,
547 // this code path is hot, and this queue usually has a max length of 1
548 // and almost never more than 3. By using a SmallVec we avoid an
549 // allocation, at the (very small) cost of (occasionally) having to
550 // shift subsequent elements down when removing the front element.
551 let mut queue: SmallVec<[_; 4]> =
552 smallvec![self.tcx.predicate_for_trait_def(self.fcx.param_env,
557 &[coerce_target.into()])];
559 let mut has_unsized_tuple_coercion = false;
561 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
562 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
563 // inference might unify those two inner type variables later.
564 let traits = [coerce_unsized_did, unsize_did];
565 while !queue.is_empty() {
566 let obligation = queue.remove(0);
567 debug!("coerce_unsized resolve step: {:?}", obligation);
568 let trait_ref = match obligation.predicate {
569 ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => {
570 if unsize_did == tr.def_id() {
571 let sty = &tr.skip_binder().input_types().nth(1).unwrap().sty;
572 if let ty::Tuple(..) = sty {
573 debug!("coerce_unsized: found unsized tuple coercion");
574 has_unsized_tuple_coercion = true;
580 coercion.obligations.push(obligation);
584 match selcx.select(&obligation.with(trait_ref)) {
585 // Uncertain or unimplemented.
587 if trait_ref.def_id() == unsize_did {
588 let trait_ref = self.resolve_vars_if_possible(&trait_ref);
589 let self_ty = trait_ref.skip_binder().self_ty();
590 let unsize_ty = trait_ref.skip_binder().input_types().nth(1).unwrap();
591 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_ref);
592 match (&self_ty.sty, &unsize_ty.sty) {
593 (ty::Infer(ty::TyVar(v)),
594 ty::Dynamic(..)) if self.type_var_is_sized(*v) => {
595 debug!("coerce_unsized: have sized infer {:?}", v);
596 coercion.obligations.push(obligation);
597 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
601 // Some other case for `$0: Unsize<Something>`. Note that we
602 // hit this case even if `Something` is a sized type, so just
603 // don't do the coercion.
604 debug!("coerce_unsized: ambiguous unsize");
605 return Err(TypeError::Mismatch);
609 debug!("coerce_unsized: early return - ambiguous");
610 return Err(TypeError::Mismatch);
613 Err(traits::Unimplemented) => {
614 debug!("coerce_unsized: early return - can't prove obligation");
615 return Err(TypeError::Mismatch);
618 // Object safety violations or miscellaneous.
620 self.report_selection_error(&obligation, &err, false);
621 // Treat this like an obligation and follow through
622 // with the unsizing - the lack of a coercion should
623 // be silent, as it causes a type mismatch later.
626 Ok(Some(vtable)) => {
627 queue.extend(vtable.nested_obligations())
632 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
633 feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
634 sym::unsized_tuple_coercion,
636 feature_gate::GateIssue::Language,
637 feature_gate::EXPLAIN_UNSIZED_TUPLE_COERCION);
643 fn coerce_from_safe_fn<F, G>(&self,
645 fn_ty_a: ty::PolyFnSig<'tcx>,
649 -> CoerceResult<'tcx>
650 where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
651 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>
653 if let ty::FnPtr(fn_ty_b) = b.sty {
654 if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe)
655 = (fn_ty_a.unsafety(), fn_ty_b.unsafety())
657 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
658 return self.unify_and(unsafe_a, b, to_unsafe);
661 self.unify_and(a, b, normal)
664 fn coerce_from_fn_pointer(&self,
666 fn_ty_a: ty::PolyFnSig<'tcx>,
668 -> CoerceResult<'tcx> {
669 //! Attempts to coerce from the type of a Rust function item
670 //! into a closure or a `proc`.
673 let b = self.shallow_resolve(b);
674 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
676 self.coerce_from_safe_fn(a, fn_ty_a, b,
677 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)), identity)
680 fn coerce_from_fn_item(&self,
683 -> CoerceResult<'tcx> {
684 //! Attempts to coerce from the type of a Rust function item
685 //! into a closure or a `proc`.
687 let b = self.shallow_resolve(b);
688 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
692 let a_sig = a.fn_sig(self.tcx);
693 // Intrinsics are not coercible to function pointers
694 if a_sig.abi() == Abi::RustIntrinsic ||
695 a_sig.abi() == Abi::PlatformIntrinsic {
696 return Err(TypeError::IntrinsicCast);
698 let InferOk { value: a_sig, mut obligations } =
699 self.normalize_associated_types_in_as_infer_ok(self.cause.span, &a_sig);
701 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
702 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
709 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
713 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
718 simple(Adjust::Pointer(PointerCast::ReifyFnPointer))
721 obligations.extend(o2);
722 Ok(InferOk { value, obligations })
724 _ => self.unify_and(a, b, identity),
728 fn coerce_closure_to_fn(&self,
731 substs_a: ClosureSubsts<'tcx>,
733 -> CoerceResult<'tcx> {
734 //! Attempts to coerce from the type of a non-capturing closure
735 //! into a function pointer.
738 let b = self.shallow_resolve(b);
741 ty::FnPtr(fn_ty) if self.tcx.upvars(def_id_a).map_or(true, |v| v.is_empty()) => {
742 // We coerce the closure, which has fn type
743 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
745 // `fn(arg0,arg1,...) -> _`
747 // `unsafe fn(arg0,arg1,...) -> _`
748 let sig = self.closure_sig(def_id_a, substs_a);
749 let unsafety = fn_ty.unsafety();
750 let pointer_ty = self.tcx.coerce_closure_fn_ty(sig, unsafety);
751 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})",
753 self.unify_and(pointer_ty, b, simple(
754 Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))
757 _ => self.unify_and(a, b, identity),
761 fn coerce_unsafe_ptr(&self,
764 mutbl_b: hir::Mutability)
765 -> CoerceResult<'tcx> {
766 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
768 let (is_ref, mt_a) = match a.sty {
769 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
770 ty::RawPtr(mt) => (false, mt),
771 _ => return self.unify_and(a, b, identity)
774 // Check that the types which they point at are compatible.
775 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut {
779 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
780 // Although references and unsafe ptrs have the same
781 // representation, we still register an Adjust::DerefRef so that
782 // regionck knows that the region for `a` must be valid here.
784 self.unify_and(a_unsafe, b, |target| {
786 kind: Adjust::Deref(None),
789 kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
793 } else if mt_a.mutbl != mutbl_b {
795 a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer))
798 self.unify_and(a_unsafe, b, identity)
803 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
804 /// Attempt to coerce an expression to a type, and return the
805 /// adjusted type of the expression, if successful.
806 /// Adjustments are only recorded if the coercion succeeded.
807 /// The expressions *must not* have any pre-existing adjustments.
813 allow_two_phase: AllowTwoPhase,
814 ) -> RelateResult<'tcx, Ty<'tcx>> {
815 let source = self.resolve_type_vars_with_obligations(expr_ty);
816 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
818 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
819 let coerce = Coerce::new(self, cause, allow_two_phase);
820 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
822 let (adjustments, _) = self.register_infer_ok_obligations(ok);
823 self.apply_adjustments(expr, adjustments);
827 /// Same as `try_coerce()`, but without side-effects.
828 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
829 let source = self.resolve_type_vars_with_obligations(expr_ty);
830 debug!("coercion::can({:?} -> {:?})", source, target);
832 let cause = self.cause(syntax_pos::DUMMY_SP, ObligationCauseCode::ExprAssignable);
833 // We don't ever need two-phase here since we throw out the result of the coercion
834 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
835 self.probe(|_| coerce.coerce(source, target)).is_ok()
838 /// Given some expressions, their known unified type and another expression,
839 /// tries to unify the types, potentially inserting coercions on any of the
840 /// provided expressions and returns their LUB (aka "common supertype").
842 /// This is really an internal helper. From outside the coercion
843 /// module, you should instantiate a `CoerceMany` instance.
844 fn try_find_coercion_lub<E>(&self,
845 cause: &ObligationCause<'tcx>,
850 -> RelateResult<'tcx, Ty<'tcx>>
851 where E: AsCoercionSite
853 let prev_ty = self.resolve_type_vars_with_obligations(prev_ty);
854 let new_ty = self.resolve_type_vars_with_obligations(new_ty);
855 debug!("coercion::try_find_coercion_lub({:?}, {:?})", prev_ty, new_ty);
857 // Special-case that coercion alone cannot handle:
858 // Two function item types of differing IDs or InternalSubsts.
859 if let (&ty::FnDef(..), &ty::FnDef(..)) = (&prev_ty.sty, &new_ty.sty) {
860 // Don't reify if the function types have a LUB, i.e., they
861 // are the same function and their parameters have a LUB.
862 let lub_ty = self.commit_if_ok(|_| {
863 self.at(cause, self.param_env)
864 .lub(prev_ty, new_ty)
865 }).map(|ok| self.register_infer_ok_obligations(ok));
868 // We have a LUB of prev_ty and new_ty, just return it.
872 // The signature must match.
873 let a_sig = prev_ty.fn_sig(self.tcx);
874 let a_sig = self.normalize_associated_types_in(new.span, &a_sig);
875 let b_sig = new_ty.fn_sig(self.tcx);
876 let b_sig = self.normalize_associated_types_in(new.span, &b_sig);
877 let sig = self.at(cause, self.param_env)
878 .trace(prev_ty, new_ty)
880 .map(|ok| self.register_infer_ok_obligations(ok))?;
882 // Reify both sides and return the reified fn pointer type.
883 let fn_ptr = self.tcx.mk_fn_ptr(sig);
884 for expr in exprs.iter().map(|e| e.as_coercion_site()).chain(Some(new)) {
885 // The only adjustment that can produce an fn item is
886 // `NeverToAny`, so this should always be valid.
887 self.apply_adjustments(expr, vec![Adjustment {
888 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
895 // Configure a Coerce instance to compute the LUB.
896 // We don't allow two-phase borrows on any autorefs this creates since we
897 // probably aren't processing function arguments here and even if we were,
898 // they're going to get autorefed again anyway and we can apply 2-phase borrows
900 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
901 coerce.use_lub = true;
903 // First try to coerce the new expression to the type of the previous ones,
904 // but only if the new expression has no coercion already applied to it.
905 let mut first_error = None;
906 if !self.tables.borrow().adjustments().contains_key(new.hir_id) {
907 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
910 let (adjustments, target) = self.register_infer_ok_obligations(ok);
911 self.apply_adjustments(new, adjustments);
914 Err(e) => first_error = Some(e),
918 // Then try to coerce the previous expressions to the type of the new one.
919 // This requires ensuring there are no coercions applied to *any* of the
920 // previous expressions, other than noop reborrows (ignoring lifetimes).
922 let expr = expr.as_coercion_site();
923 let noop = match self.tables.borrow().expr_adjustments(expr) {
925 Adjustment { kind: Adjust::Deref(_), .. },
926 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }
928 match self.node_ty(expr.hir_id).sty {
929 ty::Ref(_, _, mt_orig) => {
930 let mutbl_adj: hir::Mutability = mutbl_adj.into();
931 // Reborrow that we can safely ignore, because
932 // the next adjustment can only be a Deref
933 // which will be merged into it.
939 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
944 return self.commit_if_ok(|_|
945 self.at(cause, self.param_env)
946 .lub(prev_ty, new_ty)
947 ).map(|ok| self.register_infer_ok_obligations(ok));
951 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
953 // Avoid giving strange errors on failed attempts.
954 if let Some(e) = first_error {
957 self.commit_if_ok(|_|
958 self.at(cause, self.param_env)
959 .lub(prev_ty, new_ty)
960 ).map(|ok| self.register_infer_ok_obligations(ok))
964 let (adjustments, target) = self.register_infer_ok_obligations(ok);
966 let expr = expr.as_coercion_site();
967 self.apply_adjustments(expr, adjustments.clone());
975 /// CoerceMany encapsulates the pattern you should use when you have
976 /// many expressions that are all getting coerced to a common
977 /// type. This arises, for example, when you have a match (the result
978 /// of each arm is coerced to a common type). It also arises in less
979 /// obvious places, such as when you have many `break foo` expressions
980 /// that target the same loop, or the various `return` expressions in
983 /// The basic protocol is as follows:
985 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
986 /// This will also serve as the "starting LUB". The expectation is
987 /// that this type is something which all of the expressions *must*
988 /// be coercible to. Use a fresh type variable if needed.
989 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
990 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
991 /// unit. This happens for example if you have a `break` with no expression,
992 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
993 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
994 /// from you so that you don't have to worry your pretty head about it.
995 /// But if an error is reported, the final type will be `err`.
996 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
997 /// previously coerced expressions.
998 /// - When all done, invoke `complete()`. This will return the LUB of
999 /// all your expressions.
1000 /// - WARNING: I don't believe this final type is guaranteed to be
1001 /// related to your initial `expected_ty` in any particular way,
1002 /// although it will typically be a subtype, so you should check it.
1003 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1004 /// previously coerced expressions.
1009 /// let mut coerce = CoerceMany::new(expected_ty);
1010 /// for expr in exprs {
1011 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1012 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1014 /// let final_ty = coerce.complete(fcx);
1016 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1017 expected_ty: Ty<'tcx>,
1018 final_ty: Option<Ty<'tcx>>,
1019 expressions: Expressions<'tcx, 'exprs, E>,
1023 /// The type of a `CoerceMany` that is storing up the expressions into
1024 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1025 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, P<hir::Expr>>;
1027 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1028 Dynamic(Vec<&'tcx hir::Expr>),
1029 UpFront(&'exprs [E]),
1032 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1033 /// The usual case; collect the set of expressions dynamically.
1034 /// If the full set of coercion sites is known before hand,
1035 /// consider `with_coercion_sites()` instead to avoid allocation.
1036 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1037 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1040 /// As an optimization, you can create a `CoerceMany` with a
1041 /// pre-existing slice of expressions. In this case, you are
1042 /// expected to pass each element in the slice to `coerce(...)` in
1043 /// order. This is used with arrays in particular to avoid
1044 /// needlessly cloning the slice.
1045 pub fn with_coercion_sites(expected_ty: Ty<'tcx>,
1046 coercion_sites: &'exprs [E])
1048 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1051 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1060 /// Returns the "expected type" with which this coercion was
1061 /// constructed. This represents the "downward propagated" type
1062 /// that was given to us at the start of typing whatever construct
1063 /// we are typing (e.g., the match expression).
1065 /// Typically, this is used as the expected type when
1066 /// type-checking each of the alternative expressions whose types
1067 /// we are trying to merge.
1068 pub fn expected_ty(&self) -> Ty<'tcx> {
1072 /// Returns the current "merged type", representing our best-guess
1073 /// at the LUB of the expressions we've seen so far (if any). This
1074 /// isn't *final* until you call `self.final()`, which will return
1075 /// the merged type.
1076 pub fn merged_ty(&self) -> Ty<'tcx> {
1077 self.final_ty.unwrap_or(self.expected_ty)
1080 /// Indicates that the value generated by `expression`, which is
1081 /// of type `expression_ty`, is one of the possibilities that we
1082 /// could coerce from. This will record `expression`, and later
1083 /// calls to `coerce` may come back and add adjustments and things
1087 fcx: &FnCtxt<'a, 'tcx>,
1088 cause: &ObligationCause<'tcx>,
1089 expression: &'tcx hir::Expr,
1090 expression_ty: Ty<'tcx>,
1092 self.coerce_inner(fcx,
1099 /// Indicates that one of the inputs is a "forced unit". This
1100 /// occurs in a case like `if foo { ... };`, where the missing else
1101 /// generates a "forced unit". Another example is a `loop { break;
1102 /// }`, where the `break` has no argument expression. We treat
1103 /// these cases slightly differently for error-reporting
1104 /// purposes. Note that these tend to correspond to cases where
1105 /// the `()` expression is implicit in the source, and hence we do
1106 /// not take an expression argument.
1108 /// The `augment_error` gives you a chance to extend the error
1109 /// message, in case any results (e.g., we use this to suggest
1110 /// removing a `;`).
1111 pub fn coerce_forced_unit<'a>(
1113 fcx: &FnCtxt<'a, 'tcx>,
1114 cause: &ObligationCause<'tcx>,
1115 augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1116 label_unit_as_expected: bool,
1118 self.coerce_inner(fcx,
1122 Some(augment_error),
1123 label_unit_as_expected)
1126 /// The inner coercion "engine". If `expression` is `None`, this
1127 /// is a forced-unit case, and hence `expression_ty` must be
1129 fn coerce_inner<'a>(
1131 fcx: &FnCtxt<'a, 'tcx>,
1132 cause: &ObligationCause<'tcx>,
1133 expression: Option<&'tcx hir::Expr>,
1134 mut expression_ty: Ty<'tcx>,
1135 augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1136 label_expression_as_expected: bool,
1138 // Incorporate whatever type inference information we have
1139 // until now; in principle we might also want to process
1140 // pending obligations, but doing so should only improve
1141 // compatibility (hopefully that is true) by helping us
1142 // uncover never types better.
1143 if expression_ty.is_ty_var() {
1144 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1147 // If we see any error types, just propagate that error
1149 if expression_ty.references_error() || self.merged_ty().references_error() {
1150 self.final_ty = Some(fcx.tcx.types.err);
1154 // Handle the actual type unification etc.
1155 let result = if let Some(expression) = expression {
1156 if self.pushed == 0 {
1157 // Special-case the first expression we are coercing.
1158 // To be honest, I'm not entirely sure why we do this.
1159 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1160 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1162 match self.expressions {
1163 Expressions::Dynamic(ref exprs) =>
1164 fcx.try_find_coercion_lub(cause,
1169 Expressions::UpFront(ref coercion_sites) =>
1170 fcx.try_find_coercion_lub(cause,
1171 &coercion_sites[0..self.pushed],
1178 // this is a hack for cases where we default to `()` because
1179 // the expression etc has been omitted from the source. An
1180 // example is an `if let` without an else:
1182 // if let Some(x) = ... { }
1184 // we wind up with a second match arm that is like `_ =>
1185 // ()`. That is the case we are considering here. We take
1186 // a different path to get the right "expected, found"
1187 // message and so forth (and because we know that
1188 // `expression_ty` will be unit).
1190 // Another example is `break` with no argument expression.
1191 assert!(expression_ty.is_unit(), "if let hack without unit type");
1192 fcx.at(cause, fcx.param_env)
1193 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1195 fcx.register_infer_ok_obligations(infer_ok);
1202 self.final_ty = Some(v);
1203 if let Some(e) = expression {
1204 match self.expressions {
1205 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1206 Expressions::UpFront(coercion_sites) => {
1207 // if the user gave us an array to validate, check that we got
1208 // the next expression in the list, as expected
1209 assert_eq!(coercion_sites[self.pushed].as_coercion_site().hir_id,
1217 let (expected, found) = if label_expression_as_expected {
1218 // In the case where this is a "forced unit", like
1219 // `break`, we want to call the `()` "expected"
1220 // since it is implied by the syntax.
1221 // (Note: not all force-units work this way.)"
1222 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1224 // Otherwise, the "expected" type for error
1225 // reporting is the current unification type,
1226 // which is basically the LUB of the expressions
1227 // we've seen so far (combined with the expected
1229 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1234 ObligationCauseCode::ReturnNoExpression => {
1235 db = struct_span_err!(
1236 fcx.tcx.sess, cause.span, E0069,
1237 "`return;` in a function whose return type is not `()`");
1238 db.span_label(cause.span, "return type is not `()`");
1240 ObligationCauseCode::BlockTailExpression(blk_id) => {
1241 let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1242 db = self.report_return_mismatched_types(
1249 expression.map(|expr| (expr, blk_id)),
1252 ObligationCauseCode::ReturnType(id) => {
1253 db = self.report_return_mismatched_types(
1254 cause, expected, found, err, fcx, id, None);
1257 db = fcx.report_mismatched_types(cause, expected, found, err);
1261 if let Some(augment_error) = augment_error {
1262 augment_error(&mut db);
1265 // Error possibly reported in `check_assign` so avoid emitting error again.
1266 db.emit_unless(expression.filter(|e| fcx.is_assign_to_bool(e, expected)).is_some());
1268 self.final_ty = Some(fcx.tcx.types.err);
1273 fn report_return_mismatched_types<'a>(
1275 cause: &ObligationCause<'tcx>,
1278 err: TypeError<'tcx>,
1279 fcx: &FnCtxt<'a, 'tcx>,
1281 expression: Option<(&'tcx hir::Expr, hir::HirId)>,
1282 ) -> DiagnosticBuilder<'a> {
1283 let mut db = fcx.report_mismatched_types(cause, expected, found, err);
1285 let mut pointing_at_return_type = false;
1286 let mut return_sp = None;
1288 // Verify that this is a tail expression of a function, otherwise the
1289 // label pointing out the cause for the type coercion will be wrong
1290 // as prior return coercions would not be relevant (#57664).
1291 let parent_id = fcx.tcx.hir().get_parent_node(id);
1292 let fn_decl = if let Some((expr, blk_id)) = expression {
1293 pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1301 let parent = fcx.tcx.hir().get(parent_id);
1302 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1304 fcx.get_fn_decl(parent_id)
1307 if let (Some((fn_decl, can_suggest)), _) = (fn_decl, pointing_at_return_type) {
1308 if expression.is_none() {
1309 pointing_at_return_type |= fcx.suggest_missing_return_type(
1310 &mut db, &fn_decl, expected, found, can_suggest);
1312 if !pointing_at_return_type {
1313 return_sp = Some(fn_decl.output.span()); // `impl Trait` return type
1316 if let (Some(sp), Some(return_sp)) = (fcx.ret_coercion_span.borrow().as_ref(), return_sp) {
1317 db.span_label(return_sp, "expected because this return type...");
1318 db.span_label( *sp, format!(
1319 "...is found to be `{}` here",
1320 fcx.resolve_type_vars_with_obligations(expected),
1326 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1327 if let Some(final_ty) = self.final_ty {
1330 // If we only had inputs that were of type `!` (or no
1331 // inputs at all), then the final type is `!`.
1332 assert_eq!(self.pushed, 0);
1338 /// Something that can be converted into an expression to which we can
1339 /// apply a coercion.
1340 pub trait AsCoercionSite {
1341 fn as_coercion_site(&self) -> &hir::Expr;
1344 impl AsCoercionSite for hir::Expr {
1345 fn as_coercion_site(&self) -> &hir::Expr {
1350 impl AsCoercionSite for P<hir::Expr> {
1351 fn as_coercion_site(&self) -> &hir::Expr {
1356 impl<'a, T> AsCoercionSite for &'a T
1357 where T: AsCoercionSite
1359 fn as_coercion_site(&self) -> &hir::Expr {
1360 (**self).as_coercion_site()
1364 impl AsCoercionSite for ! {
1365 fn as_coercion_site(&self) -> &hir::Expr {
1370 impl AsCoercionSite for hir::Arm {
1371 fn as_coercion_site(&self) -> &hir::Expr {