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 inferring 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;
41 struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
44 use rustc_hir::def_id::DefId;
45 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
46 use rustc_infer::infer::{Coercion, InferOk, InferResult};
47 use rustc_infer::traits::{Obligation, TraitEngine, TraitEngineExt};
48 use rustc_middle::lint::in_external_macro;
49 use rustc_middle::ty::adjustment::{
50 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast,
52 use rustc_middle::ty::error::TypeError;
53 use rustc_middle::ty::fold::TypeFoldable;
54 use rustc_middle::ty::relate::RelateResult;
55 use rustc_middle::ty::subst::SubstsRef;
56 use rustc_middle::ty::{self, ToPredicate, Ty, TypeAndMut};
57 use rustc_session::parse::feature_err;
58 use rustc_span::symbol::sym;
59 use rustc_span::{self, BytePos, DesugaringKind, Span};
60 use rustc_target::spec::abi::Abi;
61 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
62 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode};
64 use smallvec::{smallvec, SmallVec};
67 struct Coerce<'a, 'tcx> {
68 fcx: &'a FnCtxt<'a, 'tcx>,
69 cause: ObligationCause<'tcx>,
71 /// Determines whether or not allow_two_phase_borrow is set on any
72 /// autoref adjustments we create while coercing. We don't want to
73 /// allow deref coercions to create two-phase borrows, at least initially,
74 /// but we do need two-phase borrows for function argument reborrows.
75 /// See #47489 and #48598
76 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
77 allow_two_phase: AllowTwoPhase,
80 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
81 type Target = FnCtxt<'a, 'tcx>;
82 fn deref(&self) -> &Self::Target {
87 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
89 /// Coercing a mutable reference to an immutable works, while
90 /// coercing `&T` to `&mut T` should be forbidden.
91 fn coerce_mutbls<'tcx>(
92 from_mutbl: hir::Mutability,
93 to_mutbl: hir::Mutability,
94 ) -> RelateResult<'tcx, ()> {
95 match (from_mutbl, to_mutbl) {
96 (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not)
97 | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()),
98 (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability),
102 /// Do not require any adjustments, i.e. coerce `x -> x`.
103 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> {
107 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
108 move |target| vec![Adjustment { kind, target }]
111 /// This always returns `Ok(...)`.
113 adj: Vec<Adjustment<'tcx>>,
115 obligations: traits::PredicateObligations<'tcx>,
116 ) -> CoerceResult<'tcx> {
117 Ok(InferOk { value: (adj, target), obligations })
120 impl<'f, 'tcx> Coerce<'f, 'tcx> {
122 fcx: &'f FnCtxt<'f, 'tcx>,
123 cause: ObligationCause<'tcx>,
124 allow_two_phase: AllowTwoPhase,
126 Coerce { fcx, cause, allow_two_phase, use_lub: false }
129 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
130 debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
131 self.commit_if_ok(|_| {
133 self.at(&self.cause, self.fcx.param_env).lub(b, a)
135 self.at(&self.cause, self.fcx.param_env)
137 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
142 /// Unify two types (using sub or lub) and produce a specific coercion.
143 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx>
145 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
148 .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations))
151 #[instrument(skip(self))]
152 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
153 // First, remove any resolved type variables (at the top level, at least):
154 let a = self.shallow_resolve(a);
155 let b = self.shallow_resolve(b);
156 debug!("Coerce.tys({:?} => {:?})", a, b);
158 // Just ignore error types.
159 if a.references_error() || b.references_error() {
160 return success(vec![], self.fcx.tcx.ty_error(), vec![]);
163 // Coercing from `!` to any type is allowed:
165 return success(simple(Adjust::NeverToAny)(b), b, vec![]);
168 // Coercing *from* an unresolved inference variable means that
169 // we have no information about the source type. This will always
170 // ultimately fall back to some form of subtyping.
172 return self.coerce_from_inference_variable(a, b, identity);
175 // Consider coercing the subtype to a DST
177 // NOTE: this is wrapped in a `commit_if_ok` because it creates
178 // a "spurious" type variable, and we don't want to have that
179 // type variable in memory if the coercion fails.
180 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
183 debug!("coerce: unsize successful");
186 Err(TypeError::ObjectUnsafeCoercion(did)) => {
187 debug!("coerce: unsize not object safe");
188 return Err(TypeError::ObjectUnsafeCoercion(did));
191 debug!(?error, "coerce: unsize failed");
195 // Examine the supertype and consider auto-borrowing.
197 ty::RawPtr(mt_b) => {
198 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
200 ty::Ref(r_b, _, mutbl_b) => {
201 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
208 // Function items are coercible to any closure
209 // type; function pointers are not (that would
210 // require double indirection).
211 // Additionally, we permit coercion of function
212 // items to drop the unsafe qualifier.
213 self.coerce_from_fn_item(a, b)
216 // We permit coercion of fn pointers to drop the
218 self.coerce_from_fn_pointer(a, a_f, b)
220 ty::Closure(closure_def_id_a, substs_a) => {
221 // Non-capturing closures are coercible to
222 // function pointers or unsafe function pointers.
223 // It cannot convert closures that require unsafe.
224 self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b)
227 // Otherwise, just use unification rules.
228 self.unify_and(a, b, identity)
233 /// Coercing *from* an inference variable. In this case, we have no information
234 /// about the source type, so we can't really do a true coercion and we always
235 /// fall back to subtyping (`unify_and`).
236 fn coerce_from_inference_variable(
240 make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
241 ) -> CoerceResult<'tcx> {
242 debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
243 assert!(a.is_ty_var() && self.infcx.shallow_resolve(a) == a);
244 assert!(self.infcx.shallow_resolve(b) == b);
247 // Two unresolved type variables: create a `Coerce` predicate.
248 let target_ty = if self.use_lub {
249 self.infcx.next_ty_var(TypeVariableOrigin {
250 kind: TypeVariableOriginKind::LatticeVariable,
251 span: self.cause.span,
257 let mut obligations = Vec::with_capacity(2);
258 for &source_ty in &[a, b] {
259 if source_ty != target_ty {
260 obligations.push(Obligation::new(
263 ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate {
267 .to_predicate(self.tcx()),
273 "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
274 target_ty, obligations
276 let adjustments = make_adjustments(target_ty);
277 InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations })
279 // One unresolved type variable: just apply subtyping, we may be able
280 // to do something useful.
281 self.unify_and(a, b, make_adjustments)
285 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
286 /// To match `A` with `B`, autoderef will be performed,
287 /// calling `deref`/`deref_mut` where necessary.
288 fn coerce_borrowed_pointer(
292 r_b: ty::Region<'tcx>,
293 mutbl_b: hir::Mutability,
294 ) -> CoerceResult<'tcx> {
295 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
297 // If we have a parameter of type `&M T_a` and the value
298 // provided is `expr`, we will be adding an implicit borrow,
299 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
300 // to type check, we will construct the type that `&M*expr` would
303 let (r_a, mt_a) = match *a.kind() {
304 ty::Ref(r_a, ty, mutbl) => {
305 let mt_a = ty::TypeAndMut { ty, mutbl };
306 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
309 _ => return self.unify_and(a, b, identity),
312 let span = self.cause.span;
314 let mut first_error = None;
315 let mut r_borrow_var = None;
316 let mut autoderef = self.autoderef(span, a);
317 let mut found = None;
319 for (referent_ty, autoderefs) in autoderef.by_ref() {
321 // Don't let this pass, otherwise it would cause
322 // &T to autoref to &&T.
326 // At this point, we have deref'd `a` to `referent_ty`. So
327 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
328 // In the autoderef loop for `&'a mut Vec<T>`, we would get
331 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
332 // - `Vec<T>` -- 1 deref
333 // - `[T]` -- 2 deref
335 // At each point after the first callback, we want to
336 // check to see whether this would match out target type
337 // (`&'b mut [T]`) if we autoref'd it. We can't just
338 // compare the referent types, though, because we still
339 // have to consider the mutability. E.g., in the case
340 // we've been considering, we have an `&mut` reference, so
341 // the `T` in `[T]` needs to be unified with equality.
343 // Therefore, we construct reference types reflecting what
344 // the types will be after we do the final auto-ref and
345 // compare those. Note that this means we use the target
346 // mutability [1], since it may be that we are coercing
347 // from `&mut T` to `&U`.
349 // One fine point concerns the region that we use. We
350 // choose the region such that the region of the final
351 // type that results from `unify` will be the region we
352 // want for the autoref:
354 // - if in sub mode, that means we want to use `'b` (the
355 // region from the target reference) for both
356 // pointers [2]. This is because sub mode (somewhat
357 // arbitrarily) returns the subtype region. In the case
358 // where we are coercing to a target type, we know we
359 // want to use that target type region (`'b`) because --
360 // for the program to type-check -- it must be the
361 // smaller of the two.
362 // - One fine point. It may be surprising that we can
363 // use `'b` without relating `'a` and `'b`. The reason
364 // that this is ok is that what we produce is
365 // effectively a `&'b *x` expression (if you could
366 // annotate the region of a borrow), and regionck has
367 // code that adds edges from the region of a borrow
368 // (`'b`, here) into the regions in the borrowed
369 // expression (`*x`, here). (Search for "link".)
370 // - if in lub mode, things can get fairly complicated. The
371 // easiest thing is just to make a fresh
372 // region variable [4], which effectively means we defer
373 // the decision to region inference (and regionck, which will add
374 // some more edges to this variable). However, this can wind up
375 // creating a crippling number of variables in some cases --
376 // e.g., #32278 -- so we optimize one particular case [3].
377 // Let me try to explain with some examples:
378 // - The "running example" above represents the simple case,
379 // where we have one `&` reference at the outer level and
380 // ownership all the rest of the way down. In this case,
381 // we want `LUB('a, 'b)` as the resulting region.
382 // - However, if there are nested borrows, that region is
383 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
384 // `&'b T`. In this case, `'a` is actually irrelevant.
385 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
386 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
387 // (The errors actually show up in borrowck, typically, because
388 // this extra edge causes the region `'a` to be inferred to something
389 // too big, which then results in borrowck errors.)
390 // - We could track the innermost shared reference, but there is already
391 // code in regionck that has the job of creating links between
392 // the region of a borrow and the regions in the thing being
393 // borrowed (here, `'a` and `'x`), and it knows how to handle
394 // all the various cases. So instead we just make a region variable
395 // and let regionck figure it out.
396 let r = if !self.use_lub {
398 } else if autoderefs == 1 {
401 if r_borrow_var.is_none() {
402 // create var lazily, at most once
403 let coercion = Coercion(span);
404 let r = self.next_region_var(coercion);
405 r_borrow_var = Some(r); // [4] above
407 r_borrow_var.unwrap()
409 let derefd_ty_a = self.tcx.mk_ref(
413 mutbl: mutbl_b, // [1] above
416 match self.unify(derefd_ty_a, b) {
422 if first_error.is_none() {
423 first_error = Some(err);
429 // Extract type or return an error. We return the first error
430 // we got, which should be from relating the "base" type
431 // (e.g., in example above, the failure from relating `Vec<T>`
432 // to the target type), since that should be the least
434 let Some(InferOk { value: ty, mut obligations }) = found else {
435 let err = first_error.expect("coerce_borrowed_pointer had no error");
436 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
440 if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 {
441 // As a special case, if we would produce `&'a *x`, that's
442 // a total no-op. We end up with the type `&'a T` just as
443 // we started with. In that case, just skip it
444 // altogether. This is just an optimization.
446 // Note that for `&mut`, we DO want to reborrow --
447 // otherwise, this would be a move, which might be an
448 // error. For example `foo(self.x)` where `self` and
449 // `self.x` both have `&mut `type would be a move of
450 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
451 // which is a borrow.
452 assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U
453 return success(vec![], ty, obligations);
456 let InferOk { value: mut adjustments, obligations: o } =
457 self.adjust_steps_as_infer_ok(&autoderef);
458 obligations.extend(o);
459 obligations.extend(autoderef.into_obligations());
461 // Now apply the autoref. We have to extract the region out of
462 // the final ref type we got.
463 let ty::Ref(r_borrow, _, _) = ty.kind() else {
464 span_bug!(span, "expected a ref type, got {:?}", ty);
466 let mutbl = match mutbl_b {
467 hir::Mutability::Not => AutoBorrowMutability::Not,
468 hir::Mutability::Mut => {
469 AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase }
472 adjustments.push(Adjustment {
473 kind: Adjust::Borrow(AutoBorrow::Ref(*r_borrow, mutbl)),
477 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
479 success(adjustments, ty, obligations)
482 // &[T; n] or &mut [T; n] -> &[T]
483 // or &mut [T; n] -> &mut [T]
484 // or &Concrete -> &Trait, etc.
485 #[instrument(skip(self), level = "debug")]
486 fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> {
487 source = self.shallow_resolve(source);
488 target = self.shallow_resolve(target);
489 debug!(?source, ?target);
491 // These 'if' statements require some explanation.
492 // The `CoerceUnsized` trait is special - it is only
493 // possible to write `impl CoerceUnsized<B> for A` where
494 // A and B have 'matching' fields. This rules out the following
495 // two types of blanket impls:
497 // `impl<T> CoerceUnsized<T> for SomeType`
498 // `impl<T> CoerceUnsized<SomeType> for T`
500 // Both of these trigger a special `CoerceUnsized`-related error (E0376)
502 // We can take advantage of this fact to avoid performing unnecessary work.
503 // If either `source` or `target` is a type variable, then any applicable impl
504 // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
505 // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
508 // However, these are exactly the kinds of impls which are forbidden by
509 // the compiler! Therefore, we can be sure that coercion will always fail
510 // when either the source or target type is a type variable. This allows us
511 // to skip performing any trait selection, and immediately bail out.
512 if source.is_ty_var() {
513 debug!("coerce_unsized: source is a TyVar, bailing out");
514 return Err(TypeError::Mismatch);
516 if target.is_ty_var() {
517 debug!("coerce_unsized: target is a TyVar, bailing out");
518 return Err(TypeError::Mismatch);
522 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
523 let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
524 debug!("missing Unsize or CoerceUnsized traits");
525 return Err(TypeError::Mismatch);
528 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
529 // a DST unless we have to. This currently comes out in the wash since
530 // we can't unify [T] with U. But to properly support DST, we need to allow
531 // that, at which point we will need extra checks on the target here.
533 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
534 let reborrow = match (source.kind(), target.kind()) {
535 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
536 coerce_mutbls(mutbl_a, mutbl_b)?;
538 let coercion = Coercion(self.cause.span);
539 let r_borrow = self.next_region_var(coercion);
540 let mutbl = match mutbl_b {
541 hir::Mutability::Not => AutoBorrowMutability::Not,
542 hir::Mutability::Mut => AutoBorrowMutability::Mut {
543 // We don't allow two-phase borrows here, at least for initial
544 // implementation. If it happens that this coercion is a function argument,
545 // the reborrow in coerce_borrowed_ptr will pick it up.
546 allow_two_phase_borrow: AllowTwoPhase::No,
550 Adjustment { kind: Adjust::Deref(None), target: ty_a },
552 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
555 .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }),
559 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
560 coerce_mutbls(mt_a, mt_b)?;
563 Adjustment { kind: Adjust::Deref(None), target: ty_a },
565 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
566 target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
572 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
574 // Setup either a subtyping or a LUB relationship between
575 // the `CoerceUnsized` target type and the expected type.
576 // We only have the latter, so we use an inference variable
577 // for the former and let type inference do the rest.
578 let origin = TypeVariableOrigin {
579 kind: TypeVariableOriginKind::MiscVariable,
580 span: self.cause.span,
582 let coerce_target = self.next_ty_var(origin);
583 let mut coercion = self.unify_and(coerce_target, target, |target| {
584 let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target };
586 None => vec![unsize],
587 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
591 let mut selcx = traits::SelectionContext::new(self);
593 // Create an obligation for `Source: CoerceUnsized<Target>`.
594 let cause = ObligationCause::new(
597 ObligationCauseCode::Coercion { source, target },
600 // Use a FIFO queue for this custom fulfillment procedure.
602 // A Vec (or SmallVec) is not a natural choice for a queue. However,
603 // this code path is hot, and this queue usually has a max length of 1
604 // and almost never more than 3. By using a SmallVec we avoid an
605 // allocation, at the (very small) cost of (occasionally) having to
606 // shift subsequent elements down when removing the front element.
607 let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def(
614 &[coerce_target.into()]
617 let mut has_unsized_tuple_coercion = false;
618 let mut has_trait_upcasting_coercion = false;
620 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
621 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
622 // inference might unify those two inner type variables later.
623 let traits = [coerce_unsized_did, unsize_did];
624 while !queue.is_empty() {
625 let obligation = queue.remove(0);
626 debug!("coerce_unsized resolve step: {:?}", obligation);
627 let bound_predicate = obligation.predicate.kind();
628 let trait_pred = match bound_predicate.skip_binder() {
629 ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => {
630 if unsize_did == trait_pred.def_id() {
631 let self_ty = trait_pred.self_ty();
632 let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
633 if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) =
634 (self_ty.kind(), unsize_ty.kind())
635 && data_a.principal_def_id() != data_b.principal_def_id()
637 debug!("coerce_unsized: found trait upcasting coercion");
638 has_trait_upcasting_coercion = true;
640 if let ty::Tuple(..) = unsize_ty.kind() {
641 debug!("coerce_unsized: found unsized tuple coercion");
642 has_unsized_tuple_coercion = true;
645 bound_predicate.rebind(trait_pred)
648 coercion.obligations.push(obligation);
652 match selcx.select(&obligation.with(trait_pred)) {
653 // Uncertain or unimplemented.
655 if trait_pred.def_id() == unsize_did {
656 let trait_pred = self.resolve_vars_if_possible(trait_pred);
657 let self_ty = trait_pred.skip_binder().self_ty();
658 let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty();
659 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
660 match (&self_ty.kind(), &unsize_ty.kind()) {
661 (ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
662 if self.type_var_is_sized(*v) =>
664 debug!("coerce_unsized: have sized infer {:?}", v);
665 coercion.obligations.push(obligation);
666 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
670 // Some other case for `$0: Unsize<Something>`. Note that we
671 // hit this case even if `Something` is a sized type, so just
672 // don't do the coercion.
673 debug!("coerce_unsized: ambiguous unsize");
674 return Err(TypeError::Mismatch);
678 debug!("coerce_unsized: early return - ambiguous");
679 return Err(TypeError::Mismatch);
682 Err(traits::Unimplemented) => {
683 debug!("coerce_unsized: early return - can't prove obligation");
684 return Err(TypeError::Mismatch);
687 // Object safety violations or miscellaneous.
689 self.report_selection_error(obligation.clone(), &obligation, &err, false);
690 // Treat this like an obligation and follow through
691 // with the unsizing - the lack of a coercion should
692 // be silent, as it causes a type mismatch later.
695 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
699 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
701 &self.tcx.sess.parse_sess,
702 sym::unsized_tuple_coercion,
704 "unsized tuple coercion is not stable enough for use and is subject to change",
709 if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting {
711 &self.tcx.sess.parse_sess,
712 sym::trait_upcasting,
714 "trait upcasting coercion is experimental",
722 fn coerce_from_safe_fn<F, G>(
725 fn_ty_a: ty::PolyFnSig<'tcx>,
729 ) -> CoerceResult<'tcx>
731 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
732 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
734 if let ty::FnPtr(fn_ty_b) = b.kind()
735 && let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
736 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
738 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
739 return self.unify_and(unsafe_a, b, to_unsafe);
741 self.unify_and(a, b, normal)
744 fn coerce_from_fn_pointer(
747 fn_ty_a: ty::PolyFnSig<'tcx>,
749 ) -> CoerceResult<'tcx> {
750 //! Attempts to coerce from the type of a Rust function item
751 //! into a closure or a `proc`.
754 let b = self.shallow_resolve(b);
755 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
757 self.coerce_from_safe_fn(
761 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
766 fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
767 //! Attempts to coerce from the type of a Rust function item
768 //! into a closure or a `proc`.
770 let b = self.shallow_resolve(b);
771 let InferOk { value: b, mut obligations } =
772 self.normalize_associated_types_in_as_infer_ok(self.cause.span, b);
773 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
776 ty::FnPtr(b_sig) => {
777 let a_sig = a.fn_sig(self.tcx);
778 // Intrinsics are not coercible to function pointers
779 if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic {
780 return Err(TypeError::IntrinsicCast);
783 // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
784 if let ty::FnDef(def_id, _) = *a.kind()
785 && b_sig.unsafety() == hir::Unsafety::Normal
786 && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
788 return Err(TypeError::TargetFeatureCast(def_id));
791 let InferOk { value: a_sig, obligations: o1 } =
792 self.normalize_associated_types_in_as_infer_ok(self.cause.span, a_sig);
793 obligations.extend(o1);
795 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
796 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
803 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
804 target: a_fn_pointer,
807 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
812 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
815 obligations.extend(o2);
816 Ok(InferOk { value, obligations })
818 _ => self.unify_and(a, b, identity),
822 fn coerce_closure_to_fn(
825 closure_def_id_a: DefId,
826 substs_a: SubstsRef<'tcx>,
828 ) -> CoerceResult<'tcx> {
829 //! Attempts to coerce from the type of a non-capturing closure
830 //! into a function pointer.
833 let b = self.shallow_resolve(b);
836 // At this point we haven't done capture analysis, which means
837 // that the ClosureSubsts just contains an inference variable instead
838 // of tuple of captured types.
840 // All we care here is if any variable is being captured and not the exact paths,
841 // so we check `upvars_mentioned` for root variables being captured.
845 .upvars_mentioned(closure_def_id_a.expect_local())
846 .map_or(true, |u| u.is_empty()) =>
848 // We coerce the closure, which has fn type
849 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
851 // `fn(arg0,arg1,...) -> _`
853 // `unsafe fn(arg0,arg1,...) -> _`
854 let closure_sig = substs_a.as_closure().sig();
855 let unsafety = fn_ty.unsafety();
857 self.tcx.mk_fn_ptr(self.tcx.signature_unclosure(closure_sig, unsafety));
858 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
862 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
865 _ => self.unify_and(a, b, identity),
869 fn coerce_unsafe_ptr(
873 mutbl_b: hir::Mutability,
874 ) -> CoerceResult<'tcx> {
875 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
877 let (is_ref, mt_a) = match *a.kind() {
878 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
879 ty::RawPtr(mt) => (false, mt),
880 _ => return self.unify_and(a, b, identity),
882 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
884 // Check that the types which they point at are compatible.
885 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
886 // Although references and unsafe ptrs have the same
887 // representation, we still register an Adjust::DerefRef so that
888 // regionck knows that the region for `a` must be valid here.
890 self.unify_and(a_unsafe, b, |target| {
892 Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
893 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
896 } else if mt_a.mutbl != mutbl_b {
897 self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
899 self.unify_and(a_unsafe, b, identity)
904 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
905 /// Attempt to coerce an expression to a type, and return the
906 /// adjusted type of the expression, if successful.
907 /// Adjustments are only recorded if the coercion succeeded.
908 /// The expressions *must not* have any pre-existing adjustments.
911 expr: &hir::Expr<'_>,
914 allow_two_phase: AllowTwoPhase,
915 cause: Option<ObligationCause<'tcx>>,
916 ) -> RelateResult<'tcx, Ty<'tcx>> {
917 let source = self.resolve_vars_with_obligations(expr_ty);
918 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
921 cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
922 let coerce = Coerce::new(self, cause, allow_two_phase);
923 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
925 let (adjustments, _) = self.register_infer_ok_obligations(ok);
926 self.apply_adjustments(expr, adjustments);
927 Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target })
930 /// Same as `try_coerce()`, but without side-effects.
932 /// Returns false if the coercion creates any obligations that result in
934 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
935 let source = self.resolve_vars_with_obligations(expr_ty);
936 debug!("coercion::can_with_predicates({:?} -> {:?})", source, target);
938 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
939 // We don't ever need two-phase here since we throw out the result of the coercion
940 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
942 let Ok(ok) = coerce.coerce(source, target) else {
945 let mut fcx = traits::FulfillmentContext::new_in_snapshot();
946 fcx.register_predicate_obligations(self, ok.obligations);
947 fcx.select_where_possible(&self).is_empty()
951 /// Given a type and a target type, this function will calculate and return
952 /// how many dereference steps needed to achieve `expr_ty <: target`. If
953 /// it's not possible, return `None`.
954 pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
955 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
956 // We don't ever need two-phase here since we throw out the result of the coercion
957 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
959 .autoderef(rustc_span::DUMMY_SP, expr_ty)
960 .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
963 /// Given some expressions, their known unified type and another expression,
964 /// tries to unify the types, potentially inserting coercions on any of the
965 /// provided expressions and returns their LUB (aka "common supertype").
967 /// This is really an internal helper. From outside the coercion
968 /// module, you should instantiate a `CoerceMany` instance.
969 fn try_find_coercion_lub<E>(
971 cause: &ObligationCause<'tcx>,
976 ) -> RelateResult<'tcx, Ty<'tcx>>
980 let prev_ty = self.resolve_vars_with_obligations(prev_ty);
981 let new_ty = self.resolve_vars_with_obligations(new_ty);
983 "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
989 // The following check fixes #88097, where the compiler erroneously
990 // attempted to coerce a closure type to itself via a function pointer.
991 if prev_ty == new_ty {
995 // Special-case that coercion alone cannot handle:
996 // Function items or non-capturing closures of differing IDs or InternalSubsts.
997 let (a_sig, b_sig) = {
998 let is_capturing_closure = |ty| {
999 if let &ty::Closure(closure_def_id, _substs) = ty {
1000 self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
1005 if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) {
1008 match (prev_ty.kind(), new_ty.kind()) {
1009 (ty::FnDef(..), ty::FnDef(..)) => {
1010 // Don't reify if the function types have a LUB, i.e., they
1011 // are the same function and their parameters have a LUB.
1013 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1015 // We have a LUB of prev_ty and new_ty, just return it.
1016 Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1018 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
1022 (ty::Closure(_, substs), ty::FnDef(..)) => {
1023 let b_sig = new_ty.fn_sig(self.tcx);
1026 .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
1027 (Some(a_sig), Some(b_sig))
1029 (ty::FnDef(..), ty::Closure(_, substs)) => {
1030 let a_sig = prev_ty.fn_sig(self.tcx);
1033 .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
1034 (Some(a_sig), Some(b_sig))
1036 (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => (
1037 Some(self.tcx.signature_unclosure(
1038 substs_a.as_closure().sig(),
1039 hir::Unsafety::Normal,
1041 Some(self.tcx.signature_unclosure(
1042 substs_b.as_closure().sig(),
1043 hir::Unsafety::Normal,
1050 if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
1051 // Intrinsics are not coercible to function pointers.
1052 if a_sig.abi() == Abi::RustIntrinsic
1053 || a_sig.abi() == Abi::PlatformIntrinsic
1054 || b_sig.abi() == Abi::RustIntrinsic
1055 || b_sig.abi() == Abi::PlatformIntrinsic
1057 return Err(TypeError::IntrinsicCast);
1059 // The signature must match.
1060 let a_sig = self.normalize_associated_types_in(new.span, a_sig);
1061 let b_sig = self.normalize_associated_types_in(new.span, b_sig);
1063 .at(cause, self.param_env)
1064 .trace(prev_ty, new_ty)
1066 .map(|ok| self.register_infer_ok_obligations(ok))?;
1068 // Reify both sides and return the reified fn pointer type.
1069 let fn_ptr = self.tcx.mk_fn_ptr(sig);
1070 let prev_adjustment = match prev_ty.kind() {
1071 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.unsafety())),
1072 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1073 _ => unreachable!(),
1075 let next_adjustment = match new_ty.kind() {
1076 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.unsafety())),
1077 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1078 _ => unreachable!(),
1080 for expr in exprs.iter().map(|e| e.as_coercion_site()) {
1081 self.apply_adjustments(
1083 vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1086 self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1090 // Configure a Coerce instance to compute the LUB.
1091 // We don't allow two-phase borrows on any autorefs this creates since we
1092 // probably aren't processing function arguments here and even if we were,
1093 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1095 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
1096 coerce.use_lub = true;
1098 // First try to coerce the new expression to the type of the previous ones,
1099 // but only if the new expression has no coercion already applied to it.
1100 let mut first_error = None;
1101 if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1102 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1105 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1106 self.apply_adjustments(new, adjustments);
1108 "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}",
1113 Err(e) => first_error = Some(e),
1117 // Then try to coerce the previous expressions to the type of the new one.
1118 // This requires ensuring there are no coercions applied to *any* of the
1119 // previous expressions, other than noop reborrows (ignoring lifetimes).
1121 let expr = expr.as_coercion_site();
1122 let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
1124 Adjustment { kind: Adjust::Deref(_), .. },
1125 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. },
1127 match *self.node_ty(expr.hir_id).kind() {
1128 ty::Ref(_, _, mt_orig) => {
1129 let mutbl_adj: hir::Mutability = mutbl_adj.into();
1130 // Reborrow that we can safely ignore, because
1131 // the next adjustment can only be a Deref
1132 // which will be merged into it.
1133 mutbl_adj == mt_orig
1138 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1144 "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1149 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1150 .map(|ok| self.register_infer_ok_obligations(ok));
1154 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1156 // Avoid giving strange errors on failed attempts.
1157 if let Some(e) = first_error {
1160 self.commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1161 .map(|ok| self.register_infer_ok_obligations(ok))
1166 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?}",
1169 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1171 let expr = expr.as_coercion_site();
1172 self.apply_adjustments(expr, adjustments.clone());
1180 /// CoerceMany encapsulates the pattern you should use when you have
1181 /// many expressions that are all getting coerced to a common
1182 /// type. This arises, for example, when you have a match (the result
1183 /// of each arm is coerced to a common type). It also arises in less
1184 /// obvious places, such as when you have many `break foo` expressions
1185 /// that target the same loop, or the various `return` expressions in
1188 /// The basic protocol is as follows:
1190 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1191 /// This will also serve as the "starting LUB". The expectation is
1192 /// that this type is something which all of the expressions *must*
1193 /// be coercible to. Use a fresh type variable if needed.
1194 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1195 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1196 /// unit. This happens for example if you have a `break` with no expression,
1197 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1198 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1199 /// from you so that you don't have to worry your pretty head about it.
1200 /// But if an error is reported, the final type will be `err`.
1201 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1202 /// previously coerced expressions.
1203 /// - When all done, invoke `complete()`. This will return the LUB of
1204 /// all your expressions.
1205 /// - WARNING: I don't believe this final type is guaranteed to be
1206 /// related to your initial `expected_ty` in any particular way,
1207 /// although it will typically be a subtype, so you should check it.
1208 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1209 /// previously coerced expressions.
1214 /// let mut coerce = CoerceMany::new(expected_ty);
1215 /// for expr in exprs {
1216 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1217 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1219 /// let final_ty = coerce.complete(fcx);
1221 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1222 expected_ty: Ty<'tcx>,
1223 final_ty: Option<Ty<'tcx>>,
1224 expressions: Expressions<'tcx, 'exprs, E>,
1228 /// The type of a `CoerceMany` that is storing up the expressions into
1229 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1230 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1232 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1233 Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1234 UpFront(&'exprs [E]),
1237 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1238 /// The usual case; collect the set of expressions dynamically.
1239 /// If the full set of coercion sites is known before hand,
1240 /// consider `with_coercion_sites()` instead to avoid allocation.
1241 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1242 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1245 /// As an optimization, you can create a `CoerceMany` with a
1246 /// pre-existing slice of expressions. In this case, you are
1247 /// expected to pass each element in the slice to `coerce(...)` in
1248 /// order. This is used with arrays in particular to avoid
1249 /// needlessly cloning the slice.
1250 pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1251 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1254 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1255 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1258 /// Returns the "expected type" with which this coercion was
1259 /// constructed. This represents the "downward propagated" type
1260 /// that was given to us at the start of typing whatever construct
1261 /// we are typing (e.g., the match expression).
1263 /// Typically, this is used as the expected type when
1264 /// type-checking each of the alternative expressions whose types
1265 /// we are trying to merge.
1266 pub fn expected_ty(&self) -> Ty<'tcx> {
1270 /// Returns the current "merged type", representing our best-guess
1271 /// at the LUB of the expressions we've seen so far (if any). This
1272 /// isn't *final* until you call `self.complete()`, which will return
1273 /// the merged type.
1274 pub fn merged_ty(&self) -> Ty<'tcx> {
1275 self.final_ty.unwrap_or(self.expected_ty)
1278 /// Indicates that the value generated by `expression`, which is
1279 /// of type `expression_ty`, is one of the possibilities that we
1280 /// could coerce from. This will record `expression`, and later
1281 /// calls to `coerce` may come back and add adjustments and things
1285 fcx: &FnCtxt<'a, 'tcx>,
1286 cause: &ObligationCause<'tcx>,
1287 expression: &'tcx hir::Expr<'tcx>,
1288 expression_ty: Ty<'tcx>,
1290 self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1293 /// Indicates that one of the inputs is a "forced unit". This
1294 /// occurs in a case like `if foo { ... };`, where the missing else
1295 /// generates a "forced unit". Another example is a `loop { break;
1296 /// }`, where the `break` has no argument expression. We treat
1297 /// these cases slightly differently for error-reporting
1298 /// purposes. Note that these tend to correspond to cases where
1299 /// the `()` expression is implicit in the source, and hence we do
1300 /// not take an expression argument.
1302 /// The `augment_error` gives you a chance to extend the error
1303 /// message, in case any results (e.g., we use this to suggest
1304 /// removing a `;`).
1305 pub fn coerce_forced_unit<'a>(
1307 fcx: &FnCtxt<'a, 'tcx>,
1308 cause: &ObligationCause<'tcx>,
1309 augment_error: &mut dyn FnMut(&mut Diagnostic),
1310 label_unit_as_expected: bool,
1317 Some(augment_error),
1318 label_unit_as_expected,
1322 /// The inner coercion "engine". If `expression` is `None`, this
1323 /// is a forced-unit case, and hence `expression_ty` must be
1325 #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1326 crate fn coerce_inner<'a>(
1328 fcx: &FnCtxt<'a, 'tcx>,
1329 cause: &ObligationCause<'tcx>,
1330 expression: Option<&'tcx hir::Expr<'tcx>>,
1331 mut expression_ty: Ty<'tcx>,
1332 augment_error: Option<&mut dyn FnMut(&mut Diagnostic)>,
1333 label_expression_as_expected: bool,
1335 // Incorporate whatever type inference information we have
1336 // until now; in principle we might also want to process
1337 // pending obligations, but doing so should only improve
1338 // compatibility (hopefully that is true) by helping us
1339 // uncover never types better.
1340 if expression_ty.is_ty_var() {
1341 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1344 // If we see any error types, just propagate that error
1346 if expression_ty.references_error() || self.merged_ty().references_error() {
1347 self.final_ty = Some(fcx.tcx.ty_error());
1351 // Handle the actual type unification etc.
1352 let result = if let Some(expression) = expression {
1353 if self.pushed == 0 {
1354 // Special-case the first expression we are coercing.
1355 // To be honest, I'm not entirely sure why we do this.
1356 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1362 Some(cause.clone()),
1365 match self.expressions {
1366 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1373 Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1375 &coercion_sites[0..self.pushed],
1383 // this is a hack for cases where we default to `()` because
1384 // the expression etc has been omitted from the source. An
1385 // example is an `if let` without an else:
1387 // if let Some(x) = ... { }
1389 // we wind up with a second match arm that is like `_ =>
1390 // ()`. That is the case we are considering here. We take
1391 // a different path to get the right "expected, found"
1392 // message and so forth (and because we know that
1393 // `expression_ty` will be unit).
1395 // Another example is `break` with no argument expression.
1396 assert!(expression_ty.is_unit(), "if let hack without unit type");
1397 fcx.at(cause, fcx.param_env)
1398 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1400 fcx.register_infer_ok_obligations(infer_ok);
1407 self.final_ty = Some(v);
1408 if let Some(e) = expression {
1409 match self.expressions {
1410 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1411 Expressions::UpFront(coercion_sites) => {
1412 // if the user gave us an array to validate, check that we got
1413 // the next expression in the list, as expected
1415 coercion_sites[self.pushed].as_coercion_site().hir_id,
1423 Err(coercion_error) => {
1424 let (expected, found) = if label_expression_as_expected {
1425 // In the case where this is a "forced unit", like
1426 // `break`, we want to call the `()` "expected"
1427 // since it is implied by the syntax.
1428 // (Note: not all force-units work this way.)"
1429 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1431 // Otherwise, the "expected" type for error
1432 // reporting is the current unification type,
1433 // which is basically the LUB of the expressions
1434 // we've seen so far (combined with the expected
1436 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1440 let mut unsized_return = false;
1441 match *cause.code() {
1442 ObligationCauseCode::ReturnNoExpression => {
1443 err = struct_span_err!(
1447 "`return;` in a function whose return type is not `()`"
1449 err.span_label(cause.span, "return type is not `()`");
1451 ObligationCauseCode::BlockTailExpression(blk_id) => {
1452 let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1453 err = self.report_return_mismatched_types(
1457 coercion_error.clone(),
1460 expression.map(|expr| (expr, blk_id)),
1462 if !fcx.tcx.features().unsized_locals {
1463 unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1466 ObligationCauseCode::ReturnValue(id) => {
1467 err = self.report_return_mismatched_types(
1471 coercion_error.clone(),
1476 if !fcx.tcx.features().unsized_locals {
1477 let id = fcx.tcx.hir().get_parent_node(id);
1478 unsized_return = self.is_return_ty_unsized(fcx, id);
1482 err = fcx.report_mismatched_types(
1486 coercion_error.clone(),
1491 if let Some(augment_error) = augment_error {
1492 augment_error(&mut err);
1495 if let Some(expr) = expression {
1496 fcx.emit_coerce_suggestions(
1502 Some(coercion_error),
1506 err.emit_unless(unsized_return);
1508 self.final_ty = Some(fcx.tcx.ty_error());
1513 fn report_return_mismatched_types<'a>(
1515 cause: &ObligationCause<'tcx>,
1518 ty_err: TypeError<'tcx>,
1519 fcx: &FnCtxt<'a, 'tcx>,
1521 expression: Option<(&'tcx hir::Expr<'tcx>, hir::HirId)>,
1522 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1523 let mut err = fcx.report_mismatched_types(cause, expected, found, ty_err);
1525 let mut pointing_at_return_type = false;
1526 let mut fn_output = None;
1528 // Verify that this is a tail expression of a function, otherwise the
1529 // label pointing out the cause for the type coercion will be wrong
1530 // as prior return coercions would not be relevant (#57664).
1531 let parent_id = fcx.tcx.hir().get_parent_node(id);
1532 let fn_decl = if let Some((expr, blk_id)) = expression {
1533 pointing_at_return_type =
1534 fcx.suggest_mismatched_types_on_tail(&mut err, expr, expected, found, blk_id);
1535 let parent = fcx.tcx.hir().get(parent_id);
1536 if let (Some(cond_expr), true, false) = (
1537 fcx.tcx.hir().get_if_cause(expr.hir_id),
1539 pointing_at_return_type,
1541 // If the block is from an external macro or try (`?`) desugaring, then
1542 // do not suggest adding a semicolon, because there's nowhere to put it.
1543 // See issues #81943 and #87051.
1545 cond_expr.span.desugaring_kind(),
1546 None | Some(DesugaringKind::WhileLoop)
1547 ) && !in_external_macro(fcx.tcx.sess, cond_expr.span)
1550 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar)
1553 err.span_label(cond_expr.span, "expected this to be `()`");
1554 if expr.can_have_side_effects() {
1555 fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1558 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1560 fcx.get_fn_decl(parent_id)
1563 if let Some((fn_decl, can_suggest)) = fn_decl {
1564 if expression.is_none() {
1565 pointing_at_return_type |= fcx.suggest_missing_return_type(
1571 fcx.tcx.hir().local_def_id_to_hir_id(fcx.tcx.hir().get_parent_item(id)),
1574 if !pointing_at_return_type {
1575 fn_output = Some(&fn_decl.output); // `impl Trait` return type
1579 let parent_id = fcx.tcx.hir().get_parent_item(id);
1580 let parent_item = fcx.tcx.hir().get_by_def_id(parent_id);
1582 if let (Some((expr, _)), Some((fn_decl, _, _))) =
1583 (expression, fcx.get_node_fn_decl(parent_item))
1585 fcx.suggest_missing_break_or_return_expr(
1592 fcx.tcx.hir().local_def_id_to_hir_id(parent_id),
1596 if let (Some(sp), Some(fn_output)) = (fcx.ret_coercion_span.get(), fn_output) {
1597 self.add_impl_trait_explanation(&mut err, cause, fcx, expected, sp, fn_output);
1602 fn add_impl_trait_explanation<'a>(
1604 err: &mut Diagnostic,
1605 cause: &ObligationCause<'tcx>,
1606 fcx: &FnCtxt<'a, 'tcx>,
1609 fn_output: &hir::FnRetTy<'_>,
1611 let return_sp = fn_output.span();
1612 err.span_label(return_sp, "expected because this return type...");
1615 format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1617 let impl_trait_msg = "for information on `impl Trait`, see \
1618 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1619 #returning-types-that-implement-traits>";
1620 let trait_obj_msg = "for information on trait objects, see \
1621 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1622 #using-trait-objects-that-allow-for-values-of-different-types>";
1623 err.note("to return `impl Trait`, all returned values must be of the same type");
1624 err.note(impl_trait_msg);
1629 .span_to_snippet(return_sp)
1630 .unwrap_or_else(|_| "dyn Trait".to_string());
1631 let mut snippet_iter = snippet.split_whitespace();
1632 let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1633 // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1634 let mut is_object_safe = false;
1635 if let hir::FnRetTy::Return(ty) = fn_output
1636 // Get the return type.
1637 && let hir::TyKind::OpaqueDef(..) = ty.kind
1639 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1640 // Get the `impl Trait`'s `DefId`.
1641 if let ty::Opaque(def_id, _) = ty.kind()
1642 // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1643 // get the `Trait`'s `DefId`.
1644 && let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1645 fcx.tcx.hir().expect_item(def_id.expect_local()).kind
1647 // Are of this `impl Trait`'s traits object safe?
1648 is_object_safe = bounds.iter().all(|bound| {
1651 .and_then(|t| t.trait_def_id())
1652 .map_or(false, |def_id| {
1653 fcx.tcx.object_safety_violations(def_id).is_empty()
1660 err.multipart_suggestion(
1661 "you could change the return type to be a boxed trait object",
1663 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
1664 (return_sp.shrink_to_hi(), ">".to_string()),
1666 Applicability::MachineApplicable,
1668 let sugg = [sp, cause.span]
1672 (sp.shrink_to_lo(), "Box::new(".to_string()),
1673 (sp.shrink_to_hi(), ")".to_string()),
1677 .collect::<Vec<_>>();
1678 err.multipart_suggestion(
1679 "if you change the return type to expect trait objects, box the returned \
1682 Applicability::MaybeIncorrect,
1686 "if the trait `{}` were object safe, you could return a boxed trait object",
1690 err.note(trait_obj_msg);
1692 err.help("you could instead create a new `enum` with a variant for each returned type");
1695 fn is_return_ty_unsized<'a>(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
1696 if let Some((fn_decl, _)) = fcx.get_fn_decl(blk_id)
1697 && let hir::FnRetTy::Return(ty) = fn_decl.output
1698 && let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty)
1699 && let ty::Dynamic(..) = ty.kind()
1706 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1707 if let Some(final_ty) = self.final_ty {
1710 // If we only had inputs that were of type `!` (or no
1711 // inputs at all), then the final type is `!`.
1712 assert_eq!(self.pushed, 0);
1718 /// Something that can be converted into an expression to which we can
1719 /// apply a coercion.
1720 pub trait AsCoercionSite {
1721 fn as_coercion_site(&self) -> &hir::Expr<'_>;
1724 impl AsCoercionSite for hir::Expr<'_> {
1725 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1730 impl<'a, T> AsCoercionSite for &'a T
1734 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1735 (**self).as_coercion_site()
1739 impl AsCoercionSite for ! {
1740 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1745 impl AsCoercionSite for hir::Arm<'_> {
1746 fn as_coercion_site(&self) -> &hir::Expr<'_> {