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, DiagnosticBuilder};
42 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
43 use rustc_infer::infer::{Coercion, InferOk, InferResult};
44 use rustc_middle::ty::adjustment::{
45 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast,
47 use rustc_middle::ty::error::TypeError;
48 use rustc_middle::ty::fold::TypeFoldable;
49 use rustc_middle::ty::relate::RelateResult;
50 use rustc_middle::ty::subst::SubstsRef;
51 use rustc_middle::ty::{self, Ty, TypeAndMut};
52 use rustc_session::parse::feature_err;
53 use rustc_span::symbol::sym;
54 use rustc_span::{self, Span};
55 use rustc_target::spec::abi::Abi;
56 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
57 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode};
59 use smallvec::{smallvec, SmallVec};
62 struct Coerce<'a, 'tcx> {
63 fcx: &'a FnCtxt<'a, 'tcx>,
64 cause: ObligationCause<'tcx>,
66 /// Determines whether or not allow_two_phase_borrow is set on any
67 /// autoref adjustments we create while coercing. We don't want to
68 /// allow deref coercions to create two-phase borrows, at least initially,
69 /// but we do need two-phase borrows for function argument reborrows.
70 /// See #47489 and #48598
71 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
72 allow_two_phase: AllowTwoPhase,
75 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
76 type Target = FnCtxt<'a, 'tcx>;
77 fn deref(&self) -> &Self::Target {
82 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
84 /// Coercing a mutable reference to an immutable works, while
85 /// coercing `&T` to `&mut T` should be forbidden.
86 fn coerce_mutbls<'tcx>(
87 from_mutbl: hir::Mutability,
88 to_mutbl: hir::Mutability,
89 ) -> RelateResult<'tcx, ()> {
90 match (from_mutbl, to_mutbl) {
91 (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not)
92 | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()),
93 (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability),
97 /// Do not require any adjustments, i.e. coerce `x -> x`.
98 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> {
102 fn simple(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
103 move |target| vec![Adjustment { kind, target }]
106 /// This always returns `Ok(...)`.
108 adj: Vec<Adjustment<'tcx>>,
110 obligations: traits::PredicateObligations<'tcx>,
111 ) -> CoerceResult<'tcx> {
112 Ok(InferOk { value: (adj, target), obligations })
115 impl<'f, 'tcx> Coerce<'f, 'tcx> {
117 fcx: &'f FnCtxt<'f, 'tcx>,
118 cause: ObligationCause<'tcx>,
119 allow_two_phase: AllowTwoPhase,
121 Coerce { fcx, cause, allow_two_phase, use_lub: false }
124 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
125 debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
126 self.commit_if_ok(|_| {
128 self.at(&self.cause, self.fcx.param_env).lub(b, a)
130 self.at(&self.cause, self.fcx.param_env)
132 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
137 /// Unify two types (using sub or lub) and produce a specific coercion.
138 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx>
140 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
143 .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations))
146 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
147 let a = self.shallow_resolve(a);
148 debug!("Coerce.tys({:?} => {:?})", a, b);
150 // Just ignore error types.
151 if a.references_error() || b.references_error() {
152 return success(vec![], self.fcx.tcx.ty_error(), vec![]);
156 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
157 // type variable, we want `?T` to fallback to `!` if not
158 // otherwise constrained. An example where this arises:
160 // let _: Option<?T> = Some({ return; });
162 // here, we would coerce from `!` to `?T`.
163 let b = self.shallow_resolve(b);
164 return if self.shallow_resolve(b).is_ty_var() {
165 // Micro-optimization: no need for this if `b` is
166 // already resolved in some way.
167 let diverging_ty = self.next_diverging_ty_var(TypeVariableOrigin {
168 kind: TypeVariableOriginKind::AdjustmentType,
169 span: self.cause.span,
171 self.unify_and(&b, &diverging_ty, simple(Adjust::NeverToAny))
173 success(simple(Adjust::NeverToAny)(b), b, vec![])
177 // Consider coercing the subtype to a DST
179 // NOTE: this is wrapped in a `commit_if_ok` because it creates
180 // a "spurious" type variable, and we don't want to have that
181 // type variable in memory if the coercion fails.
182 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
185 debug!("coerce: unsize successful");
188 Err(TypeError::ObjectUnsafeCoercion(did)) => {
189 debug!("coerce: unsize not object safe");
190 return Err(TypeError::ObjectUnsafeCoercion(did));
194 debug!("coerce: unsize failed");
196 // Examine the supertype and consider auto-borrowing.
198 // Note: does not attempt to resolve type variables we encounter.
199 // See above for details.
201 ty::RawPtr(mt_b) => {
202 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
204 ty::Ref(r_b, _, mutbl_b) => {
205 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
212 // Function items are coercible to any closure
213 // type; function pointers are not (that would
214 // require double indirection).
215 // Additionally, we permit coercion of function
216 // items to drop the unsafe qualifier.
217 self.coerce_from_fn_item(a, b)
220 // We permit coercion of fn pointers to drop the
222 self.coerce_from_fn_pointer(a, a_f, b)
224 ty::Closure(_, substs_a) => {
225 // Non-capturing closures are coercible to
226 // function pointers or unsafe function pointers.
227 // It cannot convert closures that require unsafe.
228 self.coerce_closure_to_fn(a, substs_a, b)
231 // Otherwise, just use unification rules.
232 self.unify_and(a, b, identity)
237 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
238 /// To match `A` with `B`, autoderef will be performed,
239 /// calling `deref`/`deref_mut` where necessary.
240 fn coerce_borrowed_pointer(
244 r_b: ty::Region<'tcx>,
245 mutbl_b: hir::Mutability,
246 ) -> CoerceResult<'tcx> {
247 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
249 // If we have a parameter of type `&M T_a` and the value
250 // provided is `expr`, we will be adding an implicit borrow,
251 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
252 // to type check, we will construct the type that `&M*expr` would
255 let (r_a, mt_a) = match a.kind {
256 ty::Ref(r_a, ty, mutbl) => {
257 let mt_a = ty::TypeAndMut { ty, mutbl };
258 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
261 _ => return self.unify_and(a, b, identity),
264 let span = self.cause.span;
266 let mut first_error = None;
267 let mut r_borrow_var = None;
268 let mut autoderef = self.autoderef(span, a);
269 let mut found = None;
271 for (referent_ty, autoderefs) in autoderef.by_ref() {
273 // Don't let this pass, otherwise it would cause
274 // &T to autoref to &&T.
278 // At this point, we have deref'd `a` to `referent_ty`. So
279 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
280 // In the autoderef loop for `&'a mut Vec<T>`, we would get
283 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
284 // - `Vec<T>` -- 1 deref
285 // - `[T]` -- 2 deref
287 // At each point after the first callback, we want to
288 // check to see whether this would match out target type
289 // (`&'b mut [T]`) if we autoref'd it. We can't just
290 // compare the referent types, though, because we still
291 // have to consider the mutability. E.g., in the case
292 // we've been considering, we have an `&mut` reference, so
293 // the `T` in `[T]` needs to be unified with equality.
295 // Therefore, we construct reference types reflecting what
296 // the types will be after we do the final auto-ref and
297 // compare those. Note that this means we use the target
298 // mutability [1], since it may be that we are coercing
299 // from `&mut T` to `&U`.
301 // One fine point concerns the region that we use. We
302 // choose the region such that the region of the final
303 // type that results from `unify` will be the region we
304 // want for the autoref:
306 // - if in sub mode, that means we want to use `'b` (the
307 // region from the target reference) for both
308 // pointers [2]. This is because sub mode (somewhat
309 // arbitrarily) returns the subtype region. In the case
310 // where we are coercing to a target type, we know we
311 // want to use that target type region (`'b`) because --
312 // for the program to type-check -- it must be the
313 // smaller of the two.
314 // - One fine point. It may be surprising that we can
315 // use `'b` without relating `'a` and `'b`. The reason
316 // that this is ok is that what we produce is
317 // effectively a `&'b *x` expression (if you could
318 // annotate the region of a borrow), and regionck has
319 // code that adds edges from the region of a borrow
320 // (`'b`, here) into the regions in the borrowed
321 // expression (`*x`, here). (Search for "link".)
322 // - if in lub mode, things can get fairly complicated. The
323 // easiest thing is just to make a fresh
324 // region variable [4], which effectively means we defer
325 // the decision to region inference (and regionck, which will add
326 // some more edges to this variable). However, this can wind up
327 // creating a crippling number of variables in some cases --
328 // e.g., #32278 -- so we optimize one particular case [3].
329 // Let me try to explain with some examples:
330 // - The "running example" above represents the simple case,
331 // where we have one `&` reference at the outer level and
332 // ownership all the rest of the way down. In this case,
333 // we want `LUB('a, 'b)` as the resulting region.
334 // - However, if there are nested borrows, that region is
335 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
336 // `&'b T`. In this case, `'a` is actually irrelevant.
337 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
338 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
339 // (The errors actually show up in borrowck, typically, because
340 // this extra edge causes the region `'a` to be inferred to something
341 // too big, which then results in borrowck errors.)
342 // - We could track the innermost shared reference, but there is already
343 // code in regionck that has the job of creating links between
344 // the region of a borrow and the regions in the thing being
345 // borrowed (here, `'a` and `'x`), and it knows how to handle
346 // all the various cases. So instead we just make a region variable
347 // and let regionck figure it out.
348 let r = if !self.use_lub {
350 } else if autoderefs == 1 {
353 if r_borrow_var.is_none() {
354 // create var lazily, at most once
355 let coercion = Coercion(span);
356 let r = self.next_region_var(coercion);
357 r_borrow_var = Some(r); // [4] above
359 r_borrow_var.unwrap()
361 let derefd_ty_a = self.tcx.mk_ref(
365 mutbl: mutbl_b, // [1] above
368 match self.unify(derefd_ty_a, b) {
374 if first_error.is_none() {
375 first_error = Some(err);
381 // Extract type or return an error. We return the first error
382 // we got, which should be from relating the "base" type
383 // (e.g., in example above, the failure from relating `Vec<T>`
384 // to the target type), since that should be the least
386 let InferOk { value: ty, mut obligations } = match found {
389 let err = first_error.expect("coerce_borrowed_pointer had no error");
390 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
395 if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 {
396 // As a special case, if we would produce `&'a *x`, that's
397 // a total no-op. We end up with the type `&'a T` just as
398 // we started with. In that case, just skip it
399 // altogether. This is just an optimization.
401 // Note that for `&mut`, we DO want to reborrow --
402 // otherwise, this would be a move, which might be an
403 // error. For example `foo(self.x)` where `self` and
404 // `self.x` both have `&mut `type would be a move of
405 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
406 // which is a borrow.
407 assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U
408 return success(vec![], ty, obligations);
411 let InferOk { value: mut adjustments, obligations: o } =
412 self.adjust_steps_as_infer_ok(&autoderef);
413 obligations.extend(o);
414 obligations.extend(autoderef.into_obligations());
416 // Now apply the autoref. We have to extract the region out of
417 // the final ref type we got.
418 let r_borrow = match ty.kind {
419 ty::Ref(r_borrow, _, _) => r_borrow,
420 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
422 let mutbl = match mutbl_b {
423 hir::Mutability::Not => AutoBorrowMutability::Not,
424 hir::Mutability::Mut => {
425 AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase }
428 adjustments.push(Adjustment {
429 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
433 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
435 success(adjustments, ty, obligations)
438 // &[T; n] or &mut [T; n] -> &[T]
439 // or &mut [T; n] -> &mut [T]
440 // or &Concrete -> &Trait, etc.
441 fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> {
442 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
444 source = self.shallow_resolve(source);
445 target = self.shallow_resolve(target);
446 debug!("coerce_unsized: resolved source={:?} target={:?}", source, target);
448 // These 'if' statements require some explanation.
449 // The `CoerceUnsized` trait is special - it is only
450 // possible to write `impl CoerceUnsized<B> for A` where
451 // A and B have 'matching' fields. This rules out the following
452 // two types of blanket impls:
454 // `impl<T> CoerceUnsized<T> for SomeType`
455 // `impl<T> CoerceUnsized<SomeType> for T`
457 // Both of these trigger a special `CoerceUnsized`-related error (E0376)
459 // We can take advantage of this fact to avoid performing unecessary work.
460 // If either `source` or `target` is a type variable, then any applicable impl
461 // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
462 // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
465 // However, these are exactly the kinds of impls which are forbidden by
466 // the compiler! Therefore, we can be sure that coercion will always fail
467 // when either the source or target type is a type variable. This allows us
468 // to skip performing any trait selection, and immediately bail out.
469 if source.is_ty_var() {
470 debug!("coerce_unsized: source is a TyVar, bailing out");
471 return Err(TypeError::Mismatch);
473 if target.is_ty_var() {
474 debug!("coerce_unsized: target is a TyVar, bailing out");
475 return Err(TypeError::Mismatch);
479 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
480 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
483 debug!("missing Unsize or CoerceUnsized traits");
484 return Err(TypeError::Mismatch);
487 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
488 // a DST unless we have to. This currently comes out in the wash since
489 // we can't unify [T] with U. But to properly support DST, we need to allow
490 // that, at which point we will need extra checks on the target here.
492 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
493 let reborrow = match (&source.kind, &target.kind) {
494 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
495 coerce_mutbls(mutbl_a, mutbl_b)?;
497 let coercion = Coercion(self.cause.span);
498 let r_borrow = self.next_region_var(coercion);
499 let mutbl = match mutbl_b {
500 hir::Mutability::Not => AutoBorrowMutability::Not,
501 hir::Mutability::Mut => AutoBorrowMutability::Mut {
502 // We don't allow two-phase borrows here, at least for initial
503 // implementation. If it happens that this coercion is a function argument,
504 // the reborrow in coerce_borrowed_ptr will pick it up.
505 allow_two_phase_borrow: AllowTwoPhase::No,
509 Adjustment { kind: Adjust::Deref(None), target: ty_a },
511 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
514 .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }),
518 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
519 coerce_mutbls(mt_a, mt_b)?;
522 Adjustment { kind: Adjust::Deref(None), target: ty_a },
524 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
525 target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
531 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
533 // Setup either a subtyping or a LUB relationship between
534 // the `CoerceUnsized` target type and the expected type.
535 // We only have the latter, so we use an inference variable
536 // for the former and let type inference do the rest.
537 let origin = TypeVariableOrigin {
538 kind: TypeVariableOriginKind::MiscVariable,
539 span: self.cause.span,
541 let coerce_target = self.next_ty_var(origin);
542 let mut coercion = self.unify_and(coerce_target, target, |target| {
543 let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target };
545 None => vec![unsize],
546 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
550 let mut selcx = traits::SelectionContext::new(self);
552 // Create an obligation for `Source: CoerceUnsized<Target>`.
553 let cause = ObligationCause::new(
556 ObligationCauseCode::Coercion { source, target },
559 // Use a FIFO queue for this custom fulfillment procedure.
561 // A Vec (or SmallVec) is not a natural choice for a queue. However,
562 // this code path is hot, and this queue usually has a max length of 1
563 // and almost never more than 3. By using a SmallVec we avoid an
564 // allocation, at the (very small) cost of (occasionally) having to
565 // shift subsequent elements down when removing the front element.
566 let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def(
573 &[coerce_target.into()]
576 let mut has_unsized_tuple_coercion = false;
578 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
579 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
580 // inference might unify those two inner type variables later.
581 let traits = [coerce_unsized_did, unsize_did];
582 while !queue.is_empty() {
583 let obligation = queue.remove(0);
584 debug!("coerce_unsized resolve step: {:?}", obligation);
585 let trait_pred = match obligation.predicate.ignore_qualifiers().skip_binder().kind() {
586 &ty::PredicateKind::Trait(trait_pred, _)
587 if traits.contains(&trait_pred.def_id()) =>
589 if unsize_did == trait_pred.def_id() {
590 let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
591 if let ty::Tuple(..) = unsize_ty.kind {
592 debug!("coerce_unsized: found unsized tuple coercion");
593 has_unsized_tuple_coercion = true;
596 ty::Binder::bind(trait_pred)
599 coercion.obligations.push(obligation);
603 match selcx.select(&obligation.with(trait_pred)) {
604 // Uncertain or unimplemented.
606 if trait_pred.def_id() == unsize_did {
607 let trait_pred = self.resolve_vars_if_possible(&trait_pred);
608 let self_ty = trait_pred.skip_binder().self_ty();
609 let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty();
610 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
611 match (&self_ty.kind, &unsize_ty.kind) {
612 (ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
613 if self.type_var_is_sized(*v) =>
615 debug!("coerce_unsized: have sized infer {:?}", v);
616 coercion.obligations.push(obligation);
617 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
621 // Some other case for `$0: Unsize<Something>`. Note that we
622 // hit this case even if `Something` is a sized type, so just
623 // don't do the coercion.
624 debug!("coerce_unsized: ambiguous unsize");
625 return Err(TypeError::Mismatch);
629 debug!("coerce_unsized: early return - ambiguous");
630 return Err(TypeError::Mismatch);
633 Err(traits::Unimplemented) => {
634 debug!("coerce_unsized: early return - can't prove obligation");
635 return Err(TypeError::Mismatch);
638 // Object safety violations or miscellaneous.
640 self.report_selection_error(&obligation, &err, false, false);
641 // Treat this like an obligation and follow through
642 // with the unsizing - the lack of a coercion should
643 // be silent, as it causes a type mismatch later.
646 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
650 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
652 &self.tcx.sess.parse_sess,
653 sym::unsized_tuple_coercion,
655 "unsized tuple coercion is not stable enough for use and is subject to change",
663 fn coerce_from_safe_fn<F, G>(
666 fn_ty_a: ty::PolyFnSig<'tcx>,
670 ) -> CoerceResult<'tcx>
672 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
673 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
675 if let ty::FnPtr(fn_ty_b) = b.kind {
676 if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
677 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
679 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
680 return self.unify_and(unsafe_a, b, to_unsafe);
683 self.unify_and(a, b, normal)
686 fn coerce_from_fn_pointer(
689 fn_ty_a: ty::PolyFnSig<'tcx>,
691 ) -> CoerceResult<'tcx> {
692 //! Attempts to coerce from the type of a Rust function item
693 //! into a closure or a `proc`.
696 let b = self.shallow_resolve(b);
697 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
699 self.coerce_from_safe_fn(
703 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
708 fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
709 //! Attempts to coerce from the type of a Rust function item
710 //! into a closure or a `proc`.
712 let b = self.shallow_resolve(b);
713 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
716 ty::FnPtr(b_sig) => {
717 let a_sig = a.fn_sig(self.tcx);
718 // Intrinsics are not coercible to function pointers
719 if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic {
720 return Err(TypeError::IntrinsicCast);
723 // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
724 if let ty::FnDef(def_id, _) = a.kind {
725 if b_sig.unsafety() == hir::Unsafety::Normal
726 && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
728 return Err(TypeError::TargetFeatureCast(def_id));
732 let InferOk { value: a_sig, mut obligations } =
733 self.normalize_associated_types_in_as_infer_ok(self.cause.span, &a_sig);
735 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
736 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
743 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
744 target: a_fn_pointer,
747 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
752 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
755 obligations.extend(o2);
756 Ok(InferOk { value, obligations })
758 _ => self.unify_and(a, b, identity),
762 fn coerce_closure_to_fn(
765 substs_a: SubstsRef<'tcx>,
767 ) -> CoerceResult<'tcx> {
768 //! Attempts to coerce from the type of a non-capturing closure
769 //! into a function pointer.
772 let b = self.shallow_resolve(b);
775 ty::FnPtr(fn_ty) if substs_a.as_closure().upvar_tys().next().is_none() => {
776 // We coerce the closure, which has fn type
777 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
779 // `fn(arg0,arg1,...) -> _`
781 // `unsafe fn(arg0,arg1,...) -> _`
782 let closure_sig = substs_a.as_closure().sig();
783 let unsafety = fn_ty.unsafety();
785 self.tcx.mk_fn_ptr(self.tcx.signature_unclosure(closure_sig, unsafety));
786 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
790 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
793 _ => self.unify_and(a, b, identity),
797 fn coerce_unsafe_ptr(
801 mutbl_b: hir::Mutability,
802 ) -> CoerceResult<'tcx> {
803 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
805 let (is_ref, mt_a) = match a.kind {
806 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
807 ty::RawPtr(mt) => (false, mt),
808 _ => return self.unify_and(a, b, identity),
810 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
812 // Check that the types which they point at are compatible.
813 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
814 // Although references and unsafe ptrs have the same
815 // representation, we still register an Adjust::DerefRef so that
816 // regionck knows that the region for `a` must be valid here.
818 self.unify_and(a_unsafe, b, |target| {
820 Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
821 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
824 } else if mt_a.mutbl != mutbl_b {
825 self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
827 self.unify_and(a_unsafe, b, identity)
832 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
833 /// Attempt to coerce an expression to a type, and return the
834 /// adjusted type of the expression, if successful.
835 /// Adjustments are only recorded if the coercion succeeded.
836 /// The expressions *must not* have any pre-existing adjustments.
839 expr: &hir::Expr<'_>,
842 allow_two_phase: AllowTwoPhase,
843 ) -> RelateResult<'tcx, Ty<'tcx>> {
844 let source = self.resolve_vars_with_obligations(expr_ty);
845 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
847 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
848 let coerce = Coerce::new(self, cause, allow_two_phase);
849 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
851 let (adjustments, _) = self.register_infer_ok_obligations(ok);
852 self.apply_adjustments(expr, adjustments);
853 Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target })
856 /// Same as `try_coerce()`, but without side-effects.
857 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
858 let source = self.resolve_vars_with_obligations(expr_ty);
859 debug!("coercion::can({:?} -> {:?})", source, target);
861 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
862 // We don't ever need two-phase here since we throw out the result of the coercion
863 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
864 self.probe(|_| coerce.coerce(source, target)).is_ok()
867 /// Given a type and a target type, this function will calculate and return
868 /// how many dereference steps needed to achieve `expr_ty <: target`. If
869 /// it's not possible, return `None`.
870 pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
871 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
872 // We don't ever need two-phase here since we throw out the result of the coercion
873 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
875 .autoderef(rustc_span::DUMMY_SP, expr_ty)
876 .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
879 /// Given some expressions, their known unified type and another expression,
880 /// tries to unify the types, potentially inserting coercions on any of the
881 /// provided expressions and returns their LUB (aka "common supertype").
883 /// This is really an internal helper. From outside the coercion
884 /// module, you should instantiate a `CoerceMany` instance.
885 fn try_find_coercion_lub<E>(
887 cause: &ObligationCause<'tcx>,
892 ) -> RelateResult<'tcx, Ty<'tcx>>
896 let prev_ty = self.resolve_vars_with_obligations(prev_ty);
897 let new_ty = self.resolve_vars_with_obligations(new_ty);
899 "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
905 // Special-case that coercion alone cannot handle:
906 // Function items or non-capturing closures of differing IDs or InternalSubsts.
907 let (a_sig, b_sig) = {
908 let is_capturing_closure = |ty| {
909 if let &ty::Closure(_, substs) = ty {
910 substs.as_closure().upvar_tys().next().is_some()
915 if is_capturing_closure(&prev_ty.kind) || is_capturing_closure(&new_ty.kind) {
918 match (&prev_ty.kind, &new_ty.kind) {
919 (&ty::FnDef(..), &ty::FnDef(..)) => {
920 // Don't reify if the function types have a LUB, i.e., they
921 // are the same function and their parameters have a LUB.
923 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
925 // We have a LUB of prev_ty and new_ty, just return it.
926 Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
928 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
932 (&ty::Closure(_, substs), &ty::FnDef(..)) => {
933 let b_sig = new_ty.fn_sig(self.tcx);
936 .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
937 (Some(a_sig), Some(b_sig))
939 (&ty::FnDef(..), &ty::Closure(_, substs)) => {
940 let a_sig = prev_ty.fn_sig(self.tcx);
943 .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
944 (Some(a_sig), Some(b_sig))
946 (&ty::Closure(_, substs_a), &ty::Closure(_, substs_b)) => (
947 Some(self.tcx.signature_unclosure(
948 substs_a.as_closure().sig(),
949 hir::Unsafety::Normal,
951 Some(self.tcx.signature_unclosure(
952 substs_b.as_closure().sig(),
953 hir::Unsafety::Normal,
960 if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
961 // The signature must match.
962 let a_sig = self.normalize_associated_types_in(new.span, &a_sig);
963 let b_sig = self.normalize_associated_types_in(new.span, &b_sig);
965 .at(cause, self.param_env)
966 .trace(prev_ty, new_ty)
968 .map(|ok| self.register_infer_ok_obligations(ok))?;
970 // Reify both sides and return the reified fn pointer type.
971 let fn_ptr = self.tcx.mk_fn_ptr(sig);
972 let prev_adjustment = match prev_ty.kind {
973 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.unsafety())),
974 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
977 let next_adjustment = match new_ty.kind {
978 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.unsafety())),
979 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
982 for expr in exprs.iter().map(|e| e.as_coercion_site()) {
983 self.apply_adjustments(
985 vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
988 self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
992 // Configure a Coerce instance to compute the LUB.
993 // We don't allow two-phase borrows on any autorefs this creates since we
994 // probably aren't processing function arguments here and even if we were,
995 // they're going to get autorefed again anyway and we can apply 2-phase borrows
997 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
998 coerce.use_lub = true;
1000 // First try to coerce the new expression to the type of the previous ones,
1001 // but only if the new expression has no coercion already applied to it.
1002 let mut first_error = None;
1003 if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1004 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1007 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1008 self.apply_adjustments(new, adjustments);
1010 "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}",
1015 Err(e) => first_error = Some(e),
1019 // Then try to coerce the previous expressions to the type of the new one.
1020 // This requires ensuring there are no coercions applied to *any* of the
1021 // previous expressions, other than noop reborrows (ignoring lifetimes).
1023 let expr = expr.as_coercion_site();
1024 let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
1025 &[Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }] =>
1027 match self.node_ty(expr.hir_id).kind {
1028 ty::Ref(_, _, mt_orig) => {
1029 let mutbl_adj: hir::Mutability = mutbl_adj.into();
1030 // Reborrow that we can safely ignore, because
1031 // the next adjustment can only be a Deref
1032 // which will be merged into it.
1033 mutbl_adj == mt_orig
1038 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1044 "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1049 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1050 .map(|ok| self.register_infer_ok_obligations(ok));
1054 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1056 // Avoid giving strange errors on failed attempts.
1057 if let Some(e) = first_error {
1060 self.commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1061 .map(|ok| self.register_infer_ok_obligations(ok))
1066 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?}",
1069 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1071 let expr = expr.as_coercion_site();
1072 self.apply_adjustments(expr, adjustments.clone());
1080 /// CoerceMany encapsulates the pattern you should use when you have
1081 /// many expressions that are all getting coerced to a common
1082 /// type. This arises, for example, when you have a match (the result
1083 /// of each arm is coerced to a common type). It also arises in less
1084 /// obvious places, such as when you have many `break foo` expressions
1085 /// that target the same loop, or the various `return` expressions in
1088 /// The basic protocol is as follows:
1090 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1091 /// This will also serve as the "starting LUB". The expectation is
1092 /// that this type is something which all of the expressions *must*
1093 /// be coercible to. Use a fresh type variable if needed.
1094 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1095 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1096 /// unit. This happens for example if you have a `break` with no expression,
1097 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1098 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1099 /// from you so that you don't have to worry your pretty head about it.
1100 /// But if an error is reported, the final type will be `err`.
1101 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1102 /// previously coerced expressions.
1103 /// - When all done, invoke `complete()`. This will return the LUB of
1104 /// all your expressions.
1105 /// - WARNING: I don't believe this final type is guaranteed to be
1106 /// related to your initial `expected_ty` in any particular way,
1107 /// although it will typically be a subtype, so you should check it.
1108 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1109 /// previously coerced expressions.
1114 /// let mut coerce = CoerceMany::new(expected_ty);
1115 /// for expr in exprs {
1116 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1117 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1119 /// let final_ty = coerce.complete(fcx);
1121 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1122 expected_ty: Ty<'tcx>,
1123 final_ty: Option<Ty<'tcx>>,
1124 expressions: Expressions<'tcx, 'exprs, E>,
1128 /// The type of a `CoerceMany` that is storing up the expressions into
1129 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1130 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1132 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1133 Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1134 UpFront(&'exprs [E]),
1137 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1138 /// The usual case; collect the set of expressions dynamically.
1139 /// If the full set of coercion sites is known before hand,
1140 /// consider `with_coercion_sites()` instead to avoid allocation.
1141 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1142 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1145 /// As an optimization, you can create a `CoerceMany` with a
1146 /// pre-existing slice of expressions. In this case, you are
1147 /// expected to pass each element in the slice to `coerce(...)` in
1148 /// order. This is used with arrays in particular to avoid
1149 /// needlessly cloning the slice.
1150 pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1151 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1154 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1155 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1158 /// Returns the "expected type" with which this coercion was
1159 /// constructed. This represents the "downward propagated" type
1160 /// that was given to us at the start of typing whatever construct
1161 /// we are typing (e.g., the match expression).
1163 /// Typically, this is used as the expected type when
1164 /// type-checking each of the alternative expressions whose types
1165 /// we are trying to merge.
1166 pub fn expected_ty(&self) -> Ty<'tcx> {
1170 /// Returns the current "merged type", representing our best-guess
1171 /// at the LUB of the expressions we've seen so far (if any). This
1172 /// isn't *final* until you call `self.final()`, which will return
1173 /// the merged type.
1174 pub fn merged_ty(&self) -> Ty<'tcx> {
1175 self.final_ty.unwrap_or(self.expected_ty)
1178 /// Indicates that the value generated by `expression`, which is
1179 /// of type `expression_ty`, is one of the possibilities that we
1180 /// could coerce from. This will record `expression`, and later
1181 /// calls to `coerce` may come back and add adjustments and things
1185 fcx: &FnCtxt<'a, 'tcx>,
1186 cause: &ObligationCause<'tcx>,
1187 expression: &'tcx hir::Expr<'tcx>,
1188 expression_ty: Ty<'tcx>,
1190 self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1193 /// Indicates that one of the inputs is a "forced unit". This
1194 /// occurs in a case like `if foo { ... };`, where the missing else
1195 /// generates a "forced unit". Another example is a `loop { break;
1196 /// }`, where the `break` has no argument expression. We treat
1197 /// these cases slightly differently for error-reporting
1198 /// purposes. Note that these tend to correspond to cases where
1199 /// the `()` expression is implicit in the source, and hence we do
1200 /// not take an expression argument.
1202 /// The `augment_error` gives you a chance to extend the error
1203 /// message, in case any results (e.g., we use this to suggest
1204 /// removing a `;`).
1205 pub fn coerce_forced_unit<'a>(
1207 fcx: &FnCtxt<'a, 'tcx>,
1208 cause: &ObligationCause<'tcx>,
1209 augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1210 label_unit_as_expected: bool,
1217 Some(augment_error),
1218 label_unit_as_expected,
1222 /// The inner coercion "engine". If `expression` is `None`, this
1223 /// is a forced-unit case, and hence `expression_ty` must be
1225 fn coerce_inner<'a>(
1227 fcx: &FnCtxt<'a, 'tcx>,
1228 cause: &ObligationCause<'tcx>,
1229 expression: Option<&'tcx hir::Expr<'tcx>>,
1230 mut expression_ty: Ty<'tcx>,
1231 augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1232 label_expression_as_expected: bool,
1234 // Incorporate whatever type inference information we have
1235 // until now; in principle we might also want to process
1236 // pending obligations, but doing so should only improve
1237 // compatibility (hopefully that is true) by helping us
1238 // uncover never types better.
1239 if expression_ty.is_ty_var() {
1240 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1243 // If we see any error types, just propagate that error
1245 if expression_ty.references_error() || self.merged_ty().references_error() {
1246 self.final_ty = Some(fcx.tcx.ty_error());
1250 // Handle the actual type unification etc.
1251 let result = if let Some(expression) = expression {
1252 if self.pushed == 0 {
1253 // Special-case the first expression we are coercing.
1254 // To be honest, I'm not entirely sure why we do this.
1255 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1256 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1258 match self.expressions {
1259 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1266 Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1268 &coercion_sites[0..self.pushed],
1276 // this is a hack for cases where we default to `()` because
1277 // the expression etc has been omitted from the source. An
1278 // example is an `if let` without an else:
1280 // if let Some(x) = ... { }
1282 // we wind up with a second match arm that is like `_ =>
1283 // ()`. That is the case we are considering here. We take
1284 // a different path to get the right "expected, found"
1285 // message and so forth (and because we know that
1286 // `expression_ty` will be unit).
1288 // Another example is `break` with no argument expression.
1289 assert!(expression_ty.is_unit(), "if let hack without unit type");
1290 fcx.at(cause, fcx.param_env)
1291 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1293 fcx.register_infer_ok_obligations(infer_ok);
1300 self.final_ty = Some(v);
1301 if let Some(e) = expression {
1302 match self.expressions {
1303 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1304 Expressions::UpFront(coercion_sites) => {
1305 // if the user gave us an array to validate, check that we got
1306 // the next expression in the list, as expected
1308 coercion_sites[self.pushed].as_coercion_site().hir_id,
1316 Err(coercion_error) => {
1317 let (expected, found) = if label_expression_as_expected {
1318 // In the case where this is a "forced unit", like
1319 // `break`, we want to call the `()` "expected"
1320 // since it is implied by the syntax.
1321 // (Note: not all force-units work this way.)"
1322 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1324 // Otherwise, the "expected" type for error
1325 // reporting is the current unification type,
1326 // which is basically the LUB of the expressions
1327 // we've seen so far (combined with the expected
1329 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1333 let mut unsized_return = false;
1335 ObligationCauseCode::ReturnNoExpression => {
1336 err = struct_span_err!(
1340 "`return;` in a function whose return type is not `()`"
1342 err.span_label(cause.span, "return type is not `()`");
1344 ObligationCauseCode::BlockTailExpression(blk_id) => {
1345 let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1346 err = self.report_return_mismatched_types(
1353 expression.map(|expr| (expr, blk_id)),
1355 if !fcx.tcx.features().unsized_locals {
1356 unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1359 ObligationCauseCode::ReturnValue(id) => {
1360 err = self.report_return_mismatched_types(
1369 if !fcx.tcx.features().unsized_locals {
1370 let id = fcx.tcx.hir().get_parent_node(id);
1371 unsized_return = self.is_return_ty_unsized(fcx, id);
1375 err = fcx.report_mismatched_types(cause, expected, found, coercion_error);
1379 if let Some(augment_error) = augment_error {
1380 augment_error(&mut err);
1383 if let Some(expr) = expression {
1384 fcx.emit_coerce_suggestions(&mut err, expr, found, expected, None);
1387 // Error possibly reported in `check_assign` so avoid emitting error again.
1388 let assign_to_bool = expression
1389 // #67273: Use initial expected type as opposed to `expected`.
1390 // Otherwise we end up using prior coercions in e.g. a `match` expression:
1393 // 0 => true, // Because of this...
1394 // 1 => i = 1, // ...`expected == bool` now, but not when checking `i = 1`.
1398 .filter(|e| fcx.is_assign_to_bool(e, self.expected_ty()))
1401 err.emit_unless(assign_to_bool || unsized_return);
1403 self.final_ty = Some(fcx.tcx.ty_error());
1408 fn report_return_mismatched_types<'a>(
1410 cause: &ObligationCause<'tcx>,
1413 ty_err: TypeError<'tcx>,
1414 fcx: &FnCtxt<'a, 'tcx>,
1416 expression: Option<(&'tcx hir::Expr<'tcx>, hir::HirId)>,
1417 ) -> DiagnosticBuilder<'a> {
1418 let mut err = fcx.report_mismatched_types(cause, expected, found, ty_err);
1420 let mut pointing_at_return_type = false;
1421 let mut fn_output = None;
1423 // Verify that this is a tail expression of a function, otherwise the
1424 // label pointing out the cause for the type coercion will be wrong
1425 // as prior return coercions would not be relevant (#57664).
1426 let parent_id = fcx.tcx.hir().get_parent_node(id);
1427 let fn_decl = if let Some((expr, blk_id)) = expression {
1428 pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1429 &mut err, expr, expected, found, cause.span, blk_id,
1431 let parent = fcx.tcx.hir().get(parent_id);
1432 if let (Some(match_expr), true, false) = (
1433 fcx.tcx.hir().get_match_if_cause(expr.hir_id),
1435 pointing_at_return_type,
1437 if match_expr.span.desugaring_kind().is_none() {
1438 err.span_label(match_expr.span, "expected this to be `()`");
1439 fcx.suggest_semicolon_at_end(match_expr.span, &mut err);
1442 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1444 fcx.get_fn_decl(parent_id)
1447 if let (Some((fn_decl, can_suggest)), _) = (fn_decl, pointing_at_return_type) {
1448 if expression.is_none() {
1449 pointing_at_return_type |= fcx.suggest_missing_return_type(
1457 if !pointing_at_return_type {
1458 fn_output = Some(&fn_decl.output); // `impl Trait` return type
1461 if let (Some(sp), Some(fn_output)) = (fcx.ret_coercion_span.borrow().as_ref(), fn_output) {
1462 self.add_impl_trait_explanation(&mut err, fcx, expected, *sp, fn_output);
1467 fn add_impl_trait_explanation<'a>(
1469 err: &mut DiagnosticBuilder<'a>,
1470 fcx: &FnCtxt<'a, 'tcx>,
1473 fn_output: &hir::FnRetTy<'_>,
1475 let return_sp = fn_output.span();
1476 err.span_label(return_sp, "expected because this return type...");
1479 format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1481 let impl_trait_msg = "for information on `impl Trait`, see \
1482 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1483 #returning-types-that-implement-traits>";
1484 let trait_obj_msg = "for information on trait objects, see \
1485 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1486 #using-trait-objects-that-allow-for-values-of-different-types>";
1487 err.note("to return `impl Trait`, all returned values must be of the same type");
1488 err.note(impl_trait_msg);
1493 .span_to_snippet(return_sp)
1494 .unwrap_or_else(|_| "dyn Trait".to_string());
1495 let mut snippet_iter = snippet.split_whitespace();
1496 let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1497 // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1498 let mut is_object_safe = false;
1499 if let hir::FnRetTy::Return(ty) = fn_output {
1500 // Get the return type.
1501 if let hir::TyKind::OpaqueDef(..) = ty.kind {
1502 let ty = AstConv::ast_ty_to_ty(fcx, ty);
1503 // Get the `impl Trait`'s `DefId`.
1504 if let ty::Opaque(def_id, _) = ty.kind {
1505 let hir_id = fcx.tcx.hir().as_local_hir_id(def_id.expect_local());
1506 // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1507 // get the `Trait`'s `DefId`.
1508 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1509 fcx.tcx.hir().expect_item(hir_id).kind
1511 // Are of this `impl Trait`'s traits object safe?
1512 is_object_safe = bounds.iter().all(|bound| {
1515 .and_then(|t| t.trait_def_id())
1516 .map_or(false, |def_id| {
1517 fcx.tcx.object_safety_violations(def_id).is_empty()
1527 "you can instead return a boxed trait object using `Box<dyn {}>`",
1532 "if the trait `{}` were object safe, you could return a boxed trait object",
1536 err.note(trait_obj_msg);
1538 err.help("alternatively, create a new `enum` with a variant for each returned type");
1541 fn is_return_ty_unsized(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
1542 if let Some((fn_decl, _)) = fcx.get_fn_decl(blk_id) {
1543 if let hir::FnRetTy::Return(ty) = fn_decl.output {
1544 let ty = AstConv::ast_ty_to_ty(fcx, ty);
1545 if let ty::Dynamic(..) = ty.kind {
1553 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1554 if let Some(final_ty) = self.final_ty {
1557 // If we only had inputs that were of type `!` (or no
1558 // inputs at all), then the final type is `!`.
1559 assert_eq!(self.pushed, 0);
1565 /// Something that can be converted into an expression to which we can
1566 /// apply a coercion.
1567 pub trait AsCoercionSite {
1568 fn as_coercion_site(&self) -> &hir::Expr<'_>;
1571 impl AsCoercionSite for hir::Expr<'_> {
1572 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1577 impl<'a, T> AsCoercionSite for &'a T
1581 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1582 (**self).as_coercion_site()
1586 impl AsCoercionSite for ! {
1587 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1592 impl AsCoercionSite for hir::Arm<'_> {
1593 fn as_coercion_site(&self) -> &hir::Expr<'_> {