3 //! Under certain circumstances we will coerce from one type to another,
4 //! for example by auto-borrowing. This occurs in situations where the
5 //! compiler has a firm 'expected type' that was supplied from the user,
6 //! and where the actual type is similar to that expected type in purpose
7 //! but not in representation (so actual subtyping is inappropriate).
11 //! Note that if we are expecting a reference, we will *reborrow*
12 //! even if the argument provided was already a reference. This is
13 //! useful for freezing mut things (that is, when the expected type is &T
14 //! but you have &mut T) and also for avoiding the linearity
15 //! of mut things (when the expected is &mut T and you have &mut T). See
16 //! the various `src/test/ui/coerce/*.rs` tests for
17 //! examples of where this is useful.
21 //! When infering the generic arguments of functions, the argument
22 //! order is relevant, which can lead to the following edge case:
25 //! fn foo<T>(a: T, b: T) {
29 //! foo(&7i32, &mut 7i32);
30 //! // This compiles, as we first infer `T` to be `&i32`,
31 //! // and then coerce `&mut 7i32` to `&7i32`.
33 //! foo(&mut 7i32, &7i32);
34 //! // This does not compile, as we first infer `T` to be `&mut i32`
35 //! // and are then unable to coerce `&7i32` to `&mut i32`.
38 use crate::astconv::AstConv;
39 use crate::check::FnCtxt;
40 use rustc_errors::{struct_span_err, Applicability, Diagnostic, DiagnosticBuilder};
42 use rustc_hir::def_id::DefId;
43 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
44 use rustc_infer::infer::{Coercion, InferOk, InferResult};
45 use rustc_infer::traits::{Obligation, TraitEngine, TraitEngineExt};
46 use rustc_middle::lint::in_external_macro;
47 use rustc_middle::ty::adjustment::{
48 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast,
50 use rustc_middle::ty::error::TypeError;
51 use rustc_middle::ty::fold::TypeFoldable;
52 use rustc_middle::ty::relate::RelateResult;
53 use rustc_middle::ty::subst::SubstsRef;
54 use rustc_middle::ty::{self, ToPredicate, Ty, TypeAndMut};
55 use rustc_session::parse::feature_err;
56 use rustc_span::symbol::sym;
57 use rustc_span::{self, BytePos, DesugaringKind, Span};
58 use rustc_target::spec::abi::Abi;
59 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
60 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode};
62 use smallvec::{smallvec, SmallVec};
65 struct Coerce<'a, 'tcx> {
66 fcx: &'a FnCtxt<'a, 'tcx>,
67 cause: ObligationCause<'tcx>,
69 /// Determines whether or not allow_two_phase_borrow is set on any
70 /// autoref adjustments we create while coercing. We don't want to
71 /// allow deref coercions to create two-phase borrows, at least initially,
72 /// but we do need two-phase borrows for function argument reborrows.
73 /// See #47489 and #48598
74 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
75 allow_two_phase: AllowTwoPhase,
78 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
79 type Target = FnCtxt<'a, 'tcx>;
80 fn deref(&self) -> &Self::Target {
85 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
87 /// Coercing a mutable reference to an immutable works, while
88 /// coercing `&T` to `&mut T` should be forbidden.
89 fn coerce_mutbls<'tcx>(
90 from_mutbl: hir::Mutability,
91 to_mutbl: hir::Mutability,
92 ) -> RelateResult<'tcx, ()> {
93 match (from_mutbl, to_mutbl) {
94 (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not)
95 | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()),
96 (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability),
100 /// Do not require any adjustments, i.e. coerce `x -> x`.
101 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> {
105 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
106 move |target| vec![Adjustment { kind, target }]
109 /// This always returns `Ok(...)`.
111 adj: Vec<Adjustment<'tcx>>,
113 obligations: traits::PredicateObligations<'tcx>,
114 ) -> CoerceResult<'tcx> {
115 Ok(InferOk { value: (adj, target), obligations })
118 impl<'f, 'tcx> Coerce<'f, 'tcx> {
120 fcx: &'f FnCtxt<'f, 'tcx>,
121 cause: ObligationCause<'tcx>,
122 allow_two_phase: AllowTwoPhase,
124 Coerce { fcx, cause, allow_two_phase, use_lub: false }
127 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
128 debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
129 self.commit_if_ok(|_| {
131 self.at(&self.cause, self.fcx.param_env).lub(b, a)
133 self.at(&self.cause, self.fcx.param_env)
135 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
140 /// Unify two types (using sub or lub) and produce a specific coercion.
141 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx>
143 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
146 .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations))
149 #[instrument(skip(self))]
150 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
151 // First, remove any resolved type variables (at the top level, at least):
152 let a = self.shallow_resolve(a);
153 let b = self.shallow_resolve(b);
154 debug!("Coerce.tys({:?} => {:?})", a, b);
156 // Just ignore error types.
157 if a.references_error() || b.references_error() {
158 return success(vec![], self.fcx.tcx.ty_error(), vec![]);
161 // Coercing from `!` to any type is allowed:
163 return success(simple(Adjust::NeverToAny)(b), b, vec![]);
166 // Coercing *from* an unresolved inference variable means that
167 // we have no information about the source type. This will always
168 // ultimately fall back to some form of subtyping.
170 return self.coerce_from_inference_variable(a, b, identity);
173 // Consider coercing the subtype to a DST
175 // NOTE: this is wrapped in a `commit_if_ok` because it creates
176 // a "spurious" type variable, and we don't want to have that
177 // type variable in memory if the coercion fails.
178 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
181 debug!("coerce: unsize successful");
184 Err(TypeError::ObjectUnsafeCoercion(did)) => {
185 debug!("coerce: unsize not object safe");
186 return Err(TypeError::ObjectUnsafeCoercion(did));
189 debug!(?error, "coerce: unsize failed");
193 // Examine the supertype and consider auto-borrowing.
195 ty::RawPtr(mt_b) => {
196 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
198 ty::Ref(r_b, _, mutbl_b) => {
199 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
206 // Function items are coercible to any closure
207 // type; function pointers are not (that would
208 // require double indirection).
209 // Additionally, we permit coercion of function
210 // items to drop the unsafe qualifier.
211 self.coerce_from_fn_item(a, b)
214 // We permit coercion of fn pointers to drop the
216 self.coerce_from_fn_pointer(a, a_f, b)
218 ty::Closure(closure_def_id_a, substs_a) => {
219 // Non-capturing closures are coercible to
220 // function pointers or unsafe function pointers.
221 // It cannot convert closures that require unsafe.
222 self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b)
225 // Otherwise, just use unification rules.
226 self.unify_and(a, b, identity)
231 /// Coercing *from* an inference variable. In this case, we have no information
232 /// about the source type, so we can't really do a true coercion and we always
233 /// fall back to subtyping (`unify_and`).
234 fn coerce_from_inference_variable(
238 make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
239 ) -> CoerceResult<'tcx> {
240 debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
241 assert!(a.is_ty_var() && self.infcx.shallow_resolve(a) == a);
242 assert!(self.infcx.shallow_resolve(b) == b);
245 // Two unresolved type variables: create a `Coerce` predicate.
246 let target_ty = if self.use_lub {
247 self.infcx.next_ty_var(TypeVariableOrigin {
248 kind: TypeVariableOriginKind::LatticeVariable,
249 span: self.cause.span,
255 let mut obligations = Vec::with_capacity(2);
256 for &source_ty in &[a, b] {
257 if source_ty != target_ty {
258 obligations.push(Obligation::new(
261 ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate {
265 .to_predicate(self.tcx()),
271 "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
272 target_ty, obligations
274 let adjustments = make_adjustments(target_ty);
275 InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations })
277 // One unresolved type variable: just apply subtyping, we may be able
278 // to do something useful.
279 self.unify_and(a, b, make_adjustments)
283 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
284 /// To match `A` with `B`, autoderef will be performed,
285 /// calling `deref`/`deref_mut` where necessary.
286 fn coerce_borrowed_pointer(
290 r_b: ty::Region<'tcx>,
291 mutbl_b: hir::Mutability,
292 ) -> CoerceResult<'tcx> {
293 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
295 // If we have a parameter of type `&M T_a` and the value
296 // provided is `expr`, we will be adding an implicit borrow,
297 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
298 // to type check, we will construct the type that `&M*expr` would
301 let (r_a, mt_a) = match *a.kind() {
302 ty::Ref(r_a, ty, mutbl) => {
303 let mt_a = ty::TypeAndMut { ty, mutbl };
304 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
307 _ => return self.unify_and(a, b, identity),
310 let span = self.cause.span;
312 let mut first_error = None;
313 let mut r_borrow_var = None;
314 let mut autoderef = self.autoderef(span, a);
315 let mut found = None;
317 for (referent_ty, autoderefs) in autoderef.by_ref() {
319 // Don't let this pass, otherwise it would cause
320 // &T to autoref to &&T.
324 // At this point, we have deref'd `a` to `referent_ty`. So
325 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
326 // In the autoderef loop for `&'a mut Vec<T>`, we would get
329 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
330 // - `Vec<T>` -- 1 deref
331 // - `[T]` -- 2 deref
333 // At each point after the first callback, we want to
334 // check to see whether this would match out target type
335 // (`&'b mut [T]`) if we autoref'd it. We can't just
336 // compare the referent types, though, because we still
337 // have to consider the mutability. E.g., in the case
338 // we've been considering, we have an `&mut` reference, so
339 // the `T` in `[T]` needs to be unified with equality.
341 // Therefore, we construct reference types reflecting what
342 // the types will be after we do the final auto-ref and
343 // compare those. Note that this means we use the target
344 // mutability [1], since it may be that we are coercing
345 // from `&mut T` to `&U`.
347 // One fine point concerns the region that we use. We
348 // choose the region such that the region of the final
349 // type that results from `unify` will be the region we
350 // want for the autoref:
352 // - if in sub mode, that means we want to use `'b` (the
353 // region from the target reference) for both
354 // pointers [2]. This is because sub mode (somewhat
355 // arbitrarily) returns the subtype region. In the case
356 // where we are coercing to a target type, we know we
357 // want to use that target type region (`'b`) because --
358 // for the program to type-check -- it must be the
359 // smaller of the two.
360 // - One fine point. It may be surprising that we can
361 // use `'b` without relating `'a` and `'b`. The reason
362 // that this is ok is that what we produce is
363 // effectively a `&'b *x` expression (if you could
364 // annotate the region of a borrow), and regionck has
365 // code that adds edges from the region of a borrow
366 // (`'b`, here) into the regions in the borrowed
367 // expression (`*x`, here). (Search for "link".)
368 // - if in lub mode, things can get fairly complicated. The
369 // easiest thing is just to make a fresh
370 // region variable [4], which effectively means we defer
371 // the decision to region inference (and regionck, which will add
372 // some more edges to this variable). However, this can wind up
373 // creating a crippling number of variables in some cases --
374 // e.g., #32278 -- so we optimize one particular case [3].
375 // Let me try to explain with some examples:
376 // - The "running example" above represents the simple case,
377 // where we have one `&` reference at the outer level and
378 // ownership all the rest of the way down. In this case,
379 // we want `LUB('a, 'b)` as the resulting region.
380 // - However, if there are nested borrows, that region is
381 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
382 // `&'b T`. In this case, `'a` is actually irrelevant.
383 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
384 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
385 // (The errors actually show up in borrowck, typically, because
386 // this extra edge causes the region `'a` to be inferred to something
387 // too big, which then results in borrowck errors.)
388 // - We could track the innermost shared reference, but there is already
389 // code in regionck that has the job of creating links between
390 // the region of a borrow and the regions in the thing being
391 // borrowed (here, `'a` and `'x`), and it knows how to handle
392 // all the various cases. So instead we just make a region variable
393 // and let regionck figure it out.
394 let r = if !self.use_lub {
396 } else if autoderefs == 1 {
399 if r_borrow_var.is_none() {
400 // create var lazily, at most once
401 let coercion = Coercion(span);
402 let r = self.next_region_var(coercion);
403 r_borrow_var = Some(r); // [4] above
405 r_borrow_var.unwrap()
407 let derefd_ty_a = self.tcx.mk_ref(
411 mutbl: mutbl_b, // [1] above
414 match self.unify(derefd_ty_a, b) {
420 if first_error.is_none() {
421 first_error = Some(err);
427 // Extract type or return an error. We return the first error
428 // we got, which should be from relating the "base" type
429 // (e.g., in example above, the failure from relating `Vec<T>`
430 // to the target type), since that should be the least
432 let Some(InferOk { value: ty, mut obligations }) = found else {
433 let err = first_error.expect("coerce_borrowed_pointer had no error");
434 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
438 if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 {
439 // As a special case, if we would produce `&'a *x`, that's
440 // a total no-op. We end up with the type `&'a T` just as
441 // we started with. In that case, just skip it
442 // altogether. This is just an optimization.
444 // Note that for `&mut`, we DO want to reborrow --
445 // otherwise, this would be a move, which might be an
446 // error. For example `foo(self.x)` where `self` and
447 // `self.x` both have `&mut `type would be a move of
448 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
449 // which is a borrow.
450 assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U
451 return success(vec![], ty, obligations);
454 let InferOk { value: mut adjustments, obligations: o } =
455 self.adjust_steps_as_infer_ok(&autoderef);
456 obligations.extend(o);
457 obligations.extend(autoderef.into_obligations());
459 // Now apply the autoref. We have to extract the region out of
460 // the final ref type we got.
461 let ty::Ref(r_borrow, _, _) = ty.kind() else {
462 span_bug!(span, "expected a ref type, got {:?}", ty);
464 let mutbl = match mutbl_b {
465 hir::Mutability::Not => AutoBorrowMutability::Not,
466 hir::Mutability::Mut => {
467 AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase }
470 adjustments.push(Adjustment {
471 kind: Adjust::Borrow(AutoBorrow::Ref(*r_borrow, mutbl)),
475 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
477 success(adjustments, ty, obligations)
480 // &[T; n] or &mut [T; n] -> &[T]
481 // or &mut [T; n] -> &mut [T]
482 // or &Concrete -> &Trait, etc.
483 #[instrument(skip(self), level = "debug")]
484 fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> {
485 source = self.shallow_resolve(source);
486 target = self.shallow_resolve(target);
487 debug!(?source, ?target);
489 // These 'if' statements require some explanation.
490 // The `CoerceUnsized` trait is special - it is only
491 // possible to write `impl CoerceUnsized<B> for A` where
492 // A and B have 'matching' fields. This rules out the following
493 // two types of blanket impls:
495 // `impl<T> CoerceUnsized<T> for SomeType`
496 // `impl<T> CoerceUnsized<SomeType> for T`
498 // Both of these trigger a special `CoerceUnsized`-related error (E0376)
500 // We can take advantage of this fact to avoid performing unnecessary work.
501 // If either `source` or `target` is a type variable, then any applicable impl
502 // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
503 // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
506 // However, these are exactly the kinds of impls which are forbidden by
507 // the compiler! Therefore, we can be sure that coercion will always fail
508 // when either the source or target type is a type variable. This allows us
509 // to skip performing any trait selection, and immediately bail out.
510 if source.is_ty_var() {
511 debug!("coerce_unsized: source is a TyVar, bailing out");
512 return Err(TypeError::Mismatch);
514 if target.is_ty_var() {
515 debug!("coerce_unsized: target is a TyVar, bailing out");
516 return Err(TypeError::Mismatch);
520 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
521 let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
522 debug!("missing Unsize or CoerceUnsized traits");
523 return Err(TypeError::Mismatch);
526 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
527 // a DST unless we have to. This currently comes out in the wash since
528 // we can't unify [T] with U. But to properly support DST, we need to allow
529 // that, at which point we will need extra checks on the target here.
531 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
532 let reborrow = match (source.kind(), target.kind()) {
533 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
534 coerce_mutbls(mutbl_a, mutbl_b)?;
536 let coercion = Coercion(self.cause.span);
537 let r_borrow = self.next_region_var(coercion);
538 let mutbl = match mutbl_b {
539 hir::Mutability::Not => AutoBorrowMutability::Not,
540 hir::Mutability::Mut => AutoBorrowMutability::Mut {
541 // We don't allow two-phase borrows here, at least for initial
542 // implementation. If it happens that this coercion is a function argument,
543 // the reborrow in coerce_borrowed_ptr will pick it up.
544 allow_two_phase_borrow: AllowTwoPhase::No,
548 Adjustment { kind: Adjust::Deref(None), target: ty_a },
550 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
553 .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }),
557 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
558 coerce_mutbls(mt_a, mt_b)?;
561 Adjustment { kind: Adjust::Deref(None), target: ty_a },
563 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
564 target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
570 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
572 // Setup either a subtyping or a LUB relationship between
573 // the `CoerceUnsized` target type and the expected type.
574 // We only have the latter, so we use an inference variable
575 // for the former and let type inference do the rest.
576 let origin = TypeVariableOrigin {
577 kind: TypeVariableOriginKind::MiscVariable,
578 span: self.cause.span,
580 let coerce_target = self.next_ty_var(origin);
581 let mut coercion = self.unify_and(coerce_target, target, |target| {
582 let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target };
584 None => vec![unsize],
585 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
589 let mut selcx = traits::SelectionContext::new(self);
591 // Create an obligation for `Source: CoerceUnsized<Target>`.
592 let cause = ObligationCause::new(
595 ObligationCauseCode::Coercion { source, target },
598 // Use a FIFO queue for this custom fulfillment procedure.
600 // A Vec (or SmallVec) is not a natural choice for a queue. However,
601 // this code path is hot, and this queue usually has a max length of 1
602 // and almost never more than 3. By using a SmallVec we avoid an
603 // allocation, at the (very small) cost of (occasionally) having to
604 // shift subsequent elements down when removing the front element.
605 let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def(
612 &[coerce_target.into()]
615 let mut has_unsized_tuple_coercion = false;
616 let mut has_trait_upcasting_coercion = false;
618 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
619 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
620 // inference might unify those two inner type variables later.
621 let traits = [coerce_unsized_did, unsize_did];
622 while !queue.is_empty() {
623 let obligation = queue.remove(0);
624 debug!("coerce_unsized resolve step: {:?}", obligation);
625 let bound_predicate = obligation.predicate.kind();
626 let trait_pred = match bound_predicate.skip_binder() {
627 ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => {
628 if unsize_did == trait_pred.def_id() {
629 let self_ty = trait_pred.self_ty();
630 let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
631 if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) =
632 (self_ty.kind(), unsize_ty.kind())
634 if data_a.principal_def_id() != data_b.principal_def_id() {
635 debug!("coerce_unsized: found trait upcasting coercion");
636 has_trait_upcasting_coercion = true;
639 if let ty::Tuple(..) = unsize_ty.kind() {
640 debug!("coerce_unsized: found unsized tuple coercion");
641 has_unsized_tuple_coercion = true;
644 bound_predicate.rebind(trait_pred)
647 coercion.obligations.push(obligation);
651 match selcx.select(&obligation.with(trait_pred)) {
652 // Uncertain or unimplemented.
654 if trait_pred.def_id() == unsize_did {
655 let trait_pred = self.resolve_vars_if_possible(trait_pred);
656 let self_ty = trait_pred.skip_binder().self_ty();
657 let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty();
658 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
659 match (&self_ty.kind(), &unsize_ty.kind()) {
660 (ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
661 if self.type_var_is_sized(*v) =>
663 debug!("coerce_unsized: have sized infer {:?}", v);
664 coercion.obligations.push(obligation);
665 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
669 // Some other case for `$0: Unsize<Something>`. Note that we
670 // hit this case even if `Something` is a sized type, so just
671 // don't do the coercion.
672 debug!("coerce_unsized: ambiguous unsize");
673 return Err(TypeError::Mismatch);
677 debug!("coerce_unsized: early return - ambiguous");
678 return Err(TypeError::Mismatch);
681 Err(traits::Unimplemented) => {
682 debug!("coerce_unsized: early return - can't prove obligation");
683 return Err(TypeError::Mismatch);
686 // Object safety violations or miscellaneous.
688 self.report_selection_error(obligation.clone(), &obligation, &err, false);
689 // Treat this like an obligation and follow through
690 // with the unsizing - the lack of a coercion should
691 // be silent, as it causes a type mismatch later.
694 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
698 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
700 &self.tcx.sess.parse_sess,
701 sym::unsized_tuple_coercion,
703 "unsized tuple coercion is not stable enough for use and is subject to change",
708 if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting {
710 &self.tcx.sess.parse_sess,
711 sym::trait_upcasting,
713 "trait upcasting coercion is experimental",
721 fn coerce_from_safe_fn<F, G>(
724 fn_ty_a: ty::PolyFnSig<'tcx>,
728 ) -> CoerceResult<'tcx>
730 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
731 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
733 if let ty::FnPtr(fn_ty_b) = b.kind() {
734 if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
735 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
737 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
738 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 if 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));
792 let InferOk { value: a_sig, obligations: o1 } =
793 self.normalize_associated_types_in_as_infer_ok(self.cause.span, a_sig);
794 obligations.extend(o1);
796 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
797 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
804 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
805 target: a_fn_pointer,
808 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
813 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
816 obligations.extend(o2);
817 Ok(InferOk { value, obligations })
819 _ => self.unify_and(a, b, identity),
823 fn coerce_closure_to_fn(
826 closure_def_id_a: DefId,
827 substs_a: SubstsRef<'tcx>,
829 ) -> CoerceResult<'tcx> {
830 //! Attempts to coerce from the type of a non-capturing closure
831 //! into a function pointer.
834 let b = self.shallow_resolve(b);
837 // At this point we haven't done capture analysis, which means
838 // that the ClosureSubsts just contains an inference variable instead
839 // of tuple of captured types.
841 // All we care here is if any variable is being captured and not the exact paths,
842 // so we check `upvars_mentioned` for root variables being captured.
846 .upvars_mentioned(closure_def_id_a.expect_local())
847 .map_or(true, |u| u.is_empty()) =>
849 // We coerce the closure, which has fn type
850 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
852 // `fn(arg0,arg1,...) -> _`
854 // `unsafe fn(arg0,arg1,...) -> _`
855 let closure_sig = substs_a.as_closure().sig();
856 let unsafety = fn_ty.unsafety();
858 self.tcx.mk_fn_ptr(self.tcx.signature_unclosure(closure_sig, unsafety));
859 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
863 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
866 _ => self.unify_and(a, b, identity),
870 fn coerce_unsafe_ptr(
874 mutbl_b: hir::Mutability,
875 ) -> CoerceResult<'tcx> {
876 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
878 let (is_ref, mt_a) = match *a.kind() {
879 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
880 ty::RawPtr(mt) => (false, mt),
881 _ => return self.unify_and(a, b, identity),
883 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
885 // Check that the types which they point at are compatible.
886 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
887 // Although references and unsafe ptrs have the same
888 // representation, we still register an Adjust::DerefRef so that
889 // regionck knows that the region for `a` must be valid here.
891 self.unify_and(a_unsafe, b, |target| {
893 Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
894 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
897 } else if mt_a.mutbl != mutbl_b {
898 self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
900 self.unify_and(a_unsafe, b, identity)
905 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
906 /// Attempt to coerce an expression to a type, and return the
907 /// adjusted type of the expression, if successful.
908 /// Adjustments are only recorded if the coercion succeeded.
909 /// The expressions *must not* have any pre-existing adjustments.
912 expr: &hir::Expr<'_>,
915 allow_two_phase: AllowTwoPhase,
916 cause: Option<ObligationCause<'tcx>>,
917 ) -> RelateResult<'tcx, Ty<'tcx>> {
918 let source = self.resolve_vars_with_obligations(expr_ty);
919 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
922 cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
923 let coerce = Coerce::new(self, cause, allow_two_phase);
924 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
926 let (adjustments, _) = self.register_infer_ok_obligations(ok);
927 self.apply_adjustments(expr, adjustments);
928 Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target })
931 /// Same as `try_coerce()`, but without side-effects.
933 /// Returns false if the coercion creates any obligations that result in
935 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
936 let source = self.resolve_vars_with_obligations(expr_ty);
937 debug!("coercion::can_with_predicates({:?} -> {:?})", source, target);
939 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
940 // We don't ever need two-phase here since we throw out the result of the coercion
941 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
943 let Ok(ok) = coerce.coerce(source, target) else {
946 let mut fcx = traits::FulfillmentContext::new_in_snapshot();
947 fcx.register_predicate_obligations(self, ok.obligations);
948 fcx.select_where_possible(&self).is_empty()
952 /// Given a type and a target type, this function will calculate and return
953 /// how many dereference steps needed to achieve `expr_ty <: target`. If
954 /// it's not possible, return `None`.
955 pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
956 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
957 // We don't ever need two-phase here since we throw out the result of the coercion
958 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
960 .autoderef(rustc_span::DUMMY_SP, expr_ty)
961 .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
964 /// Given some expressions, their known unified type and another expression,
965 /// tries to unify the types, potentially inserting coercions on any of the
966 /// provided expressions and returns their LUB (aka "common supertype").
968 /// This is really an internal helper. From outside the coercion
969 /// module, you should instantiate a `CoerceMany` instance.
970 fn try_find_coercion_lub<E>(
972 cause: &ObligationCause<'tcx>,
977 ) -> RelateResult<'tcx, Ty<'tcx>>
981 let prev_ty = self.resolve_vars_with_obligations(prev_ty);
982 let new_ty = self.resolve_vars_with_obligations(new_ty);
984 "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
990 // The following check fixes #88097, where the compiler erroneously
991 // attempted to coerce a closure type to itself via a function pointer.
992 if prev_ty == new_ty {
996 // Special-case that coercion alone cannot handle:
997 // Function items or non-capturing closures of differing IDs or InternalSubsts.
998 let (a_sig, b_sig) = {
999 let is_capturing_closure = |ty| {
1000 if let &ty::Closure(closure_def_id, _substs) = ty {
1001 self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
1006 if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) {
1009 match (prev_ty.kind(), new_ty.kind()) {
1010 (ty::FnDef(..), ty::FnDef(..)) => {
1011 // Don't reify if the function types have a LUB, i.e., they
1012 // are the same function and their parameters have a LUB.
1014 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1016 // We have a LUB of prev_ty and new_ty, just return it.
1017 Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1019 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
1023 (ty::Closure(_, substs), ty::FnDef(..)) => {
1024 let b_sig = new_ty.fn_sig(self.tcx);
1027 .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
1028 (Some(a_sig), Some(b_sig))
1030 (ty::FnDef(..), ty::Closure(_, substs)) => {
1031 let a_sig = prev_ty.fn_sig(self.tcx);
1034 .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
1035 (Some(a_sig), Some(b_sig))
1037 (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => (
1038 Some(self.tcx.signature_unclosure(
1039 substs_a.as_closure().sig(),
1040 hir::Unsafety::Normal,
1042 Some(self.tcx.signature_unclosure(
1043 substs_b.as_closure().sig(),
1044 hir::Unsafety::Normal,
1051 if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
1052 // Intrinsics are not coercible to function pointers.
1053 if a_sig.abi() == Abi::RustIntrinsic
1054 || a_sig.abi() == Abi::PlatformIntrinsic
1055 || b_sig.abi() == Abi::RustIntrinsic
1056 || b_sig.abi() == Abi::PlatformIntrinsic
1058 return Err(TypeError::IntrinsicCast);
1060 // The signature must match.
1061 let a_sig = self.normalize_associated_types_in(new.span, a_sig);
1062 let b_sig = self.normalize_associated_types_in(new.span, b_sig);
1064 .at(cause, self.param_env)
1065 .trace(prev_ty, new_ty)
1067 .map(|ok| self.register_infer_ok_obligations(ok))?;
1069 // Reify both sides and return the reified fn pointer type.
1070 let fn_ptr = self.tcx.mk_fn_ptr(sig);
1071 let prev_adjustment = match prev_ty.kind() {
1072 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.unsafety())),
1073 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1074 _ => unreachable!(),
1076 let next_adjustment = match new_ty.kind() {
1077 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.unsafety())),
1078 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1079 _ => unreachable!(),
1081 for expr in exprs.iter().map(|e| e.as_coercion_site()) {
1082 self.apply_adjustments(
1084 vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1087 self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1091 // Configure a Coerce instance to compute the LUB.
1092 // We don't allow two-phase borrows on any autorefs this creates since we
1093 // probably aren't processing function arguments here and even if we were,
1094 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1096 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
1097 coerce.use_lub = true;
1099 // First try to coerce the new expression to the type of the previous ones,
1100 // but only if the new expression has no coercion already applied to it.
1101 let mut first_error = None;
1102 if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1103 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1106 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1107 self.apply_adjustments(new, adjustments);
1109 "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}",
1114 Err(e) => first_error = Some(e),
1118 // Then try to coerce the previous expressions to the type of the new one.
1119 // This requires ensuring there are no coercions applied to *any* of the
1120 // previous expressions, other than noop reborrows (ignoring lifetimes).
1122 let expr = expr.as_coercion_site();
1123 let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
1125 Adjustment { kind: Adjust::Deref(_), .. },
1126 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. },
1128 match *self.node_ty(expr.hir_id).kind() {
1129 ty::Ref(_, _, mt_orig) => {
1130 let mutbl_adj: hir::Mutability = mutbl_adj.into();
1131 // Reborrow that we can safely ignore, because
1132 // the next adjustment can only be a Deref
1133 // which will be merged into it.
1134 mutbl_adj == mt_orig
1139 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1145 "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1150 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1151 .map(|ok| self.register_infer_ok_obligations(ok));
1155 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1157 // Avoid giving strange errors on failed attempts.
1158 if let Some(e) = first_error {
1161 self.commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1162 .map(|ok| self.register_infer_ok_obligations(ok))
1167 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?}",
1170 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1172 let expr = expr.as_coercion_site();
1173 self.apply_adjustments(expr, adjustments.clone());
1181 /// CoerceMany encapsulates the pattern you should use when you have
1182 /// many expressions that are all getting coerced to a common
1183 /// type. This arises, for example, when you have a match (the result
1184 /// of each arm is coerced to a common type). It also arises in less
1185 /// obvious places, such as when you have many `break foo` expressions
1186 /// that target the same loop, or the various `return` expressions in
1189 /// The basic protocol is as follows:
1191 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1192 /// This will also serve as the "starting LUB". The expectation is
1193 /// that this type is something which all of the expressions *must*
1194 /// be coercible to. Use a fresh type variable if needed.
1195 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1196 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1197 /// unit. This happens for example if you have a `break` with no expression,
1198 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1199 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1200 /// from you so that you don't have to worry your pretty head about it.
1201 /// But if an error is reported, the final type will be `err`.
1202 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1203 /// previously coerced expressions.
1204 /// - When all done, invoke `complete()`. This will return the LUB of
1205 /// all your expressions.
1206 /// - WARNING: I don't believe this final type is guaranteed to be
1207 /// related to your initial `expected_ty` in any particular way,
1208 /// although it will typically be a subtype, so you should check it.
1209 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1210 /// previously coerced expressions.
1215 /// let mut coerce = CoerceMany::new(expected_ty);
1216 /// for expr in exprs {
1217 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1218 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1220 /// let final_ty = coerce.complete(fcx);
1222 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1223 expected_ty: Ty<'tcx>,
1224 final_ty: Option<Ty<'tcx>>,
1225 expressions: Expressions<'tcx, 'exprs, E>,
1229 /// The type of a `CoerceMany` that is storing up the expressions into
1230 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1231 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1233 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1234 Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1235 UpFront(&'exprs [E]),
1238 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1239 /// The usual case; collect the set of expressions dynamically.
1240 /// If the full set of coercion sites is known before hand,
1241 /// consider `with_coercion_sites()` instead to avoid allocation.
1242 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1243 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1246 /// As an optimization, you can create a `CoerceMany` with a
1247 /// pre-existing slice of expressions. In this case, you are
1248 /// expected to pass each element in the slice to `coerce(...)` in
1249 /// order. This is used with arrays in particular to avoid
1250 /// needlessly cloning the slice.
1251 pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1252 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1255 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1256 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1259 /// Returns the "expected type" with which this coercion was
1260 /// constructed. This represents the "downward propagated" type
1261 /// that was given to us at the start of typing whatever construct
1262 /// we are typing (e.g., the match expression).
1264 /// Typically, this is used as the expected type when
1265 /// type-checking each of the alternative expressions whose types
1266 /// we are trying to merge.
1267 pub fn expected_ty(&self) -> Ty<'tcx> {
1271 /// Returns the current "merged type", representing our best-guess
1272 /// at the LUB of the expressions we've seen so far (if any). This
1273 /// isn't *final* until you call `self.final()`, which will return
1274 /// the merged type.
1275 pub fn merged_ty(&self) -> Ty<'tcx> {
1276 self.final_ty.unwrap_or(self.expected_ty)
1279 /// Indicates that the value generated by `expression`, which is
1280 /// of type `expression_ty`, is one of the possibilities that we
1281 /// could coerce from. This will record `expression`, and later
1282 /// calls to `coerce` may come back and add adjustments and things
1286 fcx: &FnCtxt<'a, 'tcx>,
1287 cause: &ObligationCause<'tcx>,
1288 expression: &'tcx hir::Expr<'tcx>,
1289 expression_ty: Ty<'tcx>,
1291 self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1294 /// Indicates that one of the inputs is a "forced unit". This
1295 /// occurs in a case like `if foo { ... };`, where the missing else
1296 /// generates a "forced unit". Another example is a `loop { break;
1297 /// }`, where the `break` has no argument expression. We treat
1298 /// these cases slightly differently for error-reporting
1299 /// purposes. Note that these tend to correspond to cases where
1300 /// the `()` expression is implicit in the source, and hence we do
1301 /// not take an expression argument.
1303 /// The `augment_error` gives you a chance to extend the error
1304 /// message, in case any results (e.g., we use this to suggest
1305 /// removing a `;`).
1306 pub fn coerce_forced_unit<'a>(
1308 fcx: &FnCtxt<'a, 'tcx>,
1309 cause: &ObligationCause<'tcx>,
1310 augment_error: &mut dyn FnMut(&mut Diagnostic),
1311 label_unit_as_expected: bool,
1318 Some(augment_error),
1319 label_unit_as_expected,
1323 /// The inner coercion "engine". If `expression` is `None`, this
1324 /// is a forced-unit case, and hence `expression_ty` must be
1326 #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1327 crate fn coerce_inner<'a>(
1329 fcx: &FnCtxt<'a, 'tcx>,
1330 cause: &ObligationCause<'tcx>,
1331 expression: Option<&'tcx hir::Expr<'tcx>>,
1332 mut expression_ty: Ty<'tcx>,
1333 augment_error: Option<&mut dyn FnMut(&mut Diagnostic)>,
1334 label_expression_as_expected: bool,
1336 // Incorporate whatever type inference information we have
1337 // until now; in principle we might also want to process
1338 // pending obligations, but doing so should only improve
1339 // compatibility (hopefully that is true) by helping us
1340 // uncover never types better.
1341 if expression_ty.is_ty_var() {
1342 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1345 // If we see any error types, just propagate that error
1347 if expression_ty.references_error() || self.merged_ty().references_error() {
1348 self.final_ty = Some(fcx.tcx.ty_error());
1352 // Handle the actual type unification etc.
1353 let result = if let Some(expression) = expression {
1354 if self.pushed == 0 {
1355 // Special-case the first expression we are coercing.
1356 // To be honest, I'm not entirely sure why we do this.
1357 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1363 Some(cause.clone()),
1366 match self.expressions {
1367 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1374 Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1376 &coercion_sites[0..self.pushed],
1384 // this is a hack for cases where we default to `()` because
1385 // the expression etc has been omitted from the source. An
1386 // example is an `if let` without an else:
1388 // if let Some(x) = ... { }
1390 // we wind up with a second match arm that is like `_ =>
1391 // ()`. That is the case we are considering here. We take
1392 // a different path to get the right "expected, found"
1393 // message and so forth (and because we know that
1394 // `expression_ty` will be unit).
1396 // Another example is `break` with no argument expression.
1397 assert!(expression_ty.is_unit(), "if let hack without unit type");
1398 fcx.at(cause, fcx.param_env)
1399 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1401 fcx.register_infer_ok_obligations(infer_ok);
1408 self.final_ty = Some(v);
1409 if let Some(e) = expression {
1410 match self.expressions {
1411 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1412 Expressions::UpFront(coercion_sites) => {
1413 // if the user gave us an array to validate, check that we got
1414 // the next expression in the list, as expected
1416 coercion_sites[self.pushed].as_coercion_site().hir_id,
1424 Err(coercion_error) => {
1425 let (expected, found) = if label_expression_as_expected {
1426 // In the case where this is a "forced unit", like
1427 // `break`, we want to call the `()` "expected"
1428 // since it is implied by the syntax.
1429 // (Note: not all force-units work this way.)"
1430 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1432 // Otherwise, the "expected" type for error
1433 // reporting is the current unification type,
1434 // which is basically the LUB of the expressions
1435 // we've seen so far (combined with the expected
1437 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1441 let mut unsized_return = false;
1442 match *cause.code() {
1443 ObligationCauseCode::ReturnNoExpression => {
1444 err = struct_span_err!(
1448 "`return;` in a function whose return type is not `()`"
1450 err.span_label(cause.span, "return type is not `()`");
1452 ObligationCauseCode::BlockTailExpression(blk_id) => {
1453 let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1454 err = self.report_return_mismatched_types(
1458 coercion_error.clone(),
1461 expression.map(|expr| (expr, blk_id)),
1463 if !fcx.tcx.features().unsized_locals {
1464 unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1467 ObligationCauseCode::ReturnValue(id) => {
1468 err = self.report_return_mismatched_types(
1472 coercion_error.clone(),
1477 if !fcx.tcx.features().unsized_locals {
1478 let id = fcx.tcx.hir().get_parent_node(id);
1479 unsized_return = self.is_return_ty_unsized(fcx, id);
1483 err = fcx.report_mismatched_types(
1487 coercion_error.clone(),
1492 if let Some(augment_error) = augment_error {
1493 augment_error(&mut err);
1496 if let Some(expr) = expression {
1497 fcx.emit_coerce_suggestions(
1507 err.emit_unless(unsized_return);
1509 self.final_ty = Some(fcx.tcx.ty_error());
1514 fn report_return_mismatched_types<'a>(
1516 cause: &ObligationCause<'tcx>,
1519 ty_err: TypeError<'tcx>,
1520 fcx: &FnCtxt<'a, 'tcx>,
1522 expression: Option<(&'tcx hir::Expr<'tcx>, hir::HirId)>,
1523 ) -> DiagnosticBuilder<'a> {
1524 let mut err = fcx.report_mismatched_types(cause, expected, found, ty_err);
1526 let mut pointing_at_return_type = false;
1527 let mut fn_output = None;
1529 // Verify that this is a tail expression of a function, otherwise the
1530 // label pointing out the cause for the type coercion will be wrong
1531 // as prior return coercions would not be relevant (#57664).
1532 let parent_id = fcx.tcx.hir().get_parent_node(id);
1533 let fn_decl = if let Some((expr, blk_id)) = expression {
1534 pointing_at_return_type =
1535 fcx.suggest_mismatched_types_on_tail(&mut err, expr, expected, found, blk_id);
1536 let parent = fcx.tcx.hir().get(parent_id);
1537 if let (Some(cond_expr), true, false) = (
1538 fcx.tcx.hir().get_if_cause(expr.hir_id),
1540 pointing_at_return_type,
1542 // If the block is from an external macro or try (`?`) desugaring, then
1543 // do not suggest adding a semicolon, because there's nowhere to put it.
1544 // See issues #81943 and #87051.
1546 cond_expr.span.desugaring_kind(),
1547 None | Some(DesugaringKind::WhileLoop)
1548 ) && !in_external_macro(fcx.tcx.sess, cond_expr.span)
1551 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar)
1554 err.span_label(cond_expr.span, "expected this to be `()`");
1555 if expr.can_have_side_effects() {
1556 fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1560 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1562 fcx.get_fn_decl(parent_id)
1565 if let Some((fn_decl, can_suggest)) = fn_decl {
1566 if expression.is_none() {
1567 pointing_at_return_type |= fcx.suggest_missing_return_type(
1573 fcx.tcx.hir().local_def_id_to_hir_id(fcx.tcx.hir().get_parent_item(id)),
1576 if !pointing_at_return_type {
1577 fn_output = Some(&fn_decl.output); // `impl Trait` return type
1581 let parent_id = fcx.tcx.hir().get_parent_item(id);
1582 let parent_item = fcx.tcx.hir().get_by_def_id(parent_id);
1584 if let (Some((expr, _)), Some((fn_decl, _, _))) =
1585 (expression, fcx.get_node_fn_decl(parent_item))
1587 fcx.suggest_missing_break_or_return_expr(
1594 fcx.tcx.hir().local_def_id_to_hir_id(parent_id),
1598 if let (Some(sp), Some(fn_output)) = (fcx.ret_coercion_span.get(), fn_output) {
1599 self.add_impl_trait_explanation(&mut err, cause, fcx, expected, sp, fn_output);
1604 fn add_impl_trait_explanation<'a>(
1606 err: &mut Diagnostic,
1607 cause: &ObligationCause<'tcx>,
1608 fcx: &FnCtxt<'a, 'tcx>,
1611 fn_output: &hir::FnRetTy<'_>,
1613 let return_sp = fn_output.span();
1614 err.span_label(return_sp, "expected because this return type...");
1617 format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1619 let impl_trait_msg = "for information on `impl Trait`, see \
1620 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1621 #returning-types-that-implement-traits>";
1622 let trait_obj_msg = "for information on trait objects, see \
1623 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1624 #using-trait-objects-that-allow-for-values-of-different-types>";
1625 err.note("to return `impl Trait`, all returned values must be of the same type");
1626 err.note(impl_trait_msg);
1631 .span_to_snippet(return_sp)
1632 .unwrap_or_else(|_| "dyn Trait".to_string());
1633 let mut snippet_iter = snippet.split_whitespace();
1634 let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1635 // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1636 let mut is_object_safe = false;
1637 if let hir::FnRetTy::Return(ty) = fn_output {
1638 // Get the return type.
1639 if let hir::TyKind::OpaqueDef(..) = ty.kind {
1640 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1641 // Get the `impl Trait`'s `DefId`.
1642 if let ty::Opaque(def_id, _) = ty.kind() {
1643 // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1644 // get the `Trait`'s `DefId`.
1645 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1646 fcx.tcx.hir().expect_item(def_id.expect_local()).kind
1648 // Are of this `impl Trait`'s traits object safe?
1649 is_object_safe = bounds.iter().all(|bound| {
1652 .and_then(|t| t.trait_def_id())
1653 .map_or(false, |def_id| {
1654 fcx.tcx.object_safety_violations(def_id).is_empty()
1663 err.multipart_suggestion(
1664 "you could change the return type to be a boxed trait object",
1666 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
1667 (return_sp.shrink_to_hi(), ">".to_string()),
1669 Applicability::MachineApplicable,
1671 let sugg = [sp, cause.span]
1675 (sp.shrink_to_lo(), "Box::new(".to_string()),
1676 (sp.shrink_to_hi(), ")".to_string()),
1680 .collect::<Vec<_>>();
1681 err.multipart_suggestion(
1682 "if you change the return type to expect trait objects, box the returned \
1685 Applicability::MaybeIncorrect,
1689 "if the trait `{}` were object safe, you could return a boxed trait object",
1693 err.note(trait_obj_msg);
1695 err.help("you could instead create a new `enum` with a variant for each returned type");
1698 fn is_return_ty_unsized<'a>(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
1699 if let Some((fn_decl, _)) = fcx.get_fn_decl(blk_id) {
1700 if let hir::FnRetTy::Return(ty) = fn_decl.output {
1701 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1702 if let ty::Dynamic(..) = ty.kind() {
1710 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1711 if let Some(final_ty) = self.final_ty {
1714 // If we only had inputs that were of type `!` (or no
1715 // inputs at all), then the final type is `!`.
1716 assert_eq!(self.pushed, 0);
1722 /// Something that can be converted into an expression to which we can
1723 /// apply a coercion.
1724 pub trait AsCoercionSite {
1725 fn as_coercion_site(&self) -> &hir::Expr<'_>;
1728 impl AsCoercionSite for hir::Expr<'_> {
1729 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1734 impl<'a, T> AsCoercionSite for &'a T
1738 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1739 (**self).as_coercion_site()
1743 impl AsCoercionSite for ! {
1744 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1749 impl AsCoercionSite for hir::Arm<'_> {
1750 fn as_coercion_site(&self) -> &hir::Expr<'_> {