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 things (that is, when the expected type is &T
14 //! but you have &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/*.rs` tests for
17 //! examples of where this is useful.
21 //! When infering the generic arguments of functions, the argument
22 //! order is relevant, which can lead to the following edge case:
25 //! fn foo<T>(a: T, b: T) {
29 //! foo(&7i32, &mut 7i32);
30 //! // This compiles, as we first infer `T` to be `&i32`,
31 //! // and then coerce `&mut 7i32` to `&7i32`.
33 //! foo(&mut 7i32, &7i32);
34 //! // This does not compile, as we first infer `T` to be `&mut i32`
35 //! // and are then unable to coerce `&7i32` to `&mut i32`.
38 use crate::astconv::AstConv;
39 use crate::check::FnCtxt;
40 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
42 use rustc_hir::def_id::DefId;
43 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
44 use rustc_infer::infer::{Coercion, InferOk, InferResult};
45 use rustc_middle::ty::adjustment::{
46 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast,
48 use rustc_middle::ty::error::TypeError;
49 use rustc_middle::ty::fold::TypeFoldable;
50 use rustc_middle::ty::relate::RelateResult;
51 use rustc_middle::ty::subst::SubstsRef;
52 use rustc_middle::ty::{self, Ty, TypeAndMut};
53 use rustc_session::parse::feature_err;
54 use rustc_span::symbol::sym;
55 use rustc_span::{self, BytePos, Span};
56 use rustc_target::spec::abi::Abi;
57 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
58 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode};
60 use smallvec::{smallvec, SmallVec};
63 struct Coerce<'a, 'tcx> {
64 fcx: &'a FnCtxt<'a, 'tcx>,
65 cause: ObligationCause<'tcx>,
67 /// Determines whether or not allow_two_phase_borrow is set on any
68 /// autoref adjustments we create while coercing. We don't want to
69 /// allow deref coercions to create two-phase borrows, at least initially,
70 /// but we do need two-phase borrows for function argument reborrows.
71 /// See #47489 and #48598
72 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
73 allow_two_phase: AllowTwoPhase,
76 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
77 type Target = FnCtxt<'a, 'tcx>;
78 fn deref(&self) -> &Self::Target {
83 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
85 /// Coercing a mutable reference to an immutable works, while
86 /// coercing `&T` to `&mut T` should be forbidden.
87 fn coerce_mutbls<'tcx>(
88 from_mutbl: hir::Mutability,
89 to_mutbl: hir::Mutability,
90 ) -> RelateResult<'tcx, ()> {
91 match (from_mutbl, to_mutbl) {
92 (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not)
93 | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()),
94 (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability),
98 /// Do not require any adjustments, i.e. coerce `x -> x`.
99 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> {
103 fn simple(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
104 move |target| vec![Adjustment { kind, target }]
107 /// This always returns `Ok(...)`.
109 adj: Vec<Adjustment<'tcx>>,
111 obligations: traits::PredicateObligations<'tcx>,
112 ) -> CoerceResult<'tcx> {
113 Ok(InferOk { value: (adj, target), obligations })
116 impl<'f, 'tcx> Coerce<'f, 'tcx> {
118 fcx: &'f FnCtxt<'f, 'tcx>,
119 cause: ObligationCause<'tcx>,
120 allow_two_phase: AllowTwoPhase,
122 Coerce { fcx, cause, allow_two_phase, use_lub: false }
125 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
126 debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
127 self.commit_if_ok(|_| {
129 self.at(&self.cause, self.fcx.param_env).lub(b, a)
131 self.at(&self.cause, self.fcx.param_env)
133 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
138 /// Unify two types (using sub or lub) and produce a specific coercion.
139 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx>
141 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
144 .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations))
147 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
148 let a = self.shallow_resolve(a);
149 debug!("Coerce.tys({:?} => {:?})", a, b);
151 // Just ignore error types.
152 if a.references_error() || b.references_error() {
153 return success(vec![], self.fcx.tcx.ty_error(), vec![]);
157 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
158 // type variable, we want `?T` to fallback to `!` if not
159 // otherwise constrained. An example where this arises:
161 // let _: Option<?T> = Some({ return; });
163 // here, we would coerce from `!` to `?T`.
164 let b = self.shallow_resolve(b);
165 return if self.shallow_resolve(b).is_ty_var() {
166 // Micro-optimization: no need for this if `b` is
167 // already resolved in some way.
168 let diverging_ty = self.next_diverging_ty_var(TypeVariableOrigin {
169 kind: TypeVariableOriginKind::AdjustmentType,
170 span: self.cause.span,
172 self.unify_and(&b, &diverging_ty, simple(Adjust::NeverToAny))
174 success(simple(Adjust::NeverToAny)(b), b, vec![])
178 // Consider coercing the subtype to a DST
180 // NOTE: this is wrapped in a `commit_if_ok` because it creates
181 // a "spurious" type variable, and we don't want to have that
182 // type variable in memory if the coercion fails.
183 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
186 debug!("coerce: unsize successful");
189 Err(TypeError::ObjectUnsafeCoercion(did)) => {
190 debug!("coerce: unsize not object safe");
191 return Err(TypeError::ObjectUnsafeCoercion(did));
195 debug!("coerce: unsize failed");
197 // Examine the supertype and consider auto-borrowing.
199 // Note: does not attempt to resolve type variables we encounter.
200 // See above for details.
202 ty::RawPtr(mt_b) => {
203 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
205 ty::Ref(r_b, _, mutbl_b) => {
206 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
213 // Function items are coercible to any closure
214 // type; function pointers are not (that would
215 // require double indirection).
216 // Additionally, we permit coercion of function
217 // items to drop the unsafe qualifier.
218 self.coerce_from_fn_item(a, b)
221 // We permit coercion of fn pointers to drop the
223 self.coerce_from_fn_pointer(a, a_f, b)
225 ty::Closure(closure_def_id_a, substs_a) => {
226 // Non-capturing closures are coercible to
227 // function pointers or unsafe function pointers.
228 // It cannot convert closures that require unsafe.
229 self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b)
232 // Otherwise, just use unification rules.
233 self.unify_and(a, b, identity)
238 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
239 /// To match `A` with `B`, autoderef will be performed,
240 /// calling `deref`/`deref_mut` where necessary.
241 fn coerce_borrowed_pointer(
245 r_b: ty::Region<'tcx>,
246 mutbl_b: hir::Mutability,
247 ) -> CoerceResult<'tcx> {
248 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
250 // If we have a parameter of type `&M T_a` and the value
251 // provided is `expr`, we will be adding an implicit borrow,
252 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
253 // to type check, we will construct the type that `&M*expr` would
256 let (r_a, mt_a) = match *a.kind() {
257 ty::Ref(r_a, ty, mutbl) => {
258 let mt_a = ty::TypeAndMut { ty, mutbl };
259 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
262 _ => return self.unify_and(a, b, identity),
265 let span = self.cause.span;
267 let mut first_error = None;
268 let mut r_borrow_var = None;
269 let mut autoderef = self.autoderef(span, a);
270 let mut found = None;
272 for (referent_ty, autoderefs) in autoderef.by_ref() {
274 // Don't let this pass, otherwise it would cause
275 // &T to autoref to &&T.
279 // At this point, we have deref'd `a` to `referent_ty`. So
280 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
281 // In the autoderef loop for `&'a mut Vec<T>`, we would get
284 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
285 // - `Vec<T>` -- 1 deref
286 // - `[T]` -- 2 deref
288 // At each point after the first callback, we want to
289 // check to see whether this would match out target type
290 // (`&'b mut [T]`) if we autoref'd it. We can't just
291 // compare the referent types, though, because we still
292 // have to consider the mutability. E.g., in the case
293 // we've been considering, we have an `&mut` reference, so
294 // the `T` in `[T]` needs to be unified with equality.
296 // Therefore, we construct reference types reflecting what
297 // the types will be after we do the final auto-ref and
298 // compare those. Note that this means we use the target
299 // mutability [1], since it may be that we are coercing
300 // from `&mut T` to `&U`.
302 // One fine point concerns the region that we use. We
303 // choose the region such that the region of the final
304 // type that results from `unify` will be the region we
305 // want for the autoref:
307 // - if in sub mode, that means we want to use `'b` (the
308 // region from the target reference) for both
309 // pointers [2]. This is because sub mode (somewhat
310 // arbitrarily) returns the subtype region. In the case
311 // where we are coercing to a target type, we know we
312 // want to use that target type region (`'b`) because --
313 // for the program to type-check -- it must be the
314 // smaller of the two.
315 // - One fine point. It may be surprising that we can
316 // use `'b` without relating `'a` and `'b`. The reason
317 // that this is ok is that what we produce is
318 // effectively a `&'b *x` expression (if you could
319 // annotate the region of a borrow), and regionck has
320 // code that adds edges from the region of a borrow
321 // (`'b`, here) into the regions in the borrowed
322 // expression (`*x`, here). (Search for "link".)
323 // - if in lub mode, things can get fairly complicated. The
324 // easiest thing is just to make a fresh
325 // region variable [4], which effectively means we defer
326 // the decision to region inference (and regionck, which will add
327 // some more edges to this variable). However, this can wind up
328 // creating a crippling number of variables in some cases --
329 // e.g., #32278 -- so we optimize one particular case [3].
330 // Let me try to explain with some examples:
331 // - The "running example" above represents the simple case,
332 // where we have one `&` reference at the outer level and
333 // ownership all the rest of the way down. In this case,
334 // we want `LUB('a, 'b)` as the resulting region.
335 // - However, if there are nested borrows, that region is
336 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
337 // `&'b T`. In this case, `'a` is actually irrelevant.
338 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
339 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
340 // (The errors actually show up in borrowck, typically, because
341 // this extra edge causes the region `'a` to be inferred to something
342 // too big, which then results in borrowck errors.)
343 // - We could track the innermost shared reference, but there is already
344 // code in regionck that has the job of creating links between
345 // the region of a borrow and the regions in the thing being
346 // borrowed (here, `'a` and `'x`), and it knows how to handle
347 // all the various cases. So instead we just make a region variable
348 // and let regionck figure it out.
349 let r = if !self.use_lub {
351 } else if autoderefs == 1 {
354 if r_borrow_var.is_none() {
355 // create var lazily, at most once
356 let coercion = Coercion(span);
357 let r = self.next_region_var(coercion);
358 r_borrow_var = Some(r); // [4] above
360 r_borrow_var.unwrap()
362 let derefd_ty_a = self.tcx.mk_ref(
366 mutbl: mutbl_b, // [1] above
369 match self.unify(derefd_ty_a, b) {
375 if first_error.is_none() {
376 first_error = Some(err);
382 // Extract type or return an error. We return the first error
383 // we got, which should be from relating the "base" type
384 // (e.g., in example above, the failure from relating `Vec<T>`
385 // to the target type), since that should be the least
387 let InferOk { value: ty, mut obligations } = match found {
390 let err = first_error.expect("coerce_borrowed_pointer had no error");
391 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
396 if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 {
397 // As a special case, if we would produce `&'a *x`, that's
398 // a total no-op. We end up with the type `&'a T` just as
399 // we started with. In that case, just skip it
400 // altogether. This is just an optimization.
402 // Note that for `&mut`, we DO want to reborrow --
403 // otherwise, this would be a move, which might be an
404 // error. For example `foo(self.x)` where `self` and
405 // `self.x` both have `&mut `type would be a move of
406 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
407 // which is a borrow.
408 assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U
409 return success(vec![], ty, obligations);
412 let InferOk { value: mut adjustments, obligations: o } =
413 self.adjust_steps_as_infer_ok(&autoderef);
414 obligations.extend(o);
415 obligations.extend(autoderef.into_obligations());
417 // Now apply the autoref. We have to extract the region out of
418 // the final ref type we got.
419 let r_borrow = match ty.kind() {
420 ty::Ref(r_borrow, _, _) => r_borrow,
421 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
423 let mutbl = match mutbl_b {
424 hir::Mutability::Not => AutoBorrowMutability::Not,
425 hir::Mutability::Mut => {
426 AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase }
429 adjustments.push(Adjustment {
430 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
434 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
436 success(adjustments, ty, obligations)
439 // &[T; n] or &mut [T; n] -> &[T]
440 // or &mut [T; n] -> &mut [T]
441 // or &Concrete -> &Trait, etc.
442 fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> {
443 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
445 source = self.shallow_resolve(source);
446 target = self.shallow_resolve(target);
447 debug!("coerce_unsized: resolved source={:?} target={:?}", source, target);
449 // These 'if' statements require some explanation.
450 // The `CoerceUnsized` trait is special - it is only
451 // possible to write `impl CoerceUnsized<B> for A` where
452 // A and B have 'matching' fields. This rules out the following
453 // two types of blanket impls:
455 // `impl<T> CoerceUnsized<T> for SomeType`
456 // `impl<T> CoerceUnsized<SomeType> for T`
458 // Both of these trigger a special `CoerceUnsized`-related error (E0376)
460 // We can take advantage of this fact to avoid performing unnecessary work.
461 // If either `source` or `target` is a type variable, then any applicable impl
462 // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
463 // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
466 // However, these are exactly the kinds of impls which are forbidden by
467 // the compiler! Therefore, we can be sure that coercion will always fail
468 // when either the source or target type is a type variable. This allows us
469 // to skip performing any trait selection, and immediately bail out.
470 if source.is_ty_var() {
471 debug!("coerce_unsized: source is a TyVar, bailing out");
472 return Err(TypeError::Mismatch);
474 if target.is_ty_var() {
475 debug!("coerce_unsized: target is a TyVar, bailing out");
476 return Err(TypeError::Mismatch);
480 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
481 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
484 debug!("missing Unsize or CoerceUnsized traits");
485 return Err(TypeError::Mismatch);
488 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
489 // a DST unless we have to. This currently comes out in the wash since
490 // we can't unify [T] with U. But to properly support DST, we need to allow
491 // that, at which point we will need extra checks on the target here.
493 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
494 let reborrow = match (source.kind(), target.kind()) {
495 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
496 coerce_mutbls(mutbl_a, mutbl_b)?;
498 let coercion = Coercion(self.cause.span);
499 let r_borrow = self.next_region_var(coercion);
500 let mutbl = match mutbl_b {
501 hir::Mutability::Not => AutoBorrowMutability::Not,
502 hir::Mutability::Mut => AutoBorrowMutability::Mut {
503 // We don't allow two-phase borrows here, at least for initial
504 // implementation. If it happens that this coercion is a function argument,
505 // the reborrow in coerce_borrowed_ptr will pick it up.
506 allow_two_phase_borrow: AllowTwoPhase::No,
510 Adjustment { kind: Adjust::Deref(None), target: ty_a },
512 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
515 .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }),
519 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
520 coerce_mutbls(mt_a, mt_b)?;
523 Adjustment { kind: Adjust::Deref(None), target: ty_a },
525 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
526 target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
532 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
534 // Setup either a subtyping or a LUB relationship between
535 // the `CoerceUnsized` target type and the expected type.
536 // We only have the latter, so we use an inference variable
537 // for the former and let type inference do the rest.
538 let origin = TypeVariableOrigin {
539 kind: TypeVariableOriginKind::MiscVariable,
540 span: self.cause.span,
542 let coerce_target = self.next_ty_var(origin);
543 let mut coercion = self.unify_and(coerce_target, target, |target| {
544 let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target };
546 None => vec![unsize],
547 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
551 let mut selcx = traits::SelectionContext::new(self);
553 // Create an obligation for `Source: CoerceUnsized<Target>`.
554 let cause = ObligationCause::new(
557 ObligationCauseCode::Coercion { source, target },
560 // Use a FIFO queue for this custom fulfillment procedure.
562 // A Vec (or SmallVec) is not a natural choice for a queue. However,
563 // this code path is hot, and this queue usually has a max length of 1
564 // and almost never more than 3. By using a SmallVec we avoid an
565 // allocation, at the (very small) cost of (occasionally) having to
566 // shift subsequent elements down when removing the front element.
567 let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def(
574 &[coerce_target.into()]
577 let mut has_unsized_tuple_coercion = false;
579 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
580 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
581 // inference might unify those two inner type variables later.
582 let traits = [coerce_unsized_did, unsize_did];
583 while !queue.is_empty() {
584 let obligation = queue.remove(0);
585 debug!("coerce_unsized resolve step: {:?}", obligation);
586 let bound_predicate = obligation.predicate.kind();
587 let trait_pred = match bound_predicate.skip_binder() {
588 ty::PredicateKind::Trait(trait_pred, _)
589 if traits.contains(&trait_pred.def_id()) =>
591 if unsize_did == trait_pred.def_id() {
592 let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
593 if let ty::Tuple(..) = unsize_ty.kind() {
594 debug!("coerce_unsized: found unsized tuple coercion");
595 has_unsized_tuple_coercion = true;
598 bound_predicate.rebind(trait_pred)
601 coercion.obligations.push(obligation);
605 match selcx.select(&obligation.with(trait_pred)) {
606 // Uncertain or unimplemented.
608 if trait_pred.def_id() == unsize_did {
609 let trait_pred = self.resolve_vars_if_possible(trait_pred);
610 let self_ty = trait_pred.skip_binder().self_ty();
611 let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty();
612 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
613 match (&self_ty.kind(), &unsize_ty.kind()) {
614 (ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
615 if self.type_var_is_sized(*v) =>
617 debug!("coerce_unsized: have sized infer {:?}", v);
618 coercion.obligations.push(obligation);
619 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
623 // Some other case for `$0: Unsize<Something>`. Note that we
624 // hit this case even if `Something` is a sized type, so just
625 // don't do the coercion.
626 debug!("coerce_unsized: ambiguous unsize");
627 return Err(TypeError::Mismatch);
631 debug!("coerce_unsized: early return - ambiguous");
632 return Err(TypeError::Mismatch);
635 Err(traits::Unimplemented) => {
636 debug!("coerce_unsized: early return - can't prove obligation");
637 return Err(TypeError::Mismatch);
640 // Object safety violations or miscellaneous.
642 self.report_selection_error(&obligation, &err, false, false);
643 // Treat this like an obligation and follow through
644 // with the unsizing - the lack of a coercion should
645 // be silent, as it causes a type mismatch later.
648 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
652 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
654 &self.tcx.sess.parse_sess,
655 sym::unsized_tuple_coercion,
657 "unsized tuple coercion is not stable enough for use and is subject to change",
665 fn coerce_from_safe_fn<F, G>(
668 fn_ty_a: ty::PolyFnSig<'tcx>,
672 ) -> CoerceResult<'tcx>
674 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
675 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
677 if let ty::FnPtr(fn_ty_b) = b.kind() {
678 if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
679 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
681 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
682 return self.unify_and(unsafe_a, b, to_unsafe);
685 self.unify_and(a, b, normal)
688 fn coerce_from_fn_pointer(
691 fn_ty_a: ty::PolyFnSig<'tcx>,
693 ) -> CoerceResult<'tcx> {
694 //! Attempts to coerce from the type of a Rust function item
695 //! into a closure or a `proc`.
698 let b = self.shallow_resolve(b);
699 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
701 self.coerce_from_safe_fn(
705 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
710 fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
711 //! Attempts to coerce from the type of a Rust function item
712 //! into a closure or a `proc`.
714 let b = self.shallow_resolve(b);
715 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
718 ty::FnPtr(b_sig) => {
719 let a_sig = a.fn_sig(self.tcx);
720 // Intrinsics are not coercible to function pointers
721 if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic {
722 return Err(TypeError::IntrinsicCast);
725 // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
726 if let ty::FnDef(def_id, _) = *a.kind() {
727 if b_sig.unsafety() == hir::Unsafety::Normal
728 && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
730 return Err(TypeError::TargetFeatureCast(def_id));
734 let InferOk { value: a_sig, mut obligations } =
735 self.normalize_associated_types_in_as_infer_ok(self.cause.span, a_sig);
737 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
738 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
745 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
746 target: a_fn_pointer,
749 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
754 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
757 obligations.extend(o2);
758 Ok(InferOk { value, obligations })
760 _ => self.unify_and(a, b, identity),
764 fn coerce_closure_to_fn(
767 closure_def_id_a: DefId,
768 substs_a: SubstsRef<'tcx>,
770 ) -> CoerceResult<'tcx> {
771 //! Attempts to coerce from the type of a non-capturing closure
772 //! into a function pointer.
775 let b = self.shallow_resolve(b);
778 // At this point we haven't done capture analysis, which means
779 // that the ClosureSubsts just contains an inference variable instead
780 // of tuple of captured types.
782 // All we care here is if any variable is being captured and not the exact paths,
783 // so we check `upvars_mentioned` for root variables being captured.
787 .upvars_mentioned(closure_def_id_a.expect_local())
788 .map_or(true, |u| u.is_empty()) =>
790 // We coerce the closure, which has fn type
791 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
793 // `fn(arg0,arg1,...) -> _`
795 // `unsafe fn(arg0,arg1,...) -> _`
796 let closure_sig = substs_a.as_closure().sig();
797 let unsafety = fn_ty.unsafety();
799 self.tcx.mk_fn_ptr(self.tcx.signature_unclosure(closure_sig, unsafety));
800 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
804 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
807 _ => self.unify_and(a, b, identity),
811 fn coerce_unsafe_ptr(
815 mutbl_b: hir::Mutability,
816 ) -> CoerceResult<'tcx> {
817 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
819 let (is_ref, mt_a) = match *a.kind() {
820 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
821 ty::RawPtr(mt) => (false, mt),
822 _ => return self.unify_and(a, b, identity),
824 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
826 // Check that the types which they point at are compatible.
827 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
828 // Although references and unsafe ptrs have the same
829 // representation, we still register an Adjust::DerefRef so that
830 // regionck knows that the region for `a` must be valid here.
832 self.unify_and(a_unsafe, b, |target| {
834 Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
835 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
838 } else if mt_a.mutbl != mutbl_b {
839 self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
841 self.unify_and(a_unsafe, b, identity)
846 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
847 /// Attempt to coerce an expression to a type, and return the
848 /// adjusted type of the expression, if successful.
849 /// Adjustments are only recorded if the coercion succeeded.
850 /// The expressions *must not* have any pre-existing adjustments.
853 expr: &hir::Expr<'_>,
856 allow_two_phase: AllowTwoPhase,
857 ) -> RelateResult<'tcx, Ty<'tcx>> {
858 let source = self.resolve_vars_with_obligations(expr_ty);
859 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
861 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
862 let coerce = Coerce::new(self, cause, allow_two_phase);
863 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
865 let (adjustments, _) = self.register_infer_ok_obligations(ok);
866 self.apply_adjustments(expr, adjustments);
867 Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target })
870 /// Same as `try_coerce()`, but without side-effects.
871 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
872 let source = self.resolve_vars_with_obligations(expr_ty);
873 debug!("coercion::can({:?} -> {:?})", source, target);
875 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
876 // We don't ever need two-phase here since we throw out the result of the coercion
877 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
878 self.probe(|_| coerce.coerce(source, target)).is_ok()
881 /// Given a type and a target type, this function will calculate and return
882 /// how many dereference steps needed to achieve `expr_ty <: target`. If
883 /// it's not possible, return `None`.
884 pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
885 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
886 // We don't ever need two-phase here since we throw out the result of the coercion
887 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
889 .autoderef(rustc_span::DUMMY_SP, expr_ty)
890 .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
893 /// Given some expressions, their known unified type and another expression,
894 /// tries to unify the types, potentially inserting coercions on any of the
895 /// provided expressions and returns their LUB (aka "common supertype").
897 /// This is really an internal helper. From outside the coercion
898 /// module, you should instantiate a `CoerceMany` instance.
899 fn try_find_coercion_lub<E>(
901 cause: &ObligationCause<'tcx>,
906 ) -> RelateResult<'tcx, Ty<'tcx>>
910 let prev_ty = self.resolve_vars_with_obligations(prev_ty);
911 let new_ty = self.resolve_vars_with_obligations(new_ty);
913 "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
919 // Special-case that coercion alone cannot handle:
920 // Function items or non-capturing closures of differing IDs or InternalSubsts.
921 let (a_sig, b_sig) = {
922 let is_capturing_closure = |ty| {
923 if let &ty::Closure(closure_def_id, _substs) = ty {
924 self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
929 if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) {
932 match (prev_ty.kind(), new_ty.kind()) {
933 (ty::FnDef(..), ty::FnDef(..)) => {
934 // Don't reify if the function types have a LUB, i.e., they
935 // are the same function and their parameters have a LUB.
937 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
939 // We have a LUB of prev_ty and new_ty, just return it.
940 Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
942 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
946 (ty::Closure(_, substs), ty::FnDef(..)) => {
947 let b_sig = new_ty.fn_sig(self.tcx);
950 .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
951 (Some(a_sig), Some(b_sig))
953 (ty::FnDef(..), ty::Closure(_, substs)) => {
954 let a_sig = prev_ty.fn_sig(self.tcx);
957 .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
958 (Some(a_sig), Some(b_sig))
960 (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => (
961 Some(self.tcx.signature_unclosure(
962 substs_a.as_closure().sig(),
963 hir::Unsafety::Normal,
965 Some(self.tcx.signature_unclosure(
966 substs_b.as_closure().sig(),
967 hir::Unsafety::Normal,
974 if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
975 // The signature must match.
976 let a_sig = self.normalize_associated_types_in(new.span, a_sig);
977 let b_sig = self.normalize_associated_types_in(new.span, b_sig);
979 .at(cause, self.param_env)
980 .trace(prev_ty, new_ty)
982 .map(|ok| self.register_infer_ok_obligations(ok))?;
984 // Reify both sides and return the reified fn pointer type.
985 let fn_ptr = self.tcx.mk_fn_ptr(sig);
986 let prev_adjustment = match prev_ty.kind() {
987 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.unsafety())),
988 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
991 let next_adjustment = match new_ty.kind() {
992 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.unsafety())),
993 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
996 for expr in exprs.iter().map(|e| e.as_coercion_site()) {
997 self.apply_adjustments(
999 vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1002 self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1006 // Configure a Coerce instance to compute the LUB.
1007 // We don't allow two-phase borrows on any autorefs this creates since we
1008 // probably aren't processing function arguments here and even if we were,
1009 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1011 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
1012 coerce.use_lub = true;
1014 // First try to coerce the new expression to the type of the previous ones,
1015 // but only if the new expression has no coercion already applied to it.
1016 let mut first_error = None;
1017 if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1018 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1021 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1022 self.apply_adjustments(new, adjustments);
1024 "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}",
1029 Err(e) => first_error = Some(e),
1033 // Then try to coerce the previous expressions to the type of the new one.
1034 // This requires ensuring there are no coercions applied to *any* of the
1035 // previous expressions, other than noop reborrows (ignoring lifetimes).
1037 let expr = expr.as_coercion_site();
1038 let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
1039 &[Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }] =>
1041 match *self.node_ty(expr.hir_id).kind() {
1042 ty::Ref(_, _, mt_orig) => {
1043 let mutbl_adj: hir::Mutability = mutbl_adj.into();
1044 // Reborrow that we can safely ignore, because
1045 // the next adjustment can only be a Deref
1046 // which will be merged into it.
1047 mutbl_adj == mt_orig
1052 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1058 "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1063 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1064 .map(|ok| self.register_infer_ok_obligations(ok));
1068 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1070 // Avoid giving strange errors on failed attempts.
1071 if let Some(e) = first_error {
1074 self.commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1075 .map(|ok| self.register_infer_ok_obligations(ok))
1080 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?}",
1083 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1085 let expr = expr.as_coercion_site();
1086 self.apply_adjustments(expr, adjustments.clone());
1094 /// CoerceMany encapsulates the pattern you should use when you have
1095 /// many expressions that are all getting coerced to a common
1096 /// type. This arises, for example, when you have a match (the result
1097 /// of each arm is coerced to a common type). It also arises in less
1098 /// obvious places, such as when you have many `break foo` expressions
1099 /// that target the same loop, or the various `return` expressions in
1102 /// The basic protocol is as follows:
1104 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1105 /// This will also serve as the "starting LUB". The expectation is
1106 /// that this type is something which all of the expressions *must*
1107 /// be coercible to. Use a fresh type variable if needed.
1108 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1109 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1110 /// unit. This happens for example if you have a `break` with no expression,
1111 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1112 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1113 /// from you so that you don't have to worry your pretty head about it.
1114 /// But if an error is reported, the final type will be `err`.
1115 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1116 /// previously coerced expressions.
1117 /// - When all done, invoke `complete()`. This will return the LUB of
1118 /// all your expressions.
1119 /// - WARNING: I don't believe this final type is guaranteed to be
1120 /// related to your initial `expected_ty` in any particular way,
1121 /// although it will typically be a subtype, so you should check it.
1122 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1123 /// previously coerced expressions.
1128 /// let mut coerce = CoerceMany::new(expected_ty);
1129 /// for expr in exprs {
1130 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1131 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1133 /// let final_ty = coerce.complete(fcx);
1135 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1136 expected_ty: Ty<'tcx>,
1137 final_ty: Option<Ty<'tcx>>,
1138 expressions: Expressions<'tcx, 'exprs, E>,
1142 /// The type of a `CoerceMany` that is storing up the expressions into
1143 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1144 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1146 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1147 Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1148 UpFront(&'exprs [E]),
1151 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1152 /// The usual case; collect the set of expressions dynamically.
1153 /// If the full set of coercion sites is known before hand,
1154 /// consider `with_coercion_sites()` instead to avoid allocation.
1155 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1156 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1159 /// As an optimization, you can create a `CoerceMany` with a
1160 /// pre-existing slice of expressions. In this case, you are
1161 /// expected to pass each element in the slice to `coerce(...)` in
1162 /// order. This is used with arrays in particular to avoid
1163 /// needlessly cloning the slice.
1164 pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1165 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1168 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1169 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1172 /// Returns the "expected type" with which this coercion was
1173 /// constructed. This represents the "downward propagated" type
1174 /// that was given to us at the start of typing whatever construct
1175 /// we are typing (e.g., the match expression).
1177 /// Typically, this is used as the expected type when
1178 /// type-checking each of the alternative expressions whose types
1179 /// we are trying to merge.
1180 pub fn expected_ty(&self) -> Ty<'tcx> {
1184 /// Returns the current "merged type", representing our best-guess
1185 /// at the LUB of the expressions we've seen so far (if any). This
1186 /// isn't *final* until you call `self.final()`, which will return
1187 /// the merged type.
1188 pub fn merged_ty(&self) -> Ty<'tcx> {
1189 self.final_ty.unwrap_or(self.expected_ty)
1192 /// Indicates that the value generated by `expression`, which is
1193 /// of type `expression_ty`, is one of the possibilities that we
1194 /// could coerce from. This will record `expression`, and later
1195 /// calls to `coerce` may come back and add adjustments and things
1199 fcx: &FnCtxt<'a, 'tcx>,
1200 cause: &ObligationCause<'tcx>,
1201 expression: &'tcx hir::Expr<'tcx>,
1202 expression_ty: Ty<'tcx>,
1204 self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1207 /// Indicates that one of the inputs is a "forced unit". This
1208 /// occurs in a case like `if foo { ... };`, where the missing else
1209 /// generates a "forced unit". Another example is a `loop { break;
1210 /// }`, where the `break` has no argument expression. We treat
1211 /// these cases slightly differently for error-reporting
1212 /// purposes. Note that these tend to correspond to cases where
1213 /// the `()` expression is implicit in the source, and hence we do
1214 /// not take an expression argument.
1216 /// The `augment_error` gives you a chance to extend the error
1217 /// message, in case any results (e.g., we use this to suggest
1218 /// removing a `;`).
1219 pub fn coerce_forced_unit<'a>(
1221 fcx: &FnCtxt<'a, 'tcx>,
1222 cause: &ObligationCause<'tcx>,
1223 augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1224 label_unit_as_expected: bool,
1231 Some(augment_error),
1232 label_unit_as_expected,
1236 /// The inner coercion "engine". If `expression` is `None`, this
1237 /// is a forced-unit case, and hence `expression_ty` must be
1239 fn coerce_inner<'a>(
1241 fcx: &FnCtxt<'a, 'tcx>,
1242 cause: &ObligationCause<'tcx>,
1243 expression: Option<&'tcx hir::Expr<'tcx>>,
1244 mut expression_ty: Ty<'tcx>,
1245 augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1246 label_expression_as_expected: bool,
1248 // Incorporate whatever type inference information we have
1249 // until now; in principle we might also want to process
1250 // pending obligations, but doing so should only improve
1251 // compatibility (hopefully that is true) by helping us
1252 // uncover never types better.
1253 if expression_ty.is_ty_var() {
1254 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1257 // If we see any error types, just propagate that error
1259 if expression_ty.references_error() || self.merged_ty().references_error() {
1260 self.final_ty = Some(fcx.tcx.ty_error());
1264 // Handle the actual type unification etc.
1265 let result = if let Some(expression) = expression {
1266 if self.pushed == 0 {
1267 // Special-case the first expression we are coercing.
1268 // To be honest, I'm not entirely sure why we do this.
1269 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1270 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1272 match self.expressions {
1273 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1280 Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1282 &coercion_sites[0..self.pushed],
1290 // this is a hack for cases where we default to `()` because
1291 // the expression etc has been omitted from the source. An
1292 // example is an `if let` without an else:
1294 // if let Some(x) = ... { }
1296 // we wind up with a second match arm that is like `_ =>
1297 // ()`. That is the case we are considering here. We take
1298 // a different path to get the right "expected, found"
1299 // message and so forth (and because we know that
1300 // `expression_ty` will be unit).
1302 // Another example is `break` with no argument expression.
1303 assert!(expression_ty.is_unit(), "if let hack without unit type");
1304 fcx.at(cause, fcx.param_env)
1305 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1307 fcx.register_infer_ok_obligations(infer_ok);
1314 self.final_ty = Some(v);
1315 if let Some(e) = expression {
1316 match self.expressions {
1317 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1318 Expressions::UpFront(coercion_sites) => {
1319 // if the user gave us an array to validate, check that we got
1320 // the next expression in the list, as expected
1322 coercion_sites[self.pushed].as_coercion_site().hir_id,
1330 Err(coercion_error) => {
1331 let (expected, found) = if label_expression_as_expected {
1332 // In the case where this is a "forced unit", like
1333 // `break`, we want to call the `()` "expected"
1334 // since it is implied by the syntax.
1335 // (Note: not all force-units work this way.)"
1336 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1338 // Otherwise, the "expected" type for error
1339 // reporting is the current unification type,
1340 // which is basically the LUB of the expressions
1341 // we've seen so far (combined with the expected
1343 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1347 let mut unsized_return = false;
1349 ObligationCauseCode::ReturnNoExpression => {
1350 err = struct_span_err!(
1354 "`return;` in a function whose return type is not `()`"
1356 err.span_label(cause.span, "return type is not `()`");
1358 ObligationCauseCode::BlockTailExpression(blk_id) => {
1359 let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1360 err = self.report_return_mismatched_types(
1367 expression.map(|expr| (expr, blk_id)),
1369 if !fcx.tcx.features().unsized_locals {
1370 unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1373 ObligationCauseCode::ReturnValue(id) => {
1374 err = self.report_return_mismatched_types(
1383 if !fcx.tcx.features().unsized_locals {
1384 let id = fcx.tcx.hir().get_parent_node(id);
1385 unsized_return = self.is_return_ty_unsized(fcx, id);
1389 err = fcx.report_mismatched_types(cause, expected, found, coercion_error);
1393 if let Some(augment_error) = augment_error {
1394 augment_error(&mut err);
1397 if let Some(expr) = expression {
1398 fcx.emit_coerce_suggestions(&mut err, expr, found, expected, None);
1401 // Error possibly reported in `check_assign` so avoid emitting error again.
1402 let assign_to_bool = expression
1403 // #67273: Use initial expected type as opposed to `expected`.
1404 // Otherwise we end up using prior coercions in e.g. a `match` expression:
1407 // 0 => true, // Because of this...
1408 // 1 => i = 1, // ...`expected == bool` now, but not when checking `i = 1`.
1412 .filter(|e| fcx.is_assign_to_bool(e, self.expected_ty()))
1415 err.emit_unless(assign_to_bool || unsized_return);
1417 self.final_ty = Some(fcx.tcx.ty_error());
1422 fn report_return_mismatched_types<'a>(
1424 cause: &ObligationCause<'tcx>,
1427 ty_err: TypeError<'tcx>,
1428 fcx: &FnCtxt<'a, 'tcx>,
1430 expression: Option<(&'tcx hir::Expr<'tcx>, hir::HirId)>,
1431 ) -> DiagnosticBuilder<'a> {
1432 let mut err = fcx.report_mismatched_types(cause, expected, found, ty_err);
1434 let mut pointing_at_return_type = false;
1435 let mut fn_output = None;
1437 // Verify that this is a tail expression of a function, otherwise the
1438 // label pointing out the cause for the type coercion will be wrong
1439 // as prior return coercions would not be relevant (#57664).
1440 let parent_id = fcx.tcx.hir().get_parent_node(id);
1441 let fn_decl = if let Some((expr, blk_id)) = expression {
1442 pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1443 &mut err, expr, expected, found, cause.span, blk_id,
1445 let parent = fcx.tcx.hir().get(parent_id);
1446 if let (Some(cond_expr), true, false) = (
1447 fcx.tcx.hir().get_if_cause(expr.hir_id),
1449 pointing_at_return_type,
1451 if cond_expr.span.desugaring_kind().is_none() {
1452 err.span_label(cond_expr.span, "expected this to be `()`");
1453 if expr.can_have_side_effects() {
1454 fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1458 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1460 fcx.get_fn_decl(parent_id)
1463 if let Some((fn_decl, can_suggest)) = fn_decl {
1464 if expression.is_none() {
1465 pointing_at_return_type |= fcx.suggest_missing_return_type(
1473 if !pointing_at_return_type {
1474 fn_output = Some(&fn_decl.output); // `impl Trait` return type
1478 let parent_id = fcx.tcx.hir().get_parent_item(id);
1479 let parent_item = fcx.tcx.hir().get(parent_id);
1481 if let (Some((expr, _)), Some((fn_decl, _, _))) =
1482 (expression, fcx.get_node_fn_decl(parent_item))
1484 fcx.suggest_missing_return_expr(&mut err, expr, fn_decl, expected, found);
1487 if let (Some(sp), Some(fn_output)) = (fcx.ret_coercion_span.get(), fn_output) {
1488 self.add_impl_trait_explanation(&mut err, cause, fcx, expected, sp, fn_output);
1491 if let Some(sp) = fcx.ret_coercion_span.get() {
1492 // If the closure has an explicit return type annotation,
1493 // then a type error may occur at the first return expression we
1494 // see in the closure (if it conflicts with the declared
1495 // return type). Skip adding a note in this case, since it
1496 // would be incorrect.
1497 if !err.span.primary_spans().iter().any(|&span| span == sp) {
1498 let hir = fcx.tcx.hir();
1499 let body_owner = hir.body_owned_by(hir.enclosing_body_owner(fcx.body_id));
1500 if fcx.tcx.is_closure(hir.body_owner_def_id(body_owner).to_def_id()) {
1504 "return type inferred to be `{}` here",
1505 fcx.resolve_vars_if_possible(expected)
1515 fn add_impl_trait_explanation<'a>(
1517 err: &mut DiagnosticBuilder<'a>,
1518 cause: &ObligationCause<'tcx>,
1519 fcx: &FnCtxt<'a, 'tcx>,
1522 fn_output: &hir::FnRetTy<'_>,
1524 let return_sp = fn_output.span();
1525 err.span_label(return_sp, "expected because this return type...");
1528 format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1530 let impl_trait_msg = "for information on `impl Trait`, see \
1531 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1532 #returning-types-that-implement-traits>";
1533 let trait_obj_msg = "for information on trait objects, see \
1534 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1535 #using-trait-objects-that-allow-for-values-of-different-types>";
1536 err.note("to return `impl Trait`, all returned values must be of the same type");
1537 err.note(impl_trait_msg);
1542 .span_to_snippet(return_sp)
1543 .unwrap_or_else(|_| "dyn Trait".to_string());
1544 let mut snippet_iter = snippet.split_whitespace();
1545 let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1546 // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1547 let mut is_object_safe = false;
1548 if let hir::FnRetTy::Return(ty) = fn_output {
1549 // Get the return type.
1550 if let hir::TyKind::OpaqueDef(..) = ty.kind {
1551 let ty = AstConv::ast_ty_to_ty(fcx, ty);
1552 // Get the `impl Trait`'s `DefId`.
1553 if let ty::Opaque(def_id, _) = ty.kind() {
1554 let hir_id = fcx.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1555 // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1556 // get the `Trait`'s `DefId`.
1557 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1558 fcx.tcx.hir().expect_item(hir_id).kind
1560 // Are of this `impl Trait`'s traits object safe?
1561 is_object_safe = bounds.iter().all(|bound| {
1564 .and_then(|t| t.trait_def_id())
1565 .map_or(false, |def_id| {
1566 fcx.tcx.object_safety_violations(def_id).is_empty()
1575 err.multipart_suggestion(
1576 "you could change the return type to be a boxed trait object",
1578 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
1579 (return_sp.shrink_to_hi(), ">".to_string()),
1581 Applicability::MachineApplicable,
1583 let sugg = vec![sp, cause.span]
1587 (sp.shrink_to_lo(), "Box::new(".to_string()),
1588 (sp.shrink_to_hi(), ")".to_string()),
1592 .collect::<Vec<_>>();
1593 err.multipart_suggestion(
1594 "if you change the return type to expect trait objects, box the returned \
1597 Applicability::MaybeIncorrect,
1601 "if the trait `{}` were object safe, you could return a boxed trait object",
1605 err.note(trait_obj_msg);
1607 err.help("you could instead create a new `enum` with a variant for each returned type");
1610 fn is_return_ty_unsized(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
1611 if let Some((fn_decl, _)) = fcx.get_fn_decl(blk_id) {
1612 if let hir::FnRetTy::Return(ty) = fn_decl.output {
1613 let ty = AstConv::ast_ty_to_ty(fcx, ty);
1614 if let ty::Dynamic(..) = ty.kind() {
1622 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1623 if let Some(final_ty) = self.final_ty {
1626 // If we only had inputs that were of type `!` (or no
1627 // inputs at all), then the final type is `!`.
1628 assert_eq!(self.pushed, 0);
1634 /// Something that can be converted into an expression to which we can
1635 /// apply a coercion.
1636 pub trait AsCoercionSite {
1637 fn as_coercion_site(&self) -> &hir::Expr<'_>;
1640 impl AsCoercionSite for hir::Expr<'_> {
1641 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1646 impl<'a, T> AsCoercionSite for &'a T
1650 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1651 (**self).as_coercion_site()
1655 impl AsCoercionSite for ! {
1656 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1661 impl AsCoercionSite for hir::Arm<'_> {
1662 fn as_coercion_site(&self) -> &hir::Expr<'_> {