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 `tests/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:
24 //! ```ignore (illustrative)
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`.
40 struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan,
43 use rustc_hir::def_id::DefId;
44 use rustc_hir::intravisit::{self, Visitor};
46 use rustc_hir_analysis::astconv::AstConv;
47 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
48 use rustc_infer::infer::{Coercion, InferOk, InferResult};
49 use rustc_infer::traits::Obligation;
50 use rustc_middle::lint::in_external_macro;
51 use rustc_middle::ty::adjustment::{
52 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast,
54 use rustc_middle::ty::error::TypeError;
55 use rustc_middle::ty::relate::RelateResult;
56 use rustc_middle::ty::subst::SubstsRef;
57 use rustc_middle::ty::visit::TypeVisitable;
58 use rustc_middle::ty::{self, Ty, TypeAndMut};
59 use rustc_session::parse::feature_err;
60 use rustc_span::symbol::sym;
61 use rustc_span::{self, BytePos, DesugaringKind, Span};
62 use rustc_target::spec::abi::Abi;
63 use rustc_trait_selection::infer::InferCtxtExt as _;
64 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
65 use rustc_trait_selection::traits::{
66 self, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
69 use smallvec::{smallvec, SmallVec};
72 struct Coerce<'a, 'tcx> {
73 fcx: &'a FnCtxt<'a, 'tcx>,
74 cause: ObligationCause<'tcx>,
76 /// Determines whether or not allow_two_phase_borrow is set on any
77 /// autoref adjustments we create while coercing. We don't want to
78 /// allow deref coercions to create two-phase borrows, at least initially,
79 /// but we do need two-phase borrows for function argument reborrows.
80 /// See #47489 and #48598
81 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
82 allow_two_phase: AllowTwoPhase,
85 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
86 type Target = FnCtxt<'a, 'tcx>;
87 fn deref(&self) -> &Self::Target {
92 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
94 struct CollectRetsVisitor<'tcx> {
95 ret_exprs: Vec<&'tcx hir::Expr<'tcx>>,
98 impl<'tcx> Visitor<'tcx> for CollectRetsVisitor<'tcx> {
99 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
100 if let hir::ExprKind::Ret(_) = expr.kind {
101 self.ret_exprs.push(expr);
103 intravisit::walk_expr(self, expr);
107 /// Coercing a mutable reference to an immutable works, while
108 /// coercing `&T` to `&mut T` should be forbidden.
109 fn coerce_mutbls<'tcx>(
110 from_mutbl: hir::Mutability,
111 to_mutbl: hir::Mutability,
112 ) -> RelateResult<'tcx, ()> {
113 if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
116 /// Do not require any adjustments, i.e. coerce `x -> x`.
117 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> {
121 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'_>> {
122 move |target| vec![Adjustment { kind, target }]
125 /// This always returns `Ok(...)`.
127 adj: Vec<Adjustment<'tcx>>,
129 obligations: traits::PredicateObligations<'tcx>,
130 ) -> CoerceResult<'tcx> {
131 Ok(InferOk { value: (adj, target), obligations })
134 impl<'f, 'tcx> Coerce<'f, 'tcx> {
136 fcx: &'f FnCtxt<'f, 'tcx>,
137 cause: ObligationCause<'tcx>,
138 allow_two_phase: AllowTwoPhase,
140 Coerce { fcx, cause, allow_two_phase, use_lub: false }
143 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
144 debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
145 self.commit_if_ok(|_| {
147 self.at(&self.cause, self.fcx.param_env).lub(b, a)
149 self.at(&self.cause, self.fcx.param_env)
151 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
156 /// Unify two types (using sub or lub) and produce a specific coercion.
157 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx>
159 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
162 .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations))
165 #[instrument(skip(self))]
166 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
167 // First, remove any resolved type variables (at the top level, at least):
168 let a = self.shallow_resolve(a);
169 let b = self.shallow_resolve(b);
170 debug!("Coerce.tys({:?} => {:?})", a, b);
172 // Just ignore error types.
173 if a.references_error() || b.references_error() {
174 // Best-effort try to unify these types -- we're already on the error path,
175 // so this will have the side-effect of making sure we have no ambiguities
176 // due to `[type error]` and `_` not coercing together.
177 let _ = self.commit_if_ok(|_| self.at(&self.cause, self.param_env).eq(a, b));
178 return success(vec![], self.fcx.tcx.ty_error(), vec![]);
181 // Coercing from `!` to any type is allowed:
183 return success(simple(Adjust::NeverToAny)(b), b, vec![]);
186 // Coercing *from* an unresolved inference variable means that
187 // we have no information about the source type. This will always
188 // ultimately fall back to some form of subtyping.
190 return self.coerce_from_inference_variable(a, b, identity);
193 // Consider coercing the subtype to a DST
195 // NOTE: this is wrapped in a `commit_if_ok` because it creates
196 // a "spurious" type variable, and we don't want to have that
197 // type variable in memory if the coercion fails.
198 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
201 debug!("coerce: unsize successful");
205 debug!(?error, "coerce: unsize failed");
209 // Examine the supertype and consider auto-borrowing.
211 ty::RawPtr(mt_b) => {
212 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
214 ty::Ref(r_b, _, mutbl_b) => {
215 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
217 ty::Dynamic(predicates, region, ty::DynStar) if self.tcx.features().dyn_star => {
218 return self.coerce_dyn_star(a, b, predicates, region);
225 // Function items are coercible to any closure
226 // type; function pointers are not (that would
227 // require double indirection).
228 // Additionally, we permit coercion of function
229 // items to drop the unsafe qualifier.
230 self.coerce_from_fn_item(a, b)
233 // We permit coercion of fn pointers to drop the
235 self.coerce_from_fn_pointer(a, a_f, b)
237 ty::Closure(closure_def_id_a, substs_a) => {
238 // Non-capturing closures are coercible to
239 // function pointers or unsafe function pointers.
240 // It cannot convert closures that require unsafe.
241 self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b)
244 // Otherwise, just use unification rules.
245 self.unify_and(a, b, identity)
250 /// Coercing *from* an inference variable. In this case, we have no information
251 /// about the source type, so we can't really do a true coercion and we always
252 /// fall back to subtyping (`unify_and`).
253 fn coerce_from_inference_variable(
257 make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
258 ) -> CoerceResult<'tcx> {
259 debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
260 assert!(a.is_ty_var() && self.shallow_resolve(a) == a);
261 assert!(self.shallow_resolve(b) == b);
264 // Two unresolved type variables: create a `Coerce` predicate.
265 let target_ty = if self.use_lub {
266 self.next_ty_var(TypeVariableOrigin {
267 kind: TypeVariableOriginKind::LatticeVariable,
268 span: self.cause.span,
274 let mut obligations = Vec::with_capacity(2);
275 for &source_ty in &[a, b] {
276 if source_ty != target_ty {
277 obligations.push(Obligation::new(
281 ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate {
290 "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
291 target_ty, obligations
293 let adjustments = make_adjustments(target_ty);
294 InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations })
296 // One unresolved type variable: just apply subtyping, we may be able
297 // to do something useful.
298 self.unify_and(a, b, make_adjustments)
302 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
303 /// To match `A` with `B`, autoderef will be performed,
304 /// calling `deref`/`deref_mut` where necessary.
305 fn coerce_borrowed_pointer(
309 r_b: ty::Region<'tcx>,
310 mutbl_b: hir::Mutability,
311 ) -> CoerceResult<'tcx> {
312 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
314 // If we have a parameter of type `&M T_a` and the value
315 // provided is `expr`, we will be adding an implicit borrow,
316 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
317 // to type check, we will construct the type that `&M*expr` would
320 let (r_a, mt_a) = match *a.kind() {
321 ty::Ref(r_a, ty, mutbl) => {
322 let mt_a = ty::TypeAndMut { ty, mutbl };
323 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
326 _ => return self.unify_and(a, b, identity),
329 let span = self.cause.span;
331 let mut first_error = None;
332 let mut r_borrow_var = None;
333 let mut autoderef = self.autoderef(span, a);
334 let mut found = None;
336 for (referent_ty, autoderefs) in autoderef.by_ref() {
338 // Don't let this pass, otherwise it would cause
339 // &T to autoref to &&T.
343 // At this point, we have deref'd `a` to `referent_ty`. So
344 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
345 // In the autoderef loop for `&'a mut Vec<T>`, we would get
348 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
349 // - `Vec<T>` -- 1 deref
350 // - `[T]` -- 2 deref
352 // At each point after the first callback, we want to
353 // check to see whether this would match out target type
354 // (`&'b mut [T]`) if we autoref'd it. We can't just
355 // compare the referent types, though, because we still
356 // have to consider the mutability. E.g., in the case
357 // we've been considering, we have an `&mut` reference, so
358 // the `T` in `[T]` needs to be unified with equality.
360 // Therefore, we construct reference types reflecting what
361 // the types will be after we do the final auto-ref and
362 // compare those. Note that this means we use the target
363 // mutability [1], since it may be that we are coercing
364 // from `&mut T` to `&U`.
366 // One fine point concerns the region that we use. We
367 // choose the region such that the region of the final
368 // type that results from `unify` will be the region we
369 // want for the autoref:
371 // - if in sub mode, that means we want to use `'b` (the
372 // region from the target reference) for both
373 // pointers [2]. This is because sub mode (somewhat
374 // arbitrarily) returns the subtype region. In the case
375 // where we are coercing to a target type, we know we
376 // want to use that target type region (`'b`) because --
377 // for the program to type-check -- it must be the
378 // smaller of the two.
379 // - One fine point. It may be surprising that we can
380 // use `'b` without relating `'a` and `'b`. The reason
381 // that this is ok is that what we produce is
382 // effectively a `&'b *x` expression (if you could
383 // annotate the region of a borrow), and regionck has
384 // code that adds edges from the region of a borrow
385 // (`'b`, here) into the regions in the borrowed
386 // expression (`*x`, here). (Search for "link".)
387 // - if in lub mode, things can get fairly complicated. The
388 // easiest thing is just to make a fresh
389 // region variable [4], which effectively means we defer
390 // the decision to region inference (and regionck, which will add
391 // some more edges to this variable). However, this can wind up
392 // creating a crippling number of variables in some cases --
393 // e.g., #32278 -- so we optimize one particular case [3].
394 // Let me try to explain with some examples:
395 // - The "running example" above represents the simple case,
396 // where we have one `&` reference at the outer level and
397 // ownership all the rest of the way down. In this case,
398 // we want `LUB('a, 'b)` as the resulting region.
399 // - However, if there are nested borrows, that region is
400 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
401 // `&'b T`. In this case, `'a` is actually irrelevant.
402 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
403 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
404 // (The errors actually show up in borrowck, typically, because
405 // this extra edge causes the region `'a` to be inferred to something
406 // too big, which then results in borrowck errors.)
407 // - We could track the innermost shared reference, but there is already
408 // code in regionck that has the job of creating links between
409 // the region of a borrow and the regions in the thing being
410 // borrowed (here, `'a` and `'x`), and it knows how to handle
411 // all the various cases. So instead we just make a region variable
412 // and let regionck figure it out.
413 let r = if !self.use_lub {
415 } else if autoderefs == 1 {
418 if r_borrow_var.is_none() {
419 // create var lazily, at most once
420 let coercion = Coercion(span);
421 let r = self.next_region_var(coercion);
422 r_borrow_var = Some(r); // [4] above
424 r_borrow_var.unwrap()
426 let derefd_ty_a = self.tcx.mk_ref(
430 mutbl: mutbl_b, // [1] above
433 match self.unify(derefd_ty_a, b) {
439 if first_error.is_none() {
440 first_error = Some(err);
446 // Extract type or return an error. We return the first error
447 // we got, which should be from relating the "base" type
448 // (e.g., in example above, the failure from relating `Vec<T>`
449 // to the target type), since that should be the least
451 let Some(InferOk { value: ty, mut obligations }) = found else {
452 let err = first_error.expect("coerce_borrowed_pointer had no error");
453 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
457 if ty == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
458 // As a special case, if we would produce `&'a *x`, that's
459 // a total no-op. We end up with the type `&'a T` just as
460 // we started with. In that case, just skip it
461 // altogether. This is just an optimization.
463 // Note that for `&mut`, we DO want to reborrow --
464 // otherwise, this would be a move, which might be an
465 // error. For example `foo(self.x)` where `self` and
466 // `self.x` both have `&mut `type would be a move of
467 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
468 // which is a borrow.
469 assert!(mutbl_b.is_not()); // can only coerce &T -> &U
470 return success(vec![], ty, obligations);
473 let InferOk { value: mut adjustments, obligations: o } =
474 self.adjust_steps_as_infer_ok(&autoderef);
475 obligations.extend(o);
476 obligations.extend(autoderef.into_obligations());
478 // Now apply the autoref. We have to extract the region out of
479 // the final ref type we got.
480 let ty::Ref(r_borrow, _, _) = ty.kind() else {
481 span_bug!(span, "expected a ref type, got {:?}", ty);
483 let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
484 adjustments.push(Adjustment {
485 kind: Adjust::Borrow(AutoBorrow::Ref(*r_borrow, mutbl)),
489 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
491 success(adjustments, ty, obligations)
494 // &[T; n] or &mut [T; n] -> &[T]
495 // or &mut [T; n] -> &mut [T]
496 // or &Concrete -> &Trait, etc.
497 #[instrument(skip(self), level = "debug")]
498 fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> {
499 source = self.shallow_resolve(source);
500 target = self.shallow_resolve(target);
501 debug!(?source, ?target);
503 // We don't apply any coercions incase either the source or target
504 // aren't sufficiently well known but tend to instead just equate
506 if source.is_ty_var() {
507 debug!("coerce_unsized: source is a TyVar, bailing out");
508 return Err(TypeError::Mismatch);
510 if target.is_ty_var() {
511 debug!("coerce_unsized: target is a TyVar, bailing out");
512 return Err(TypeError::Mismatch);
516 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
517 let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
518 debug!("missing Unsize or CoerceUnsized traits");
519 return Err(TypeError::Mismatch);
522 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
523 // a DST unless we have to. This currently comes out in the wash since
524 // we can't unify [T] with U. But to properly support DST, we need to allow
525 // that, at which point we will need extra checks on the target here.
527 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
528 let reborrow = match (source.kind(), target.kind()) {
529 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
530 coerce_mutbls(mutbl_a, mutbl_b)?;
532 let coercion = Coercion(self.cause.span);
533 let r_borrow = self.next_region_var(coercion);
535 // We don't allow two-phase borrows here, at least for initial
536 // implementation. If it happens that this coercion is a function argument,
537 // the reborrow in coerce_borrowed_ptr will pick it up.
538 let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
541 Adjustment { kind: Adjust::Deref(None), target: ty_a },
543 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
546 .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }),
550 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
551 coerce_mutbls(mt_a, mt_b)?;
554 Adjustment { kind: Adjust::Deref(None), target: ty_a },
556 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
557 target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
563 let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
565 // Setup either a subtyping or a LUB relationship between
566 // the `CoerceUnsized` target type and the expected type.
567 // We only have the latter, so we use an inference variable
568 // for the former and let type inference do the rest.
569 let origin = TypeVariableOrigin {
570 kind: TypeVariableOriginKind::MiscVariable,
571 span: self.cause.span,
573 let coerce_target = self.next_ty_var(origin);
574 let mut coercion = self.unify_and(coerce_target, target, |target| {
575 let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target };
577 None => vec![unsize],
578 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
582 let mut selcx = traits::SelectionContext::new(self);
584 // Create an obligation for `Source: CoerceUnsized<Target>`.
585 let cause = ObligationCause::new(
588 ObligationCauseCode::Coercion { source, target },
591 // Use a FIFO queue for this custom fulfillment procedure.
593 // A Vec (or SmallVec) is not a natural choice for a queue. However,
594 // this code path is hot, and this queue usually has a max length of 1
595 // and almost never more than 3. By using a SmallVec we avoid an
596 // allocation, at the (very small) cost of (occasionally) having to
597 // shift subsequent elements down when removing the front element.
598 let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def(
604 [coerce_source, coerce_target]
607 let mut has_unsized_tuple_coercion = false;
608 let mut has_trait_upcasting_coercion = None;
610 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
611 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
612 // inference might unify those two inner type variables later.
613 let traits = [coerce_unsized_did, unsize_did];
614 while !queue.is_empty() {
615 let obligation = queue.remove(0);
616 debug!("coerce_unsized resolve step: {:?}", obligation);
617 let bound_predicate = obligation.predicate.kind();
618 let trait_pred = match bound_predicate.skip_binder() {
619 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
620 if traits.contains(&trait_pred.def_id()) =>
622 if unsize_did == trait_pred.def_id() {
623 let self_ty = trait_pred.self_ty();
624 let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
625 if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) =
626 (self_ty.kind(), unsize_ty.kind())
627 && data_a.principal_def_id() != data_b.principal_def_id()
629 debug!("coerce_unsized: found trait upcasting coercion");
630 has_trait_upcasting_coercion = Some((self_ty, unsize_ty));
632 if let ty::Tuple(..) = unsize_ty.kind() {
633 debug!("coerce_unsized: found unsized tuple coercion");
634 has_unsized_tuple_coercion = true;
637 bound_predicate.rebind(trait_pred)
640 coercion.obligations.push(obligation);
644 match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
645 // Uncertain or unimplemented.
647 if trait_pred.def_id() == unsize_did {
648 let trait_pred = self.resolve_vars_if_possible(trait_pred);
649 let self_ty = trait_pred.skip_binder().self_ty();
650 let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty();
651 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
652 match (&self_ty.kind(), &unsize_ty.kind()) {
653 (ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
654 if self.type_var_is_sized(*v) =>
656 debug!("coerce_unsized: have sized infer {:?}", v);
657 coercion.obligations.push(obligation);
658 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
662 // Some other case for `$0: Unsize<Something>`. Note that we
663 // hit this case even if `Something` is a sized type, so just
664 // don't do the coercion.
665 debug!("coerce_unsized: ambiguous unsize");
666 return Err(TypeError::Mismatch);
670 debug!("coerce_unsized: early return - ambiguous");
671 return Err(TypeError::Mismatch);
674 Err(traits::Unimplemented) => {
675 debug!("coerce_unsized: early return - can't prove obligation");
676 return Err(TypeError::Mismatch);
679 // Object safety violations or miscellaneous.
681 self.err_ctxt().report_selection_error(obligation.clone(), &obligation, &err);
682 // Treat this like an obligation and follow through
683 // with the unsizing - the lack of a coercion should
684 // be silent, as it causes a type mismatch later.
687 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
691 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
693 &self.tcx.sess.parse_sess,
694 sym::unsized_tuple_coercion,
696 "unsized tuple coercion is not stable enough for use and is subject to change",
701 if let Some((sub, sup)) = has_trait_upcasting_coercion
702 && !self.tcx().features().trait_upcasting
704 // Renders better when we erase regions, since they're not really the point here.
705 let (sub, sup) = self.tcx.erase_regions((sub, sup));
706 let mut err = feature_err(
707 &self.tcx.sess.parse_sess,
708 sym::trait_upcasting,
710 &format!("cannot cast `{sub}` to `{sup}`, trait upcasting coercion is experimental"),
712 err.note(&format!("required when coercing `{source}` into `{target}`"));
723 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
724 b_region: ty::Region<'tcx>,
725 ) -> CoerceResult<'tcx> {
726 if !self.tcx.features().dyn_star {
727 return Err(TypeError::Mismatch);
730 if let ty::Dynamic(a_data, _, _) = a.kind()
731 && let ty::Dynamic(b_data, _, _) = b.kind()
732 && a_data.principal_def_id() == b_data.principal_def_id()
734 return self.unify_and(a, b, |_| vec![]);
737 // Check the obligations of the cast -- for example, when casting
738 // `usize` to `dyn* Clone + 'static`:
739 let mut obligations: Vec<_> = predicates
742 // For each existential predicate (e.g., `?Self: Clone`) substitute
743 // the type of the expression (e.g., `usize` in our example above)
744 // and then require that the resulting predicate (e.g., `usize: Clone`)
746 let predicate = predicate.with_self_ty(self.tcx, a);
747 Obligation::new(self.tcx, self.cause.clone(), self.param_env, predicate)
750 // Enforce the region bound (e.g., `usize: 'static`, in our example).
755 ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::TypeOutlives(
756 ty::OutlivesPredicate(a, b_region),
762 // Enforce that the type is `usize`/pointer-sized.
763 obligations.push(Obligation::new(
768 self.tcx.at(self.cause.span).mk_trait_ref(hir::LangItem::PointerSized, [a]),
773 value: (vec![Adjustment { kind: Adjust::DynStar, target: b }], b),
778 fn coerce_from_safe_fn<F, G>(
781 fn_ty_a: ty::PolyFnSig<'tcx>,
785 ) -> CoerceResult<'tcx>
787 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
788 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
790 self.commit_if_ok(|snapshot| {
791 let result = if let ty::FnPtr(fn_ty_b) = b.kind()
792 && let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
793 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
795 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
796 self.unify_and(unsafe_a, b, to_unsafe)
798 self.unify_and(a, b, normal)
801 // FIXME(#73154): This is a hack. Currently LUB can generate
802 // unsolvable constraints. Additionally, it returns `a`
803 // unconditionally, even when the "LUB" is `b`. In the future, we
804 // want the coerced type to be the actual supertype of these two,
805 // but for now, we want to just error to ensure we don't lock
806 // ourselves into a specific behavior with NLL.
807 self.leak_check(false, snapshot)?;
813 fn coerce_from_fn_pointer(
816 fn_ty_a: ty::PolyFnSig<'tcx>,
818 ) -> CoerceResult<'tcx> {
819 //! Attempts to coerce from the type of a Rust function item
820 //! into a closure or a `proc`.
823 let b = self.shallow_resolve(b);
824 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
826 self.coerce_from_safe_fn(
830 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
835 fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
836 //! Attempts to coerce from the type of a Rust function item
837 //! into a closure or a `proc`.
839 let b = self.shallow_resolve(b);
840 let InferOk { value: b, mut obligations } =
841 self.at(&self.cause, self.param_env).normalize(b);
842 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
845 ty::FnPtr(b_sig) => {
846 let a_sig = a.fn_sig(self.tcx);
847 if let ty::FnDef(def_id, _) = *a.kind() {
848 // Intrinsics are not coercible to function pointers
849 if self.tcx.is_intrinsic(def_id) {
850 return Err(TypeError::IntrinsicCast);
853 // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
855 if b_sig.unsafety() == hir::Unsafety::Normal
856 && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
858 return Err(TypeError::TargetFeatureCast(def_id));
862 let InferOk { value: a_sig, obligations: o1 } =
863 self.at(&self.cause, self.param_env).normalize(a_sig);
864 obligations.extend(o1);
866 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
867 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
874 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
875 target: a_fn_pointer,
878 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
883 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
886 obligations.extend(o2);
887 Ok(InferOk { value, obligations })
889 _ => self.unify_and(a, b, identity),
893 fn coerce_closure_to_fn(
896 closure_def_id_a: DefId,
897 substs_a: SubstsRef<'tcx>,
899 ) -> CoerceResult<'tcx> {
900 //! Attempts to coerce from the type of a non-capturing closure
901 //! into a function pointer.
904 let b = self.shallow_resolve(b);
907 // At this point we haven't done capture analysis, which means
908 // that the ClosureSubsts just contains an inference variable instead
909 // of tuple of captured types.
911 // All we care here is if any variable is being captured and not the exact paths,
912 // so we check `upvars_mentioned` for root variables being captured.
916 .upvars_mentioned(closure_def_id_a.expect_local())
917 .map_or(true, |u| u.is_empty()) =>
919 // We coerce the closure, which has fn type
920 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
922 // `fn(arg0,arg1,...) -> _`
924 // `unsafe fn(arg0,arg1,...) -> _`
925 let closure_sig = substs_a.as_closure().sig();
926 let unsafety = fn_ty.unsafety();
928 self.tcx.mk_fn_ptr(self.tcx.signature_unclosure(closure_sig, unsafety));
929 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
933 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
936 _ => self.unify_and(a, b, identity),
940 fn coerce_unsafe_ptr(
944 mutbl_b: hir::Mutability,
945 ) -> CoerceResult<'tcx> {
946 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
948 let (is_ref, mt_a) = match *a.kind() {
949 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
950 ty::RawPtr(mt) => (false, mt),
951 _ => return self.unify_and(a, b, identity),
953 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
955 // Check that the types which they point at are compatible.
956 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
957 // Although references and unsafe ptrs have the same
958 // representation, we still register an Adjust::DerefRef so that
959 // regionck knows that the region for `a` must be valid here.
961 self.unify_and(a_unsafe, b, |target| {
963 Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
964 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
967 } else if mt_a.mutbl != mutbl_b {
968 self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
970 self.unify_and(a_unsafe, b, identity)
975 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
976 /// Attempt to coerce an expression to a type, and return the
977 /// adjusted type of the expression, if successful.
978 /// Adjustments are only recorded if the coercion succeeded.
979 /// The expressions *must not* have any pre-existing adjustments.
982 expr: &hir::Expr<'_>,
985 allow_two_phase: AllowTwoPhase,
986 cause: Option<ObligationCause<'tcx>>,
987 ) -> RelateResult<'tcx, Ty<'tcx>> {
988 let source = self.resolve_vars_with_obligations(expr_ty);
989 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
992 cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
993 let coerce = Coerce::new(self, cause, allow_two_phase);
994 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
996 let (adjustments, _) = self.register_infer_ok_obligations(ok);
997 self.apply_adjustments(expr, adjustments);
998 Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target })
1001 /// Same as `try_coerce()`, but without side-effects.
1003 /// Returns false if the coercion creates any obligations that result in
1005 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
1006 let source = self.resolve_vars_with_obligations(expr_ty);
1007 debug!("coercion::can_with_predicates({:?} -> {:?})", source, target);
1009 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
1010 // We don't ever need two-phase here since we throw out the result of the coercion
1011 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
1013 let Ok(ok) = coerce.coerce(source, target) else {
1016 let ocx = ObligationCtxt::new_in_snapshot(self);
1017 ocx.register_obligations(ok.obligations);
1018 ocx.select_where_possible().is_empty()
1022 /// Given a type and a target type, this function will calculate and return
1023 /// how many dereference steps needed to achieve `expr_ty <: target`. If
1024 /// it's not possible, return `None`.
1025 pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
1026 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
1027 // We don't ever need two-phase here since we throw out the result of the coercion
1028 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
1030 .autoderef(rustc_span::DUMMY_SP, expr_ty)
1031 .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
1034 /// Given a type, this function will calculate and return the type given
1035 /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1037 /// This function is for diagnostics only, since it does not register
1038 /// trait or region sub-obligations. (presumably we could, but it's not
1039 /// particularly important for diagnostics...)
1040 pub fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1041 self.autoderef(rustc_span::DUMMY_SP, expr_ty).nth(1).and_then(|(deref_ty, _)| {
1043 .type_implements_trait(
1044 self.tcx.lang_items().deref_mut_trait()?,
1053 /// Given some expressions, their known unified type and another expression,
1054 /// tries to unify the types, potentially inserting coercions on any of the
1055 /// provided expressions and returns their LUB (aka "common supertype").
1057 /// This is really an internal helper. From outside the coercion
1058 /// module, you should instantiate a `CoerceMany` instance.
1059 fn try_find_coercion_lub<E>(
1061 cause: &ObligationCause<'tcx>,
1064 new: &hir::Expr<'_>,
1066 ) -> RelateResult<'tcx, Ty<'tcx>>
1070 let prev_ty = self.resolve_vars_with_obligations(prev_ty);
1071 let new_ty = self.resolve_vars_with_obligations(new_ty);
1073 "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1079 // The following check fixes #88097, where the compiler erroneously
1080 // attempted to coerce a closure type to itself via a function pointer.
1081 if prev_ty == new_ty {
1085 // Special-case that coercion alone cannot handle:
1086 // Function items or non-capturing closures of differing IDs or InternalSubsts.
1087 let (a_sig, b_sig) = {
1088 let is_capturing_closure = |ty: Ty<'tcx>| {
1089 if let &ty::Closure(closure_def_id, _substs) = ty.kind() {
1090 self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
1095 if is_capturing_closure(prev_ty) || is_capturing_closure(new_ty) {
1098 match (prev_ty.kind(), new_ty.kind()) {
1099 (ty::FnDef(..), ty::FnDef(..)) => {
1100 // Don't reify if the function types have a LUB, i.e., they
1101 // are the same function and their parameters have a LUB.
1103 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1105 // We have a LUB of prev_ty and new_ty, just return it.
1106 Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1108 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
1112 (ty::Closure(_, substs), ty::FnDef(..)) => {
1113 let b_sig = new_ty.fn_sig(self.tcx);
1116 .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
1117 (Some(a_sig), Some(b_sig))
1119 (ty::FnDef(..), ty::Closure(_, substs)) => {
1120 let a_sig = prev_ty.fn_sig(self.tcx);
1123 .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
1124 (Some(a_sig), Some(b_sig))
1126 (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => (
1127 Some(self.tcx.signature_unclosure(
1128 substs_a.as_closure().sig(),
1129 hir::Unsafety::Normal,
1131 Some(self.tcx.signature_unclosure(
1132 substs_b.as_closure().sig(),
1133 hir::Unsafety::Normal,
1140 if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
1141 // Intrinsics are not coercible to function pointers.
1142 if a_sig.abi() == Abi::RustIntrinsic
1143 || a_sig.abi() == Abi::PlatformIntrinsic
1144 || b_sig.abi() == Abi::RustIntrinsic
1145 || b_sig.abi() == Abi::PlatformIntrinsic
1147 return Err(TypeError::IntrinsicCast);
1149 // The signature must match.
1150 let (a_sig, b_sig) = self.normalize(new.span, (a_sig, b_sig));
1152 .at(cause, self.param_env)
1153 .trace(prev_ty, new_ty)
1155 .map(|ok| self.register_infer_ok_obligations(ok))?;
1157 // Reify both sides and return the reified fn pointer type.
1158 let fn_ptr = self.tcx.mk_fn_ptr(sig);
1159 let prev_adjustment = match prev_ty.kind() {
1160 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.unsafety())),
1161 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1162 _ => unreachable!(),
1164 let next_adjustment = match new_ty.kind() {
1165 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.unsafety())),
1166 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1167 _ => unreachable!(),
1169 for expr in exprs.iter().map(|e| e.as_coercion_site()) {
1170 self.apply_adjustments(
1172 vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1175 self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1179 // Configure a Coerce instance to compute the LUB.
1180 // We don't allow two-phase borrows on any autorefs this creates since we
1181 // probably aren't processing function arguments here and even if we were,
1182 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1184 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
1185 coerce.use_lub = true;
1187 // First try to coerce the new expression to the type of the previous ones,
1188 // but only if the new expression has no coercion already applied to it.
1189 let mut first_error = None;
1190 if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1191 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1194 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1195 self.apply_adjustments(new, adjustments);
1197 "coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1198 new_ty, prev_ty, target
1202 Err(e) => first_error = Some(e),
1206 // Then try to coerce the previous expressions to the type of the new one.
1207 // This requires ensuring there are no coercions applied to *any* of the
1208 // previous expressions, other than noop reborrows (ignoring lifetimes).
1210 let expr = expr.as_coercion_site();
1211 let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
1213 Adjustment { kind: Adjust::Deref(_), .. },
1214 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. },
1216 match *self.node_ty(expr.hir_id).kind() {
1217 ty::Ref(_, _, mt_orig) => {
1218 let mutbl_adj: hir::Mutability = mutbl_adj.into();
1219 // Reborrow that we can safely ignore, because
1220 // the next adjustment can only be a Deref
1221 // which will be merged into it.
1222 mutbl_adj == mt_orig
1227 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1233 "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1238 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1239 .map(|ok| self.register_infer_ok_obligations(ok));
1243 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1245 // Avoid giving strange errors on failed attempts.
1246 if let Some(e) = first_error {
1249 self.commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1250 .map(|ok| self.register_infer_ok_obligations(ok))
1254 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1256 let expr = expr.as_coercion_site();
1257 self.apply_adjustments(expr, adjustments.clone());
1260 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1261 prev_ty, new_ty, target
1269 /// CoerceMany encapsulates the pattern you should use when you have
1270 /// many expressions that are all getting coerced to a common
1271 /// type. This arises, for example, when you have a match (the result
1272 /// of each arm is coerced to a common type). It also arises in less
1273 /// obvious places, such as when you have many `break foo` expressions
1274 /// that target the same loop, or the various `return` expressions in
1277 /// The basic protocol is as follows:
1279 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1280 /// This will also serve as the "starting LUB". The expectation is
1281 /// that this type is something which all of the expressions *must*
1282 /// be coercible to. Use a fresh type variable if needed.
1283 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1284 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1285 /// unit. This happens for example if you have a `break` with no expression,
1286 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1287 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1288 /// from you so that you don't have to worry your pretty head about it.
1289 /// But if an error is reported, the final type will be `err`.
1290 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1291 /// previously coerced expressions.
1292 /// - When all done, invoke `complete()`. This will return the LUB of
1293 /// all your expressions.
1294 /// - WARNING: I don't believe this final type is guaranteed to be
1295 /// related to your initial `expected_ty` in any particular way,
1296 /// although it will typically be a subtype, so you should check it.
1297 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1298 /// previously coerced expressions.
1302 /// ```ignore (illustrative)
1303 /// let mut coerce = CoerceMany::new(expected_ty);
1304 /// for expr in exprs {
1305 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1306 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1308 /// let final_ty = coerce.complete(fcx);
1310 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1311 expected_ty: Ty<'tcx>,
1312 final_ty: Option<Ty<'tcx>>,
1313 expressions: Expressions<'tcx, 'exprs, E>,
1317 /// The type of a `CoerceMany` that is storing up the expressions into
1318 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1319 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1321 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1322 Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1323 UpFront(&'exprs [E]),
1326 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1327 /// The usual case; collect the set of expressions dynamically.
1328 /// If the full set of coercion sites is known before hand,
1329 /// consider `with_coercion_sites()` instead to avoid allocation.
1330 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1331 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1334 /// As an optimization, you can create a `CoerceMany` with a
1335 /// pre-existing slice of expressions. In this case, you are
1336 /// expected to pass each element in the slice to `coerce(...)` in
1337 /// order. This is used with arrays in particular to avoid
1338 /// needlessly cloning the slice.
1339 pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1340 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1343 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1344 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1347 /// Returns the "expected type" with which this coercion was
1348 /// constructed. This represents the "downward propagated" type
1349 /// that was given to us at the start of typing whatever construct
1350 /// we are typing (e.g., the match expression).
1352 /// Typically, this is used as the expected type when
1353 /// type-checking each of the alternative expressions whose types
1354 /// we are trying to merge.
1355 pub fn expected_ty(&self) -> Ty<'tcx> {
1359 /// Returns the current "merged type", representing our best-guess
1360 /// at the LUB of the expressions we've seen so far (if any). This
1361 /// isn't *final* until you call `self.complete()`, which will return
1362 /// the merged type.
1363 pub fn merged_ty(&self) -> Ty<'tcx> {
1364 self.final_ty.unwrap_or(self.expected_ty)
1367 /// Indicates that the value generated by `expression`, which is
1368 /// of type `expression_ty`, is one of the possibilities that we
1369 /// could coerce from. This will record `expression`, and later
1370 /// calls to `coerce` may come back and add adjustments and things
1374 fcx: &FnCtxt<'a, 'tcx>,
1375 cause: &ObligationCause<'tcx>,
1376 expression: &'tcx hir::Expr<'tcx>,
1377 expression_ty: Ty<'tcx>,
1379 self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1382 /// Indicates that one of the inputs is a "forced unit". This
1383 /// occurs in a case like `if foo { ... };`, where the missing else
1384 /// generates a "forced unit". Another example is a `loop { break;
1385 /// }`, where the `break` has no argument expression. We treat
1386 /// these cases slightly differently for error-reporting
1387 /// purposes. Note that these tend to correspond to cases where
1388 /// the `()` expression is implicit in the source, and hence we do
1389 /// not take an expression argument.
1391 /// The `augment_error` gives you a chance to extend the error
1392 /// message, in case any results (e.g., we use this to suggest
1393 /// removing a `;`).
1394 pub fn coerce_forced_unit<'a>(
1396 fcx: &FnCtxt<'a, 'tcx>,
1397 cause: &ObligationCause<'tcx>,
1398 augment_error: &mut dyn FnMut(&mut Diagnostic),
1399 label_unit_as_expected: bool,
1406 Some(augment_error),
1407 label_unit_as_expected,
1411 /// The inner coercion "engine". If `expression` is `None`, this
1412 /// is a forced-unit case, and hence `expression_ty` must be
1414 #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1415 pub(crate) fn coerce_inner<'a>(
1417 fcx: &FnCtxt<'a, 'tcx>,
1418 cause: &ObligationCause<'tcx>,
1419 expression: Option<&'tcx hir::Expr<'tcx>>,
1420 mut expression_ty: Ty<'tcx>,
1421 augment_error: Option<&mut dyn FnMut(&mut Diagnostic)>,
1422 label_expression_as_expected: bool,
1424 // Incorporate whatever type inference information we have
1425 // until now; in principle we might also want to process
1426 // pending obligations, but doing so should only improve
1427 // compatibility (hopefully that is true) by helping us
1428 // uncover never types better.
1429 if expression_ty.is_ty_var() {
1430 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1433 // If we see any error types, just propagate that error
1435 if expression_ty.references_error() || self.merged_ty().references_error() {
1436 self.final_ty = Some(fcx.tcx.ty_error());
1440 // Handle the actual type unification etc.
1441 let result = if let Some(expression) = expression {
1442 if self.pushed == 0 {
1443 // Special-case the first expression we are coercing.
1444 // To be honest, I'm not entirely sure why we do this.
1445 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1451 Some(cause.clone()),
1454 match self.expressions {
1455 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1462 Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1464 &coercion_sites[0..self.pushed],
1472 // this is a hack for cases where we default to `()` because
1473 // the expression etc has been omitted from the source. An
1474 // example is an `if let` without an else:
1476 // if let Some(x) = ... { }
1478 // we wind up with a second match arm that is like `_ =>
1479 // ()`. That is the case we are considering here. We take
1480 // a different path to get the right "expected, found"
1481 // message and so forth (and because we know that
1482 // `expression_ty` will be unit).
1484 // Another example is `break` with no argument expression.
1485 assert!(expression_ty.is_unit(), "if let hack without unit type");
1486 fcx.at(cause, fcx.param_env)
1487 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1489 fcx.register_infer_ok_obligations(infer_ok);
1497 self.final_ty = Some(v);
1498 if let Some(e) = expression {
1499 match self.expressions {
1500 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1501 Expressions::UpFront(coercion_sites) => {
1502 // if the user gave us an array to validate, check that we got
1503 // the next expression in the list, as expected
1505 coercion_sites[self.pushed].as_coercion_site().hir_id,
1513 Err(coercion_error) => {
1514 // Mark that we've failed to coerce the types here to suppress
1515 // any superfluous errors we might encounter while trying to
1516 // emit or provide suggestions on how to fix the initial error.
1517 fcx.set_tainted_by_errors(
1518 fcx.tcx.sess.delay_span_bug(cause.span, "coercion error but no error emitted"),
1520 let (expected, found) = if label_expression_as_expected {
1521 // In the case where this is a "forced unit", like
1522 // `break`, we want to call the `()` "expected"
1523 // since it is implied by the syntax.
1524 // (Note: not all force-units work this way.)"
1525 (expression_ty, self.merged_ty())
1527 // Otherwise, the "expected" type for error
1528 // reporting is the current unification type,
1529 // which is basically the LUB of the expressions
1530 // we've seen so far (combined with the expected
1532 (self.merged_ty(), expression_ty)
1534 let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
1537 let mut unsized_return = false;
1538 let mut visitor = CollectRetsVisitor { ret_exprs: vec![] };
1539 match *cause.code() {
1540 ObligationCauseCode::ReturnNoExpression => {
1541 err = struct_span_err!(
1545 "`return;` in a function whose return type is not `()`"
1547 err.span_label(cause.span, "return type is not `()`");
1549 ObligationCauseCode::BlockTailExpression(blk_id) => {
1550 let parent_id = fcx.tcx.hir().parent_id(blk_id);
1551 err = self.report_return_mismatched_types(
1561 if !fcx.tcx.features().unsized_locals {
1562 unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1564 if let Some(expression) = expression
1565 && let hir::ExprKind::Loop(loop_blk, ..) = expression.kind {
1566 intravisit::walk_block(& mut visitor, loop_blk);
1569 ObligationCauseCode::ReturnValue(id) => {
1570 err = self.report_return_mismatched_types(
1580 if !fcx.tcx.features().unsized_locals {
1581 let id = fcx.tcx.hir().parent_id(id);
1582 unsized_return = self.is_return_ty_unsized(fcx, id);
1586 err = fcx.err_ctxt().report_mismatched_types(
1595 if let Some(augment_error) = augment_error {
1596 augment_error(&mut err);
1599 let is_insufficiently_polymorphic =
1600 matches!(coercion_error, TypeError::RegionsInsufficientlyPolymorphic(..));
1602 if !is_insufficiently_polymorphic && let Some(expr) = expression {
1603 fcx.emit_coerce_suggestions(
1609 Some(coercion_error),
1613 if visitor.ret_exprs.len() > 0 && let Some(expr) = expression {
1614 self.note_unreachable_loop_return(&mut err, &expr, &visitor.ret_exprs);
1616 let reported = err.emit_unless(unsized_return);
1618 self.final_ty = Some(fcx.tcx.ty_error_with_guaranteed(reported));
1622 fn note_unreachable_loop_return(
1624 err: &mut Diagnostic,
1625 expr: &hir::Expr<'tcx>,
1626 ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>,
1628 let hir::ExprKind::Loop(_, _, _, loop_span) = expr.kind else { return;};
1629 let mut span: MultiSpan = vec![loop_span].into();
1630 span.push_span_label(loop_span, "this might have zero elements to iterate on");
1631 const MAXITER: usize = 3;
1632 let iter = ret_exprs.iter().take(MAXITER);
1633 for ret_expr in iter {
1634 span.push_span_label(
1636 "if the loop doesn't execute, this value would never get returned",
1641 "the function expects a value to always be returned, but loops might run zero times",
1643 if MAXITER < ret_exprs.len() {
1645 "if the loop doesn't execute, {} other values would never get returned",
1646 ret_exprs.len() - MAXITER
1650 "return a value for the case when the loop has zero elements to iterate on, or \
1651 consider changing the return type to account for that possibility",
1655 fn report_return_mismatched_types<'a>(
1657 cause: &ObligationCause<'tcx>,
1660 ty_err: TypeError<'tcx>,
1661 fcx: &FnCtxt<'a, 'tcx>,
1663 expression: Option<&'tcx hir::Expr<'tcx>>,
1664 blk_id: Option<hir::HirId>,
1665 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1666 let mut err = fcx.err_ctxt().report_mismatched_types(cause, expected, found, ty_err);
1668 let mut pointing_at_return_type = false;
1669 let mut fn_output = None;
1671 let parent_id = fcx.tcx.hir().parent_id(id);
1672 let parent = fcx.tcx.hir().get(parent_id);
1673 if let Some(expr) = expression
1674 && let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { body, .. }), .. }) = parent
1675 && !matches!(fcx.tcx.hir().body(body).value.kind, hir::ExprKind::Block(..))
1677 fcx.suggest_missing_semicolon(&mut err, expr, expected, true);
1679 // Verify that this is a tail expression of a function, otherwise the
1680 // label pointing out the cause for the type coercion will be wrong
1681 // as prior return coercions would not be relevant (#57664).
1682 let fn_decl = if let (Some(expr), Some(blk_id)) = (expression, blk_id) {
1683 pointing_at_return_type =
1684 fcx.suggest_mismatched_types_on_tail(&mut err, expr, expected, found, blk_id);
1685 if let (Some(cond_expr), true, false) = (
1686 fcx.tcx.hir().get_if_cause(expr.hir_id),
1688 pointing_at_return_type,
1690 // If the block is from an external macro or try (`?`) desugaring, then
1691 // do not suggest adding a semicolon, because there's nowhere to put it.
1692 // See issues #81943 and #87051.
1694 cond_expr.span.desugaring_kind(),
1695 None | Some(DesugaringKind::WhileLoop)
1696 ) && !in_external_macro(fcx.tcx.sess, cond_expr.span)
1699 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar)
1702 err.span_label(cond_expr.span, "expected this to be `()`");
1703 if expr.can_have_side_effects() {
1704 fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1707 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1709 fcx.get_fn_decl(parent_id)
1712 if let Some((fn_decl, can_suggest)) = fn_decl {
1713 if blk_id.is_none() {
1714 pointing_at_return_type |= fcx.suggest_missing_return_type(
1720 fcx.tcx.hir().get_parent_item(id).into(),
1723 if !pointing_at_return_type {
1724 fn_output = Some(&fn_decl.output); // `impl Trait` return type
1728 let parent_id = fcx.tcx.hir().get_parent_item(id);
1729 let parent_item = fcx.tcx.hir().get_by_def_id(parent_id.def_id);
1731 if let (Some(expr), Some(_), Some((fn_decl, _, _))) =
1732 (expression, blk_id, fcx.get_node_fn_decl(parent_item))
1734 fcx.suggest_missing_break_or_return_expr(
1745 let ret_coercion_span = fcx.ret_coercion_span.get();
1747 if let Some(sp) = ret_coercion_span
1748 // If the closure has an explicit return type annotation, or if
1749 // the closure's return type has been inferred from outside
1750 // requirements (such as an Fn* trait bound), then a type error
1751 // may occur at the first return expression we see in the closure
1752 // (if it conflicts with the declared return type). Skip adding a
1753 // note in this case, since it would be incorrect.
1754 && let Some(fn_sig) = fcx.body_fn_sig()
1755 && fn_sig.output().is_ty_var()
1760 "return type inferred to be `{}` here",
1766 if let (Some(sp), Some(fn_output)) = (ret_coercion_span, fn_output) {
1767 self.add_impl_trait_explanation(&mut err, cause, fcx, expected, sp, fn_output);
1773 fn add_impl_trait_explanation<'a>(
1775 err: &mut Diagnostic,
1776 cause: &ObligationCause<'tcx>,
1777 fcx: &FnCtxt<'a, 'tcx>,
1780 fn_output: &hir::FnRetTy<'_>,
1782 let return_sp = fn_output.span();
1783 err.span_label(return_sp, "expected because this return type...");
1786 format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1788 let impl_trait_msg = "for information on `impl Trait`, see \
1789 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1790 #returning-types-that-implement-traits>";
1791 let trait_obj_msg = "for information on trait objects, see \
1792 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1793 #using-trait-objects-that-allow-for-values-of-different-types>";
1794 err.note("to return `impl Trait`, all returned values must be of the same type");
1795 err.note(impl_trait_msg);
1800 .span_to_snippet(return_sp)
1801 .unwrap_or_else(|_| "dyn Trait".to_string());
1802 let mut snippet_iter = snippet.split_whitespace();
1803 let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1804 // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1805 let mut is_object_safe = false;
1806 if let hir::FnRetTy::Return(ty) = fn_output
1807 // Get the return type.
1808 && let hir::TyKind::OpaqueDef(..) = ty.kind
1810 let ty = fcx.astconv().ast_ty_to_ty( ty);
1811 // Get the `impl Trait`'s `DefId`.
1812 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = ty.kind()
1813 // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1814 // get the `Trait`'s `DefId`.
1815 && let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1816 fcx.tcx.hir().expect_item(def_id.expect_local()).kind
1818 // Are of this `impl Trait`'s traits object safe?
1819 is_object_safe = bounds.iter().all(|bound| {
1822 .and_then(|t| t.trait_def_id())
1823 .map_or(false, |def_id| {
1824 fcx.tcx.object_safety_violations(def_id).is_empty()
1831 err.multipart_suggestion(
1832 "you could change the return type to be a boxed trait object",
1834 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
1835 (return_sp.shrink_to_hi(), ">".to_string()),
1837 Applicability::MachineApplicable,
1839 let sugg = [sp, cause.span]
1843 (sp.shrink_to_lo(), "Box::new(".to_string()),
1844 (sp.shrink_to_hi(), ")".to_string()),
1848 .collect::<Vec<_>>();
1849 err.multipart_suggestion(
1850 "if you change the return type to expect trait objects, box the returned \
1853 Applicability::MaybeIncorrect,
1857 "if the trait `{}` were object safe, you could return a boxed trait object",
1861 err.note(trait_obj_msg);
1863 err.help("you could instead create a new `enum` with a variant for each returned type");
1866 fn is_return_ty_unsized<'a>(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
1867 if let Some((fn_decl, _)) = fcx.get_fn_decl(blk_id)
1868 && let hir::FnRetTy::Return(ty) = fn_decl.output
1869 && let ty = fcx.astconv().ast_ty_to_ty( ty)
1870 && let ty::Dynamic(..) = ty.kind()
1877 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1878 if let Some(final_ty) = self.final_ty {
1881 // If we only had inputs that were of type `!` (or no
1882 // inputs at all), then the final type is `!`.
1883 assert_eq!(self.pushed, 0);
1889 /// Something that can be converted into an expression to which we can
1890 /// apply a coercion.
1891 pub trait AsCoercionSite {
1892 fn as_coercion_site(&self) -> &hir::Expr<'_>;
1895 impl AsCoercionSite for hir::Expr<'_> {
1896 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1901 impl<'a, T> AsCoercionSite for &'a T
1905 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1906 (**self).as_coercion_site()
1910 impl AsCoercionSite for ! {
1911 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1916 impl AsCoercionSite for hir::Arm<'_> {
1917 fn as_coercion_site(&self) -> &hir::Expr<'_> {