rustc_hir_typeck/coercion.rs
1//! # Type Coercion
2//!
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).
8//!
9//! ## Reborrowing
10//!
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.
18//!
19//! ## Subtle note
20//!
21//! When inferring the generic arguments of functions, the argument
22//! order is relevant, which can lead to the following edge case:
23//!
24//! ```ignore (illustrative)
25//! fn foo<T>(a: T, b: T) {
26//! // ...
27//! }
28//!
29//! foo(&7i32, &mut 7i32);
30//! // This compiles, as we first infer `T` to be `&i32`,
31//! // and then coerce `&mut 7i32` to `&7i32`.
32//!
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`.
36//! ```
37
38use std::ops::{ControlFlow, Deref};
39
40use rustc_errors::codes::*;
41use rustc_errors::{Applicability, Diag, struct_span_code_err};
42use rustc_hir::attrs::InlineAttr;
43use rustc_hir::def_id::{DefId, LocalDefId};
44use rustc_hir::{self as hir, LangItem};
45use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
46use rustc_infer::infer::relate::RelateResult;
47use rustc_infer::infer::{DefineOpaqueTypes, InferOk, InferResult, RegionVariableOrigin};
48use rustc_infer::traits::{
49 MatchExpressionArmCause, Obligation, PredicateObligation, PredicateObligations, SelectionError,
50};
51use rustc_middle::span_bug;
52use rustc_middle::ty::adjustment::{
53 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCoercion,
54};
55use rustc_middle::ty::error::TypeError;
56use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
57use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Span};
58use rustc_trait_selection::infer::InferCtxtExt as _;
59use rustc_trait_selection::solve::inspect::{self, InferCtxtProofTreeExt, ProofTreeVisitor};
60use rustc_trait_selection::solve::{Certainty, Goal, NoSolution};
61use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
62use rustc_trait_selection::traits::{
63 self, ImplSource, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
64};
65use smallvec::{SmallVec, smallvec};
66use tracing::{debug, instrument};
67
68use crate::FnCtxt;
69use crate::errors::SuggestBoxingForReturnImplTrait;
70
71struct Coerce<'a, 'tcx> {
72 fcx: &'a FnCtxt<'a, 'tcx>,
73 cause: ObligationCause<'tcx>,
74 use_lub: bool,
75 /// Determines whether or not allow_two_phase_borrow is set on any
76 /// autoref adjustments we create while coercing. We don't want to
77 /// allow deref coercions to create two-phase borrows, at least initially,
78 /// but we do need two-phase borrows for function argument reborrows.
79 /// See #47489 and #48598
80 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
81 allow_two_phase: AllowTwoPhase,
82 /// Whether we allow `NeverToAny` coercions. This is unsound if we're
83 /// coercing a place expression without it counting as a read in the MIR.
84 /// This is a side-effect of HIR not really having a great distinction
85 /// between places and values.
86 coerce_never: bool,
87}
88
89impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
90 type Target = FnCtxt<'a, 'tcx>;
91 fn deref(&self) -> &Self::Target {
92 self.fcx
93 }
94}
95
96type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
97
98/// Coercing a mutable reference to an immutable works, while
99/// coercing `&T` to `&mut T` should be forbidden.
100fn coerce_mutbls<'tcx>(
101 from_mutbl: hir::Mutability,
102 to_mutbl: hir::Mutability,
103) -> RelateResult<'tcx, ()> {
104 if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
105}
106
107/// This always returns `Ok(...)`.
108fn success<'tcx>(
109 adj: Vec<Adjustment<'tcx>>,
110 target: Ty<'tcx>,
111 obligations: PredicateObligations<'tcx>,
112) -> CoerceResult<'tcx> {
113 Ok(InferOk { value: (adj, target), obligations })
114}
115
116/// Whether to force a leak check to occur in `Coerce::unify_raw`.
117/// Note that leak checks may still occur evn with `ForceLeakCheck::No`.
118///
119/// FIXME: We may want to change type relations to always leak-check
120/// after exiting a binder, at which point we will always do so and
121/// no longer need to handle this explicitly
122enum ForceLeakCheck {
123 Yes,
124 No,
125}
126
127impl<'f, 'tcx> Coerce<'f, 'tcx> {
128 fn new(
129 fcx: &'f FnCtxt<'f, 'tcx>,
130 cause: ObligationCause<'tcx>,
131 allow_two_phase: AllowTwoPhase,
132 coerce_never: bool,
133 ) -> Self {
134 Coerce { fcx, cause, allow_two_phase, use_lub: false, coerce_never }
135 }
136
137 fn unify_raw(
138 &self,
139 a: Ty<'tcx>,
140 b: Ty<'tcx>,
141 leak_check: ForceLeakCheck,
142 ) -> InferResult<'tcx, Ty<'tcx>> {
143 debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
144 self.commit_if_ok(|snapshot| {
145 let outer_universe = self.infcx.universe();
146
147 let at = self.at(&self.cause, self.fcx.param_env);
148
149 let res = if self.use_lub {
150 at.lub(b, a)
151 } else {
152 at.sup(DefineOpaqueTypes::Yes, b, a)
153 .map(|InferOk { value: (), obligations }| InferOk { value: b, obligations })
154 };
155
156 // In the new solver, lazy norm may allow us to shallowly equate
157 // more types, but we emit possibly impossible-to-satisfy obligations.
158 // Filter these cases out to make sure our coercion is more accurate.
159 let res = match res {
160 Ok(InferOk { value, obligations }) if self.next_trait_solver() => {
161 let ocx = ObligationCtxt::new(self);
162 ocx.register_obligations(obligations);
163 if ocx.try_evaluate_obligations().is_empty() {
164 Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
165 } else {
166 Err(TypeError::Mismatch)
167 }
168 }
169 res => res,
170 };
171
172 // We leak check here mostly because lub operations are
173 // kind of scuffed around binders. Instead of computing an actual
174 // lub'd binder we instead:
175 // - Equate the binders
176 // - Return the lhs of the lub operation
177 //
178 // This may lead to incomplete type inference for the resulting type
179 // of a `match` or `if .. else`, etc. This is a backwards compat
180 // hazard for if/when we start handling `lub` more correctly.
181 //
182 // In order to actually ensure that equating the binders *does*
183 // result in equal binders, and that the lhs is actually a supertype
184 // of the rhs, we must perform a leak check here.
185 if matches!(leak_check, ForceLeakCheck::Yes) {
186 self.leak_check(outer_universe, Some(snapshot))?;
187 }
188
189 res
190 })
191 }
192
193 /// Unify two types (using sub or lub).
194 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>, leak_check: ForceLeakCheck) -> CoerceResult<'tcx> {
195 self.unify_raw(a, b, leak_check)
196 .and_then(|InferOk { value: ty, obligations }| success(vec![], ty, obligations))
197 }
198
199 /// Unify two types (using sub or lub) and produce a specific coercion.
200 fn unify_and(
201 &self,
202 a: Ty<'tcx>,
203 b: Ty<'tcx>,
204 adjustments: impl IntoIterator<Item = Adjustment<'tcx>>,
205 final_adjustment: Adjust,
206 leak_check: ForceLeakCheck,
207 ) -> CoerceResult<'tcx> {
208 self.unify_raw(a, b, leak_check).and_then(|InferOk { value: ty, obligations }| {
209 success(
210 adjustments
211 .into_iter()
212 .chain(std::iter::once(Adjustment { target: ty, kind: final_adjustment }))
213 .collect(),
214 ty,
215 obligations,
216 )
217 })
218 }
219
220 #[instrument(skip(self), ret)]
221 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
222 // First, remove any resolved type variables (at the top level, at least):
223 let a = self.shallow_resolve(a);
224 let b = self.shallow_resolve(b);
225 debug!("Coerce.tys({:?} => {:?})", a, b);
226
227 // Coercing from `!` to any type is allowed:
228 if a.is_never() {
229 if self.coerce_never {
230 return success(
231 vec![Adjustment { kind: Adjust::NeverToAny, target: b }],
232 b,
233 PredicateObligations::new(),
234 );
235 } else {
236 // Otherwise the only coercion we can do is unification.
237 return self.unify(a, b, ForceLeakCheck::No);
238 }
239 }
240
241 // Coercing *from* an unresolved inference variable means that
242 // we have no information about the source type. This will always
243 // ultimately fall back to some form of subtyping.
244 if a.is_ty_var() {
245 return self.coerce_from_inference_variable(a, b);
246 }
247
248 // Consider coercing the subtype to a DST
249 //
250 // NOTE: this is wrapped in a `commit_if_ok` because it creates
251 // a "spurious" type variable, and we don't want to have that
252 // type variable in memory if the coercion fails.
253 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
254 match unsize {
255 Ok(_) => {
256 debug!("coerce: unsize successful");
257 return unsize;
258 }
259 Err(error) => {
260 debug!(?error, "coerce: unsize failed");
261 }
262 }
263
264 // Examine the target type and consider type-specific coercions, such
265 // as auto-borrowing, coercing pointer mutability, or pin-ergonomics.
266 match *b.kind() {
267 ty::RawPtr(_, b_mutbl) => {
268 return self.coerce_to_raw_ptr(a, b, b_mutbl);
269 }
270 ty::Ref(r_b, _, mutbl_b) => {
271 return self.coerce_to_ref(a, b, r_b, mutbl_b);
272 }
273 ty::Adt(pin, _)
274 if self.tcx.features().pin_ergonomics()
275 && self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) =>
276 {
277 let pin_coerce = self.commit_if_ok(|_| self.coerce_to_pin_ref(a, b));
278 if pin_coerce.is_ok() {
279 return pin_coerce;
280 }
281 }
282 _ => {}
283 }
284
285 match *a.kind() {
286 ty::FnDef(..) => {
287 // Function items are coercible to any closure
288 // type; function pointers are not (that would
289 // require double indirection).
290 // Additionally, we permit coercion of function
291 // items to drop the unsafe qualifier.
292 self.coerce_from_fn_item(a, b)
293 }
294 ty::FnPtr(a_sig_tys, a_hdr) => {
295 // We permit coercion of fn pointers to drop the
296 // unsafe qualifier.
297 self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
298 }
299 ty::Closure(..) => {
300 // Non-capturing closures are coercible to
301 // function pointers or unsafe function pointers.
302 // It cannot convert closures that require unsafe.
303 self.coerce_closure_to_fn(a, b)
304 }
305 _ => {
306 // Otherwise, just use unification rules.
307 self.unify(a, b, ForceLeakCheck::No)
308 }
309 }
310 }
311
312 /// Coercing *from* an inference variable. In this case, we have no information
313 /// about the source type, so we can't really do a true coercion and we always
314 /// fall back to subtyping (`unify_and`).
315 fn coerce_from_inference_variable(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
316 debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
317 debug_assert!(a.is_ty_var() && self.shallow_resolve(a) == a);
318 debug_assert!(self.shallow_resolve(b) == b);
319
320 if b.is_ty_var() {
321 let mut obligations = PredicateObligations::with_capacity(2);
322 let mut push_coerce_obligation = |a, b| {
323 obligations.push(Obligation::new(
324 self.tcx(),
325 self.cause.clone(),
326 self.param_env,
327 ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { a, b })),
328 ));
329 };
330
331 let target_ty = if self.use_lub {
332 // When computing the lub, we create a new target
333 // and coerce both `a` and `b` to it.
334 let target_ty = self.next_ty_var(self.cause.span);
335 push_coerce_obligation(a, target_ty);
336 push_coerce_obligation(b, target_ty);
337 target_ty
338 } else {
339 // When subtyping, we don't need to create a new target
340 // as we only coerce `a` to `b`.
341 push_coerce_obligation(a, b);
342 b
343 };
344
345 debug!(
346 "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
347 target_ty, obligations
348 );
349 success(vec![], target_ty, obligations)
350 } else {
351 // One unresolved type variable: just apply subtyping, we may be able
352 // to do something useful.
353 self.unify(a, b, ForceLeakCheck::No)
354 }
355 }
356
357 /// Handles coercing some arbitrary type `a` to some reference (`b`). This
358 /// handles a few cases:
359 /// - Introducing reborrows to give more flexible lifetimes
360 /// - Deref coercions to allow `&T` to coerce to `&T::Target`
361 /// - Coercing mutable references to immutable references
362 /// These coercions can be freely intermixed, for example we are able to
363 /// coerce `&mut T` to `&mut T::Target`.
364 fn coerce_to_ref(
365 &self,
366 a: Ty<'tcx>,
367 b: Ty<'tcx>,
368 r_b: ty::Region<'tcx>,
369 mutbl_b: hir::Mutability,
370 ) -> CoerceResult<'tcx> {
371 debug!("coerce_to_ref(a={:?}, b={:?})", a, b);
372 debug_assert!(self.shallow_resolve(a) == a);
373 debug_assert!(self.shallow_resolve(b) == b);
374
375 let (r_a, mt_a) = match *a.kind() {
376 ty::Ref(r_a, ty, mutbl) => {
377 coerce_mutbls(mutbl, mutbl_b)?;
378 (r_a, ty::TypeAndMut { ty, mutbl })
379 }
380 _ => return self.unify(a, b, ForceLeakCheck::No),
381 };
382
383 // Look at each step in the `Deref` chain and check if
384 // any of the autoref'd `Target` types unify with the
385 // coercion target.
386 //
387 // For example when coercing from `&mut Vec<T>` to `&M [T]` we
388 // have three deref steps:
389 // 1. `&mut Vec<T>`, skip autoref
390 // 2. `Vec<T>`, autoref'd ty: `&M Vec<T>`
391 // - `&M Vec<T>` does not unify with `&M [T]`
392 // 3. `[T]`, autoref'd ty: `&M [T]`
393 // - `&M [T]` does unify with `&M [T]`
394 let mut first_error = None;
395 let mut r_borrow_var = None;
396 let mut autoderef = self.autoderef(self.cause.span, a);
397 let found = autoderef.by_ref().find_map(|(deref_ty, autoderefs)| {
398 if autoderefs == 0 {
399 // Don't autoref the first step as otherwise we'd allow
400 // coercing `&T` to `&&T`.
401 return None;
402 }
403
404 // The logic here really shouldn't exist. We don't care about free
405 // lifetimes during HIR typeck. Unfortunately later parts of this
406 // function rely on structural identity of the autoref'd deref'd ty.
407 //
408 // This means that what region we use here actually impacts whether
409 // we emit a reborrow coercion or not which can affect diagnostics
410 // and capture analysis (which in turn affects borrowck).
411 let r = if !self.use_lub {
412 r_b
413 } else if autoderefs == 1 {
414 r_a
415 } else {
416 if r_borrow_var.is_none() {
417 // create var lazily, at most once
418 let coercion = RegionVariableOrigin::Coercion(self.cause.span);
419 let r = self.next_region_var(coercion);
420 r_borrow_var = Some(r);
421 }
422 r_borrow_var.unwrap()
423 };
424
425 let autorefd_deref_ty = Ty::new_ref(self.tcx, r, deref_ty, mutbl_b);
426
427 // Note that we unify the autoref'd `Target` type with `b` rather than
428 // the `Target` type with the pointee of `b`. This is necessary
429 // to properly account for the differing variances of the pointees
430 // of `&` vs `&mut` references.
431 match self.unify_raw(autorefd_deref_ty, b, ForceLeakCheck::No) {
432 Ok(ok) => Some(ok),
433 Err(err) => {
434 if first_error.is_none() {
435 first_error = Some(err);
436 }
437 None
438 }
439 }
440 });
441
442 // Extract type or return an error. We return the first error
443 // we got, which should be from relating the "base" type
444 // (e.g., in example above, the failure from relating `Vec<T>`
445 // to the target type), since that should be the least
446 // confusing.
447 let Some(InferOk { value: coerced_a, mut obligations }) = found else {
448 if let Some(first_error) = first_error {
449 debug!("coerce_to_ref: failed with err = {:?}", first_error);
450 return Err(first_error);
451 } else {
452 // This may happen in the new trait solver since autoderef requires
453 // the pointee to be structurally normalizable, or else it'll just bail.
454 // So when we have a type like `&<not well formed>`, then we get no
455 // autoderef steps (even though there should be at least one). That means
456 // we get no type mismatches, since the loop above just exits early.
457 return Err(TypeError::Mismatch);
458 }
459 };
460
461 if coerced_a == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
462 // As a special case, if we would produce `&'a *x`, that's
463 // a total no-op. We end up with the type `&'a T` just as
464 // we started with. In that case, just skip it altogether.
465 //
466 // Unfortunately, this can actually effect capture analysis
467 // which in turn means this effects borrow checking. This can
468 // also effect diagnostics.
469 // FIXME(BoxyUwU): we should always emit reborrow coercions
470 //
471 // Note that for `&mut`, we DO want to reborrow --
472 // otherwise, this would be a move, which might be an
473 // error. For example `foo(self.x)` where `self` and
474 // `self.x` both have `&mut `type would be a move of
475 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
476 // which is a borrow.
477 assert!(mutbl_b.is_not()); // can only coerce &T -> &U
478 return success(vec![], coerced_a, obligations);
479 }
480
481 let InferOk { value: mut adjustments, obligations: o } =
482 self.adjust_steps_as_infer_ok(&autoderef);
483 obligations.extend(o);
484 obligations.extend(autoderef.into_obligations());
485
486 assert!(
487 matches!(coerced_a.kind(), ty::Ref(..)),
488 "expected a ref type, got {:?}",
489 coerced_a
490 );
491
492 // Now apply the autoref
493 let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
494 adjustments
495 .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target: coerced_a });
496
497 debug!("coerce_to_ref: succeeded coerced_a={:?} adjustments={:?}", coerced_a, adjustments);
498
499 success(adjustments, coerced_a, obligations)
500 }
501
502 /// Performs [unsized coercion] by emulating a fulfillment loop on a
503 /// `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals
504 /// are successfully selected.
505 ///
506 /// [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions)
507 #[instrument(skip(self), level = "debug")]
508 fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
509 debug!(?source, ?target);
510 debug_assert!(self.shallow_resolve(source) == source);
511 debug_assert!(self.shallow_resolve(target) == target);
512
513 // We don't apply any coercions incase either the source or target
514 // aren't sufficiently well known but tend to instead just equate
515 // them both.
516 if source.is_ty_var() {
517 debug!("coerce_unsized: source is a TyVar, bailing out");
518 return Err(TypeError::Mismatch);
519 }
520 if target.is_ty_var() {
521 debug!("coerce_unsized: target is a TyVar, bailing out");
522 return Err(TypeError::Mismatch);
523 }
524
525 // This is an optimization because coercion is one of the most common
526 // operations that we do in typeck, since it happens at every assignment
527 // and call arg (among other positions).
528 //
529 // These targets are known to never be RHS in `LHS: CoerceUnsized<RHS>`.
530 // That's because these are built-in types for which a core-provided impl
531 // doesn't exist, and for which a user-written impl is invalid.
532 //
533 // This is technically incomplete when users write impossible bounds like
534 // `where T: CoerceUnsized<usize>`, for example, but that trait is unstable
535 // and coercion is allowed to be incomplete. The only case where this matters
536 // is impossible bounds.
537 //
538 // Note that some of these types implement `LHS: Unsize<RHS>`, but they
539 // do not implement *`CoerceUnsized`* which is the root obligation of the
540 // check below.
541 match target.kind() {
542 ty::Bool
543 | ty::Char
544 | ty::Int(_)
545 | ty::Uint(_)
546 | ty::Float(_)
547 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
548 | ty::Str
549 | ty::Array(_, _)
550 | ty::Slice(_)
551 | ty::FnDef(_, _)
552 | ty::FnPtr(_, _)
553 | ty::Dynamic(_, _)
554 | ty::Closure(_, _)
555 | ty::CoroutineClosure(_, _)
556 | ty::Coroutine(_, _)
557 | ty::CoroutineWitness(_, _)
558 | ty::Never
559 | ty::Tuple(_) => return Err(TypeError::Mismatch),
560 _ => {}
561 }
562 // `&str: CoerceUnsized<&str>` does not hold but is encountered frequently
563 // so we fast path bail out here
564 if let ty::Ref(_, source_pointee, ty::Mutability::Not) = *source.kind()
565 && source_pointee.is_str()
566 && let ty::Ref(_, target_pointee, ty::Mutability::Not) = *target.kind()
567 && target_pointee.is_str()
568 {
569 return Err(TypeError::Mismatch);
570 }
571
572 let traits =
573 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
574 let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
575 debug!("missing Unsize or CoerceUnsized traits");
576 return Err(TypeError::Mismatch);
577 };
578
579 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
580 // a DST unless we have to. This currently comes out in the wash since
581 // we can't unify [T] with U. But to properly support DST, we need to allow
582 // that, at which point we will need extra checks on the target here.
583
584 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
585 let reborrow = match (source.kind(), target.kind()) {
586 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
587 coerce_mutbls(mutbl_a, mutbl_b)?;
588
589 let coercion = RegionVariableOrigin::Coercion(self.cause.span);
590 let r_borrow = self.next_region_var(coercion);
591
592 // We don't allow two-phase borrows here, at least for initial
593 // implementation. If it happens that this coercion is a function argument,
594 // the reborrow in coerce_borrowed_ptr will pick it up.
595 let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
596
597 Some((
598 Adjustment { kind: Adjust::Deref(None), target: ty_a },
599 Adjustment {
600 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
601 target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
602 },
603 ))
604 }
605 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
606 coerce_mutbls(mt_a, mt_b)?;
607
608 Some((
609 Adjustment { kind: Adjust::Deref(None), target: ty_a },
610 Adjustment {
611 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
612 target: Ty::new_ptr(self.tcx, ty_a, mt_b),
613 },
614 ))
615 }
616 _ => None,
617 };
618 let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
619
620 // Setup either a subtyping or a LUB relationship between
621 // the `CoerceUnsized` target type and the expected type.
622 // We only have the latter, so we use an inference variable
623 // for the former and let type inference do the rest.
624 let coerce_target = self.next_ty_var(self.cause.span);
625
626 let mut coercion = self.unify_and(
627 coerce_target,
628 target,
629 reborrow.into_iter().flat_map(|(deref, autoref)| [deref, autoref]),
630 Adjust::Pointer(PointerCoercion::Unsize),
631 ForceLeakCheck::No,
632 )?;
633
634 // Create an obligation for `Source: CoerceUnsized<Target>`.
635 let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
636 let pred = ty::TraitRef::new(self.tcx, coerce_unsized_did, [coerce_source, coerce_target]);
637 let obligation = Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
638
639 if self.next_trait_solver() {
640 coercion.obligations.push(obligation);
641
642 if self
643 .infcx
644 .visit_proof_tree(
645 Goal::new(self.tcx, self.param_env, pred),
646 &mut CoerceVisitor { fcx: self.fcx, span: self.cause.span },
647 )
648 .is_break()
649 {
650 return Err(TypeError::Mismatch);
651 }
652 } else {
653 self.coerce_unsized_old_solver(
654 obligation,
655 &mut coercion,
656 coerce_unsized_did,
657 unsize_did,
658 )?;
659 }
660
661 Ok(coercion)
662 }
663
664 fn coerce_unsized_old_solver(
665 &self,
666 obligation: Obligation<'tcx, ty::Predicate<'tcx>>,
667 coercion: &mut InferOk<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>,
668 coerce_unsized_did: DefId,
669 unsize_did: DefId,
670 ) -> Result<(), TypeError<'tcx>> {
671 let mut selcx = traits::SelectionContext::new(self);
672 // Use a FIFO queue for this custom fulfillment procedure.
673 //
674 // A Vec (or SmallVec) is not a natural choice for a queue. However,
675 // this code path is hot, and this queue usually has a max length of 1
676 // and almost never more than 3. By using a SmallVec we avoid an
677 // allocation, at the (very small) cost of (occasionally) having to
678 // shift subsequent elements down when removing the front element.
679 let mut queue: SmallVec<[PredicateObligation<'tcx>; 4]> = smallvec![obligation];
680
681 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
682 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
683 // inference might unify those two inner type variables later.
684 let traits = [coerce_unsized_did, unsize_did];
685 while !queue.is_empty() {
686 let obligation = queue.remove(0);
687 let trait_pred = match obligation.predicate.kind().no_bound_vars() {
688 Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)))
689 if traits.contains(&trait_pred.def_id()) =>
690 {
691 self.resolve_vars_if_possible(trait_pred)
692 }
693 // Eagerly process alias-relate obligations in new trait solver,
694 // since these can be emitted in the process of solving trait goals,
695 // but we need to constrain vars before processing goals mentioning
696 // them.
697 Some(ty::PredicateKind::AliasRelate(..)) => {
698 let ocx = ObligationCtxt::new(self);
699 ocx.register_obligation(obligation);
700 if !ocx.try_evaluate_obligations().is_empty() {
701 return Err(TypeError::Mismatch);
702 }
703 coercion.obligations.extend(ocx.into_pending_obligations());
704 continue;
705 }
706 _ => {
707 coercion.obligations.push(obligation);
708 continue;
709 }
710 };
711 debug!("coerce_unsized resolve step: {:?}", trait_pred);
712 match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
713 // Uncertain or unimplemented.
714 Ok(None) => {
715 if trait_pred.def_id() == unsize_did {
716 let self_ty = trait_pred.self_ty();
717 let unsize_ty = trait_pred.trait_ref.args[1].expect_ty();
718 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
719 match (self_ty.kind(), unsize_ty.kind()) {
720 (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
721 if self.type_var_is_sized(v) =>
722 {
723 debug!("coerce_unsized: have sized infer {:?}", v);
724 coercion.obligations.push(obligation);
725 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
726 // for unsizing.
727 }
728 _ => {
729 // Some other case for `$0: Unsize<Something>`. Note that we
730 // hit this case even if `Something` is a sized type, so just
731 // don't do the coercion.
732 debug!("coerce_unsized: ambiguous unsize");
733 return Err(TypeError::Mismatch);
734 }
735 }
736 } else {
737 debug!("coerce_unsized: early return - ambiguous");
738 return Err(TypeError::Mismatch);
739 }
740 }
741 Err(SelectionError::Unimplemented) => {
742 debug!("coerce_unsized: early return - can't prove obligation");
743 return Err(TypeError::Mismatch);
744 }
745
746 Err(SelectionError::TraitDynIncompatible(_)) => {
747 // Dyn compatibility errors in coercion will *always* be due to the
748 // fact that the RHS of the coercion is a non-dyn compatible `dyn Trait`
749 // written in source somewhere (otherwise we will never have lowered
750 // the dyn trait from HIR to middle).
751 //
752 // There's no reason to emit yet another dyn compatibility error,
753 // especially since the span will differ slightly and thus not be
754 // deduplicated at all!
755 self.fcx.set_tainted_by_errors(
756 self.fcx
757 .dcx()
758 .span_delayed_bug(self.cause.span, "dyn compatibility during coercion"),
759 );
760 }
761 Err(err) => {
762 let guar = self.err_ctxt().report_selection_error(
763 obligation.clone(),
764 &obligation,
765 &err,
766 );
767 self.fcx.set_tainted_by_errors(guar);
768 // Treat this like an obligation and follow through
769 // with the unsizing - the lack of a coercion should
770 // be silent, as it causes a type mismatch later.
771 }
772 Ok(Some(ImplSource::UserDefined(impl_source))) => {
773 queue.extend(impl_source.nested);
774 // Certain incoherent `CoerceUnsized` implementations may cause ICEs,
775 // so check the impl's validity. Taint the body so that we don't try
776 // to evaluate these invalid coercions in CTFE. We only need to do this
777 // for local impls, since upstream impls should be valid.
778 if impl_source.impl_def_id.is_local()
779 && let Err(guar) =
780 self.tcx.ensure_ok().coerce_unsized_info(impl_source.impl_def_id)
781 {
782 self.fcx.set_tainted_by_errors(guar);
783 }
784 }
785 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
786 }
787 }
788
789 Ok(())
790 }
791
792 /// Applies reborrowing for `Pin`
793 ///
794 /// We currently only support reborrowing `Pin<&mut T>` as `Pin<&mut T>`. This is accomplished
795 /// by inserting a call to `Pin::as_mut` during MIR building.
796 ///
797 /// In the future we might want to support other reborrowing coercions, such as:
798 /// - `Pin<&mut T>` as `Pin<&T>`
799 /// - `Pin<&T>` as `Pin<&T>`
800 /// - `Pin<Box<T>>` as `Pin<&T>`
801 /// - `Pin<Box<T>>` as `Pin<&mut T>`
802 #[instrument(skip(self), level = "trace")]
803 fn coerce_to_pin_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
804 debug_assert!(self.shallow_resolve(a) == a);
805 debug_assert!(self.shallow_resolve(b) == b);
806
807 // We need to make sure the two types are compatible for coercion.
808 // Then we will build a ReborrowPin adjustment and return that as an InferOk.
809
810 // Right now we can only reborrow if this is a `Pin<&mut T>`.
811 let extract_pin_mut = |ty: Ty<'tcx>| {
812 // Get the T out of Pin<T>
813 let (pin, ty) = match ty.kind() {
814 ty::Adt(pin, args) if self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) => {
815 (*pin, args[0].expect_ty())
816 }
817 _ => {
818 debug!("can't reborrow {:?} as pinned", ty);
819 return Err(TypeError::Mismatch);
820 }
821 };
822 // Make sure the T is something we understand (just `&mut U` for now)
823 match ty.kind() {
824 ty::Ref(region, ty, mutbl) => Ok((pin, *region, *ty, *mutbl)),
825 _ => {
826 debug!("can't reborrow pin of inner type {:?}", ty);
827 Err(TypeError::Mismatch)
828 }
829 }
830 };
831
832 let (pin, a_region, a_ty, mut_a) = extract_pin_mut(a)?;
833 let (_, _, _b_ty, mut_b) = extract_pin_mut(b)?;
834
835 coerce_mutbls(mut_a, mut_b)?;
836
837 // update a with b's mutability since we'll be coercing mutability
838 let a = Ty::new_adt(
839 self.tcx,
840 pin,
841 self.tcx.mk_args(&[Ty::new_ref(self.tcx, a_region, a_ty, mut_b).into()]),
842 );
843
844 // To complete the reborrow, we need to make sure we can unify the inner types, and if so we
845 // add the adjustments.
846 self.unify_and(a, b, [], Adjust::ReborrowPin(mut_b), ForceLeakCheck::No)
847 }
848
849 fn coerce_from_fn_pointer(
850 &self,
851 a: Ty<'tcx>,
852 a_sig: ty::PolyFnSig<'tcx>,
853 b: Ty<'tcx>,
854 ) -> CoerceResult<'tcx> {
855 debug!(?a_sig, ?b, "coerce_from_fn_pointer");
856 debug_assert!(self.shallow_resolve(b) == b);
857
858 match b.kind() {
859 ty::FnPtr(_, b_hdr) if a_sig.safety().is_safe() && b_hdr.safety.is_unsafe() => {
860 let a = self.tcx.safe_to_unsafe_fn_ty(a_sig);
861 let adjust = Adjust::Pointer(PointerCoercion::UnsafeFnPointer);
862 self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)
863 }
864 _ => self.unify(a, b, ForceLeakCheck::Yes),
865 }
866 }
867
868 fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
869 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
870 debug_assert!(self.shallow_resolve(a) == a);
871 debug_assert!(self.shallow_resolve(b) == b);
872
873 match b.kind() {
874 ty::FnPtr(_, b_hdr) => {
875 let a_sig = self.sig_for_fn_def_coercion(a, Some(b_hdr.safety))?;
876
877 let InferOk { value: a_sig, mut obligations } =
878 self.at(&self.cause, self.param_env).normalize(a_sig);
879 let a = Ty::new_fn_ptr(self.tcx, a_sig);
880
881 let adjust = Adjust::Pointer(PointerCoercion::ReifyFnPointer(b_hdr.safety));
882 let InferOk { value, obligations: o2 } =
883 self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)?;
884
885 obligations.extend(o2);
886 Ok(InferOk { value, obligations })
887 }
888 _ => self.unify(a, b, ForceLeakCheck::No),
889 }
890 }
891
892 /// Attempts to coerce from a closure to a function pointer. Fails
893 /// if the closure has any upvars.
894 fn coerce_closure_to_fn(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
895 debug_assert!(self.shallow_resolve(a) == a);
896 debug_assert!(self.shallow_resolve(b) == b);
897
898 match b.kind() {
899 ty::FnPtr(_, hdr) => {
900 let safety = hdr.safety;
901 let terr = TypeError::Sorts(ty::error::ExpectedFound::new(a, b));
902 let closure_sig = self.sig_for_closure_coercion(a, Some(hdr.safety), terr)?;
903 let pointer_ty = Ty::new_fn_ptr(self.tcx, closure_sig);
904 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
905
906 let adjust = Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety));
907 self.unify_and(pointer_ty, b, [], adjust, ForceLeakCheck::No)
908 }
909 _ => self.unify(a, b, ForceLeakCheck::No),
910 }
911 }
912
913 fn coerce_to_raw_ptr(
914 &self,
915 a: Ty<'tcx>,
916 b: Ty<'tcx>,
917 mutbl_b: hir::Mutability,
918 ) -> CoerceResult<'tcx> {
919 debug!("coerce_to_raw_ptr(a={:?}, b={:?})", a, b);
920 debug_assert!(self.shallow_resolve(a) == a);
921 debug_assert!(self.shallow_resolve(b) == b);
922
923 let (is_ref, mt_a) = match *a.kind() {
924 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
925 ty::RawPtr(ty, mutbl) => (false, ty::TypeAndMut { ty, mutbl }),
926 _ => return self.unify(a, b, ForceLeakCheck::No),
927 };
928 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
929
930 // Check that the types which they point at are compatible.
931 let a_raw = Ty::new_ptr(self.tcx, mt_a.ty, mutbl_b);
932 // Although references and raw ptrs have the same
933 // representation, we still register an Adjust::DerefRef so that
934 // regionck knows that the region for `a` must be valid here.
935 if is_ref {
936 self.unify_and(
937 a_raw,
938 b,
939 [Adjustment { kind: Adjust::Deref(None), target: mt_a.ty }],
940 Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
941 ForceLeakCheck::No,
942 )
943 } else if mt_a.mutbl != mutbl_b {
944 self.unify_and(
945 a_raw,
946 b,
947 [],
948 Adjust::Pointer(PointerCoercion::MutToConstPointer),
949 ForceLeakCheck::No,
950 )
951 } else {
952 self.unify(a_raw, b, ForceLeakCheck::No)
953 }
954 }
955}
956
957impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
958 /// Attempt to coerce an expression to a type, and return the
959 /// adjusted type of the expression, if successful.
960 /// Adjustments are only recorded if the coercion succeeded.
961 /// The expressions *must not* have any preexisting adjustments.
962 pub(crate) fn coerce(
963 &self,
964 expr: &'tcx hir::Expr<'tcx>,
965 expr_ty: Ty<'tcx>,
966 mut target: Ty<'tcx>,
967 allow_two_phase: AllowTwoPhase,
968 cause: Option<ObligationCause<'tcx>>,
969 ) -> RelateResult<'tcx, Ty<'tcx>> {
970 let source = self.try_structurally_resolve_type(expr.span, expr_ty);
971 if self.next_trait_solver() {
972 target = self.try_structurally_resolve_type(
973 cause.as_ref().map_or(expr.span, |cause| cause.span),
974 target,
975 );
976 }
977 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
978
979 let cause =
980 cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
981 let coerce = Coerce::new(
982 self,
983 cause,
984 allow_two_phase,
985 self.tcx.expr_guaranteed_to_constitute_read_for_never(expr),
986 );
987 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
988
989 let (adjustments, _) = self.register_infer_ok_obligations(ok);
990 self.apply_adjustments(expr, adjustments);
991 Ok(if let Err(guar) = expr_ty.error_reported() {
992 Ty::new_error(self.tcx, guar)
993 } else {
994 target
995 })
996 }
997
998 /// Probe whether `expr_ty` can be coerced to `target_ty`. This has no side-effects,
999 /// and may return false positives if types are not yet fully constrained by inference.
1000 ///
1001 /// Returns false if the coercion is not possible, or if the coercion creates any
1002 /// sub-obligations that result in errors.
1003 ///
1004 /// This should only be used for diagnostics.
1005 pub(crate) fn may_coerce(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1006 let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1007 // We don't ever need two-phase here since we throw out the result of the coercion.
1008 // We also just always set `coerce_never` to true, since this is a heuristic.
1009 let coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1010 self.probe(|_| {
1011 // Make sure to structurally resolve the types, since we use
1012 // the `TyKind`s heavily in coercion.
1013 let ocx = ObligationCtxt::new(self);
1014 let structurally_resolve = |ty| {
1015 let ty = self.shallow_resolve(ty);
1016 if self.next_trait_solver()
1017 && let ty::Alias(..) = ty.kind()
1018 {
1019 ocx.structurally_normalize_ty(&cause, self.param_env, ty)
1020 } else {
1021 Ok(ty)
1022 }
1023 };
1024 let Ok(expr_ty) = structurally_resolve(expr_ty) else {
1025 return false;
1026 };
1027 let Ok(target_ty) = structurally_resolve(target_ty) else {
1028 return false;
1029 };
1030
1031 let Ok(ok) = coerce.coerce(expr_ty, target_ty) else {
1032 return false;
1033 };
1034 ocx.register_obligations(ok.obligations);
1035 ocx.try_evaluate_obligations().is_empty()
1036 })
1037 }
1038
1039 /// Given a type and a target type, this function will calculate and return
1040 /// how many dereference steps needed to coerce `expr_ty` to `target`. If
1041 /// it's not possible, return `None`.
1042 pub(crate) fn deref_steps_for_suggestion(
1043 &self,
1044 expr_ty: Ty<'tcx>,
1045 target: Ty<'tcx>,
1046 ) -> Option<usize> {
1047 let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1048 // We don't ever need two-phase here since we throw out the result of the coercion.
1049 let coerce = Coerce::new(self, cause, AllowTwoPhase::No, true);
1050 coerce.autoderef(DUMMY_SP, expr_ty).find_map(|(ty, steps)| {
1051 self.probe(|_| coerce.unify_raw(ty, target, ForceLeakCheck::No)).ok().map(|_| steps)
1052 })
1053 }
1054
1055 /// Given a type, this function will calculate and return the type given
1056 /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1057 ///
1058 /// This function is for diagnostics only, since it does not register
1059 /// trait or region sub-obligations. (presumably we could, but it's not
1060 /// particularly important for diagnostics...)
1061 pub(crate) fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1062 self.autoderef(DUMMY_SP, expr_ty).silence_errors().nth(1).and_then(|(deref_ty, _)| {
1063 self.infcx
1064 .type_implements_trait(
1065 self.tcx.lang_items().deref_mut_trait()?,
1066 [expr_ty],
1067 self.param_env,
1068 )
1069 .may_apply()
1070 .then_some(deref_ty)
1071 })
1072 }
1073
1074 #[instrument(level = "debug", skip(self), ret)]
1075 fn sig_for_coerce_lub(
1076 &self,
1077 ty: Ty<'tcx>,
1078 closure_upvars_terr: TypeError<'tcx>,
1079 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1080 match ty.kind() {
1081 ty::FnDef(..) => self.sig_for_fn_def_coercion(ty, None),
1082 ty::Closure(..) => self.sig_for_closure_coercion(ty, None, closure_upvars_terr),
1083 _ => unreachable!("`sig_for_fn_def_closure_coerce_lub` called with wrong ty: {:?}", ty),
1084 }
1085 }
1086
1087 fn sig_for_fn_def_coercion(
1088 &self,
1089 fndef: Ty<'tcx>,
1090 expected_safety: Option<hir::Safety>,
1091 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1092 let tcx = self.tcx;
1093
1094 let &ty::FnDef(def_id, _) = fndef.kind() else {
1095 unreachable!("`sig_for_fn_def_coercion` called with non-fndef: {:?}", fndef);
1096 };
1097
1098 // Intrinsics are not coercible to function pointers
1099 if tcx.intrinsic(def_id).is_some() {
1100 return Err(TypeError::IntrinsicCast);
1101 }
1102
1103 let fn_attrs = tcx.codegen_fn_attrs(def_id);
1104 if matches!(fn_attrs.inline, InlineAttr::Force { .. }) {
1105 return Err(TypeError::ForceInlineCast);
1106 }
1107
1108 let sig = fndef.fn_sig(tcx);
1109 let sig = if fn_attrs.safe_target_features {
1110 // Allow the coercion if the current function has all the features that would be
1111 // needed to call the coercee safely.
1112 match tcx.adjust_target_feature_sig(def_id, sig, self.body_id.into()) {
1113 Some(adjusted_sig) => adjusted_sig,
1114 None if matches!(expected_safety, Some(hir::Safety::Safe)) => {
1115 return Err(TypeError::TargetFeatureCast(def_id));
1116 }
1117 None => sig,
1118 }
1119 } else {
1120 sig
1121 };
1122
1123 if sig.safety().is_safe() && matches!(expected_safety, Some(hir::Safety::Unsafe)) {
1124 Ok(tcx.safe_to_unsafe_sig(sig))
1125 } else {
1126 Ok(sig)
1127 }
1128 }
1129
1130 fn sig_for_closure_coercion(
1131 &self,
1132 closure: Ty<'tcx>,
1133 expected_safety: Option<hir::Safety>,
1134 closure_upvars_terr: TypeError<'tcx>,
1135 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1136 let tcx = self.tcx;
1137
1138 let ty::Closure(closure_def, closure_args) = closure.kind() else {
1139 unreachable!("`sig_for_closure_coercion` called with non closure ty: {:?}", closure);
1140 };
1141
1142 // At this point we haven't done capture analysis, which means
1143 // that the ClosureArgs just contains an inference variable instead
1144 // of tuple of captured types.
1145 //
1146 // All we care here is if any variable is being captured and not the exact paths,
1147 // so we check `upvars_mentioned` for root variables being captured.
1148 if !tcx.upvars_mentioned(closure_def.expect_local()).is_none_or(|u| u.is_empty()) {
1149 return Err(closure_upvars_terr);
1150 }
1151
1152 // We coerce the closure, which has fn type
1153 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
1154 // to
1155 // `fn(arg0,arg1,...) -> _`
1156 // or
1157 // `unsafe fn(arg0,arg1,...) -> _`
1158 let closure_sig = closure_args.as_closure().sig();
1159 Ok(tcx.signature_unclosure(closure_sig, expected_safety.unwrap_or(hir::Safety::Safe)))
1160 }
1161
1162 /// Given some expressions, their known unified type and another expression,
1163 /// tries to unify the types, potentially inserting coercions on any of the
1164 /// provided expressions and returns their LUB (aka "common supertype").
1165 ///
1166 /// This is really an internal helper. From outside the coercion
1167 /// module, you should instantiate a `CoerceMany` instance.
1168 fn try_find_coercion_lub(
1169 &self,
1170 cause: &ObligationCause<'tcx>,
1171 exprs: &[&'tcx hir::Expr<'tcx>],
1172 prev_ty: Ty<'tcx>,
1173 new: &hir::Expr<'_>,
1174 new_ty: Ty<'tcx>,
1175 ) -> RelateResult<'tcx, Ty<'tcx>> {
1176 let prev_ty = self.try_structurally_resolve_type(cause.span, prev_ty);
1177 let new_ty = self.try_structurally_resolve_type(new.span, new_ty);
1178 debug!(
1179 "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1180 prev_ty,
1181 new_ty,
1182 exprs.len()
1183 );
1184
1185 // Fast Path: don't go through the coercion logic if we're coercing
1186 // a type to itself. This is unfortunately quite perf relevant so
1187 // we do it even though it may mask bugs in the coercion logic.
1188 if prev_ty == new_ty {
1189 return Ok(prev_ty);
1190 }
1191
1192 let terr = TypeError::Sorts(ty::error::ExpectedFound::new(prev_ty, new_ty));
1193 let opt_sigs = match (prev_ty.kind(), new_ty.kind()) {
1194 // Don't coerce pairs of fndefs or pairs of closures to fn ptrs
1195 // if they can just be lubbed.
1196 //
1197 // See #88097 or `lub_closures_before_fnptr_coercion.rs` for where
1198 // we would erroneously coerce closures to fnptrs when attempting to
1199 // coerce a closure to itself.
1200 (ty::FnDef(..), ty::FnDef(..)) | (ty::Closure(..), ty::Closure(..)) => {
1201 let lubbed_ty = self.commit_if_ok(|snapshot| {
1202 let outer_universe = self.infcx.universe();
1203
1204 // We need to eagerly handle nested obligations due to lazy norm.
1205 let result = if self.next_trait_solver() {
1206 let ocx = ObligationCtxt::new(self);
1207 let value = ocx.lub(cause, self.param_env, prev_ty, new_ty)?;
1208 if ocx.try_evaluate_obligations().is_empty() {
1209 Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
1210 } else {
1211 Err(TypeError::Mismatch)
1212 }
1213 } else {
1214 self.at(cause, self.param_env).lub(prev_ty, new_ty)
1215 };
1216
1217 self.leak_check(outer_universe, Some(snapshot))?;
1218 result
1219 });
1220
1221 match lubbed_ty {
1222 Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1223 Err(_) => {
1224 let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1225 let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1226 Some((a_sig, b_sig))
1227 }
1228 }
1229 }
1230
1231 (ty::Closure(..), ty::FnDef(..)) | (ty::FnDef(..), ty::Closure(..)) => {
1232 let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1233 let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1234 Some((a_sig, b_sig))
1235 }
1236 // ty::FnPtr x ty::FnPtr is fine to just be handled through a normal `unify`
1237 // call using `lub` which is what will happen on the normal path.
1238 (ty::FnPtr(..), ty::FnPtr(..)) => None,
1239 _ => None,
1240 };
1241
1242 if let Some((mut a_sig, mut b_sig)) = opt_sigs {
1243 // Allow coercing safe sigs to unsafe sigs
1244 if a_sig.safety().is_safe() && b_sig.safety().is_unsafe() {
1245 a_sig = self.tcx.safe_to_unsafe_sig(a_sig);
1246 } else if b_sig.safety().is_safe() && a_sig.safety().is_unsafe() {
1247 b_sig = self.tcx.safe_to_unsafe_sig(b_sig);
1248 };
1249
1250 // The signature must match.
1251 let (a_sig, b_sig) = self.normalize(new.span, (a_sig, b_sig));
1252 let sig = self
1253 .at(cause, self.param_env)
1254 .lub(a_sig, b_sig)
1255 .map(|ok| self.register_infer_ok_obligations(ok))?;
1256
1257 // Reify both sides and return the reified fn pointer type.
1258 let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
1259 let prev_adjustment = match prev_ty.kind() {
1260 ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1261 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1262 _ => span_bug!(cause.span, "should not try to coerce a {prev_ty} to a fn pointer"),
1263 };
1264 let next_adjustment = match new_ty.kind() {
1265 ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1266 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1267 _ => span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"),
1268 };
1269 for expr in exprs.iter() {
1270 self.apply_adjustments(
1271 expr,
1272 vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1273 );
1274 }
1275 self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1276 return Ok(fn_ptr);
1277 }
1278
1279 // Configure a Coerce instance to compute the LUB.
1280 // We don't allow two-phase borrows on any autorefs this creates since we
1281 // probably aren't processing function arguments here and even if we were,
1282 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1283 // at that time.
1284 //
1285 // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1286 // operate on values and not places, so a never coercion is valid.
1287 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1288 coerce.use_lub = true;
1289
1290 // First try to coerce the new expression to the type of the previous ones,
1291 // but only if the new expression has no coercion already applied to it.
1292 let mut first_error = None;
1293 if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1294 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1295 match result {
1296 Ok(ok) => {
1297 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1298 self.apply_adjustments(new, adjustments);
1299 debug!(
1300 "coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1301 new_ty, prev_ty, target
1302 );
1303 return Ok(target);
1304 }
1305 Err(e) => first_error = Some(e),
1306 }
1307 }
1308
1309 let ok = self
1310 .commit_if_ok(|_| coerce.coerce(prev_ty, new_ty))
1311 // Avoid giving strange errors on failed attempts.
1312 .map_err(|e| first_error.unwrap_or(e))?;
1313
1314 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1315 for expr in exprs {
1316 self.apply_adjustments(expr, adjustments.clone());
1317 }
1318 debug!(
1319 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1320 prev_ty, new_ty, target
1321 );
1322 Ok(target)
1323 }
1324}
1325
1326/// Check whether `ty` can be coerced to `output_ty`.
1327/// Used from clippy.
1328pub fn can_coerce<'tcx>(
1329 tcx: TyCtxt<'tcx>,
1330 param_env: ty::ParamEnv<'tcx>,
1331 body_id: LocalDefId,
1332 ty: Ty<'tcx>,
1333 output_ty: Ty<'tcx>,
1334) -> bool {
1335 let root_ctxt = crate::typeck_root_ctxt::TypeckRootCtxt::new(tcx, body_id);
1336 let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, body_id);
1337 fn_ctxt.may_coerce(ty, output_ty)
1338}
1339
1340/// CoerceMany encapsulates the pattern you should use when you have
1341/// many expressions that are all getting coerced to a common
1342/// type. This arises, for example, when you have a match (the result
1343/// of each arm is coerced to a common type). It also arises in less
1344/// obvious places, such as when you have many `break foo` expressions
1345/// that target the same loop, or the various `return` expressions in
1346/// a function.
1347///
1348/// The basic protocol is as follows:
1349///
1350/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1351/// This will also serve as the "starting LUB". The expectation is
1352/// that this type is something which all of the expressions *must*
1353/// be coercible to. Use a fresh type variable if needed.
1354/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1355/// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1356/// unit. This happens for example if you have a `break` with no expression,
1357/// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1358/// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1359/// from you so that you don't have to worry your pretty head about it.
1360/// But if an error is reported, the final type will be `err`.
1361/// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1362/// previously coerced expressions.
1363/// - When all done, invoke `complete()`. This will return the LUB of
1364/// all your expressions.
1365/// - WARNING: I don't believe this final type is guaranteed to be
1366/// related to your initial `expected_ty` in any particular way,
1367/// although it will typically be a subtype, so you should check it.
1368/// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1369/// previously coerced expressions.
1370///
1371/// Example:
1372///
1373/// ```ignore (illustrative)
1374/// let mut coerce = CoerceMany::new(expected_ty);
1375/// for expr in exprs {
1376/// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1377/// coerce.coerce(fcx, &cause, expr, expr_ty);
1378/// }
1379/// let final_ty = coerce.complete(fcx);
1380/// ```
1381pub(crate) struct CoerceMany<'tcx> {
1382 expected_ty: Ty<'tcx>,
1383 final_ty: Option<Ty<'tcx>>,
1384 expressions: Vec<&'tcx hir::Expr<'tcx>>,
1385}
1386
1387impl<'tcx> CoerceMany<'tcx> {
1388 /// Creates a `CoerceMany` with a default capacity of 1. If the full set of
1389 /// coercion sites is known before hand, consider `with_capacity()` instead
1390 /// to avoid allocation.
1391 pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self {
1392 Self::with_capacity(expected_ty, 1)
1393 }
1394
1395 /// Creates a `CoerceMany` with a given capacity.
1396 pub(crate) fn with_capacity(expected_ty: Ty<'tcx>, capacity: usize) -> Self {
1397 CoerceMany { expected_ty, final_ty: None, expressions: Vec::with_capacity(capacity) }
1398 }
1399
1400 /// Returns the "expected type" with which this coercion was
1401 /// constructed. This represents the "downward propagated" type
1402 /// that was given to us at the start of typing whatever construct
1403 /// we are typing (e.g., the match expression).
1404 ///
1405 /// Typically, this is used as the expected type when
1406 /// type-checking each of the alternative expressions whose types
1407 /// we are trying to merge.
1408 pub(crate) fn expected_ty(&self) -> Ty<'tcx> {
1409 self.expected_ty
1410 }
1411
1412 /// Returns the current "merged type", representing our best-guess
1413 /// at the LUB of the expressions we've seen so far (if any). This
1414 /// isn't *final* until you call `self.complete()`, which will return
1415 /// the merged type.
1416 pub(crate) fn merged_ty(&self) -> Ty<'tcx> {
1417 self.final_ty.unwrap_or(self.expected_ty)
1418 }
1419
1420 /// Indicates that the value generated by `expression`, which is
1421 /// of type `expression_ty`, is one of the possibilities that we
1422 /// could coerce from. This will record `expression`, and later
1423 /// calls to `coerce` may come back and add adjustments and things
1424 /// if necessary.
1425 pub(crate) fn coerce<'a>(
1426 &mut self,
1427 fcx: &FnCtxt<'a, 'tcx>,
1428 cause: &ObligationCause<'tcx>,
1429 expression: &'tcx hir::Expr<'tcx>,
1430 expression_ty: Ty<'tcx>,
1431 ) {
1432 self.coerce_inner(fcx, cause, Some(expression), expression_ty, |_| {}, false)
1433 }
1434
1435 /// Indicates that one of the inputs is a "forced unit". This
1436 /// occurs in a case like `if foo { ... };`, where the missing else
1437 /// generates a "forced unit". Another example is a `loop { break;
1438 /// }`, where the `break` has no argument expression. We treat
1439 /// these cases slightly differently for error-reporting
1440 /// purposes. Note that these tend to correspond to cases where
1441 /// the `()` expression is implicit in the source, and hence we do
1442 /// not take an expression argument.
1443 ///
1444 /// The `augment_error` gives you a chance to extend the error
1445 /// message, in case any results (e.g., we use this to suggest
1446 /// removing a `;`).
1447 pub(crate) fn coerce_forced_unit<'a>(
1448 &mut self,
1449 fcx: &FnCtxt<'a, 'tcx>,
1450 cause: &ObligationCause<'tcx>,
1451 augment_error: impl FnOnce(&mut Diag<'_>),
1452 label_unit_as_expected: bool,
1453 ) {
1454 self.coerce_inner(
1455 fcx,
1456 cause,
1457 None,
1458 fcx.tcx.types.unit,
1459 augment_error,
1460 label_unit_as_expected,
1461 )
1462 }
1463
1464 /// The inner coercion "engine". If `expression` is `None`, this
1465 /// is a forced-unit case, and hence `expression_ty` must be
1466 /// `Nil`.
1467 #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1468 pub(crate) fn coerce_inner<'a>(
1469 &mut self,
1470 fcx: &FnCtxt<'a, 'tcx>,
1471 cause: &ObligationCause<'tcx>,
1472 expression: Option<&'tcx hir::Expr<'tcx>>,
1473 mut expression_ty: Ty<'tcx>,
1474 augment_error: impl FnOnce(&mut Diag<'_>),
1475 label_expression_as_expected: bool,
1476 ) {
1477 // Incorporate whatever type inference information we have
1478 // until now; in principle we might also want to process
1479 // pending obligations, but doing so should only improve
1480 // compatibility (hopefully that is true) by helping us
1481 // uncover never types better.
1482 if expression_ty.is_ty_var() {
1483 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1484 }
1485
1486 // If we see any error types, just propagate that error
1487 // upwards.
1488 if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1489 self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1490 return;
1491 }
1492
1493 let (expected, found) = if label_expression_as_expected {
1494 // In the case where this is a "forced unit", like
1495 // `break`, we want to call the `()` "expected"
1496 // since it is implied by the syntax.
1497 // (Note: not all force-units work this way.)"
1498 (expression_ty, self.merged_ty())
1499 } else {
1500 // Otherwise, the "expected" type for error
1501 // reporting is the current unification type,
1502 // which is basically the LUB of the expressions
1503 // we've seen so far (combined with the expected
1504 // type)
1505 (self.merged_ty(), expression_ty)
1506 };
1507
1508 // Handle the actual type unification etc.
1509 let result = if let Some(expression) = expression {
1510 if self.expressions.is_empty() {
1511 // Special-case the first expression we are coercing.
1512 // To be honest, I'm not entirely sure why we do this.
1513 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1514 fcx.coerce(
1515 expression,
1516 expression_ty,
1517 self.expected_ty,
1518 AllowTwoPhase::No,
1519 Some(cause.clone()),
1520 )
1521 } else {
1522 fcx.try_find_coercion_lub(
1523 cause,
1524 &self.expressions,
1525 self.merged_ty(),
1526 expression,
1527 expression_ty,
1528 )
1529 }
1530 } else {
1531 // this is a hack for cases where we default to `()` because
1532 // the expression etc has been omitted from the source. An
1533 // example is an `if let` without an else:
1534 //
1535 // if let Some(x) = ... { }
1536 //
1537 // we wind up with a second match arm that is like `_ =>
1538 // ()`. That is the case we are considering here. We take
1539 // a different path to get the right "expected, found"
1540 // message and so forth (and because we know that
1541 // `expression_ty` will be unit).
1542 //
1543 // Another example is `break` with no argument expression.
1544 assert!(expression_ty.is_unit(), "if let hack without unit type");
1545 fcx.at(cause, fcx.param_env)
1546 .eq(
1547 // needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1548 DefineOpaqueTypes::Yes,
1549 expected,
1550 found,
1551 )
1552 .map(|infer_ok| {
1553 fcx.register_infer_ok_obligations(infer_ok);
1554 expression_ty
1555 })
1556 };
1557
1558 debug!(?result);
1559 match result {
1560 Ok(v) => {
1561 self.final_ty = Some(v);
1562 if let Some(e) = expression {
1563 self.expressions.push(e);
1564 }
1565 }
1566 Err(coercion_error) => {
1567 // Mark that we've failed to coerce the types here to suppress
1568 // any superfluous errors we might encounter while trying to
1569 // emit or provide suggestions on how to fix the initial error.
1570 fcx.set_tainted_by_errors(
1571 fcx.dcx().span_delayed_bug(cause.span, "coercion error but no error emitted"),
1572 );
1573 let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
1574
1575 let mut err;
1576 let mut unsized_return = false;
1577 match *cause.code() {
1578 ObligationCauseCode::ReturnNoExpression => {
1579 err = struct_span_code_err!(
1580 fcx.dcx(),
1581 cause.span,
1582 E0069,
1583 "`return;` in a function whose return type is not `()`"
1584 );
1585 if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1586 {
1587 err.span_suggestion_verbose(
1588 cause.span.shrink_to_hi(),
1589 "give the `return` a value of the expected type",
1590 format!(" {value}"),
1591 Applicability::HasPlaceholders,
1592 );
1593 }
1594 err.span_label(cause.span, "return type is not `()`");
1595 }
1596 ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
1597 err = self.report_return_mismatched_types(
1598 cause,
1599 expected,
1600 found,
1601 coercion_error,
1602 fcx,
1603 blk_id,
1604 expression,
1605 );
1606 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1607 }
1608 ObligationCauseCode::ReturnValue(return_expr_id) => {
1609 err = self.report_return_mismatched_types(
1610 cause,
1611 expected,
1612 found,
1613 coercion_error,
1614 fcx,
1615 return_expr_id,
1616 expression,
1617 );
1618 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1619 }
1620 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1621 arm_span,
1622 arm_ty,
1623 prior_arm_ty,
1624 ref prior_non_diverging_arms,
1625 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1626 ..
1627 }) => {
1628 err = fcx.err_ctxt().report_mismatched_types(
1629 cause,
1630 fcx.param_env,
1631 expected,
1632 found,
1633 coercion_error,
1634 );
1635 // Check that we're actually in the second or later arm
1636 if prior_non_diverging_arms.len() > 0 {
1637 self.suggest_boxing_tail_for_return_position_impl_trait(
1638 fcx,
1639 &mut err,
1640 rpit_def_id,
1641 arm_ty,
1642 prior_arm_ty,
1643 prior_non_diverging_arms
1644 .iter()
1645 .chain(std::iter::once(&arm_span))
1646 .copied(),
1647 );
1648 }
1649 }
1650 ObligationCauseCode::IfExpression {
1651 expr_id,
1652 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1653 } => {
1654 let hir::Node::Expr(hir::Expr {
1655 kind: hir::ExprKind::If(_, then_expr, Some(else_expr)),
1656 ..
1657 }) = fcx.tcx.hir_node(expr_id)
1658 else {
1659 unreachable!();
1660 };
1661 err = fcx.err_ctxt().report_mismatched_types(
1662 cause,
1663 fcx.param_env,
1664 expected,
1665 found,
1666 coercion_error,
1667 );
1668 let then_span = fcx.find_block_span_from_hir_id(then_expr.hir_id);
1669 let else_span = fcx.find_block_span_from_hir_id(else_expr.hir_id);
1670 // Don't suggest wrapping whole block in `Box::new`.
1671 if then_span != then_expr.span && else_span != else_expr.span {
1672 let then_ty = fcx.typeck_results.borrow().expr_ty(then_expr);
1673 let else_ty = fcx.typeck_results.borrow().expr_ty(else_expr);
1674 self.suggest_boxing_tail_for_return_position_impl_trait(
1675 fcx,
1676 &mut err,
1677 rpit_def_id,
1678 then_ty,
1679 else_ty,
1680 [then_span, else_span].into_iter(),
1681 );
1682 }
1683 }
1684 _ => {
1685 err = fcx.err_ctxt().report_mismatched_types(
1686 cause,
1687 fcx.param_env,
1688 expected,
1689 found,
1690 coercion_error,
1691 );
1692 }
1693 }
1694
1695 augment_error(&mut err);
1696
1697 if let Some(expr) = expression {
1698 if let hir::ExprKind::Loop(
1699 _,
1700 _,
1701 loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop),
1702 _,
1703 ) = expr.kind
1704 {
1705 let loop_type = if loop_src == hir::LoopSource::While {
1706 "`while` loops"
1707 } else {
1708 "`for` loops"
1709 };
1710
1711 err.note(format!("{loop_type} evaluate to unit type `()`"));
1712 }
1713
1714 fcx.emit_coerce_suggestions(
1715 &mut err,
1716 expr,
1717 found,
1718 expected,
1719 None,
1720 Some(coercion_error),
1721 );
1722 }
1723
1724 let reported = err.emit_unless_delay(unsized_return);
1725
1726 self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
1727 }
1728 }
1729 }
1730
1731 fn suggest_boxing_tail_for_return_position_impl_trait(
1732 &self,
1733 fcx: &FnCtxt<'_, 'tcx>,
1734 err: &mut Diag<'_>,
1735 rpit_def_id: LocalDefId,
1736 a_ty: Ty<'tcx>,
1737 b_ty: Ty<'tcx>,
1738 arm_spans: impl Iterator<Item = Span>,
1739 ) {
1740 let compatible = |ty: Ty<'tcx>| {
1741 fcx.probe(|_| {
1742 let ocx = ObligationCtxt::new(fcx);
1743 ocx.register_obligations(
1744 fcx.tcx.item_self_bounds(rpit_def_id).iter_identity().filter_map(|clause| {
1745 let predicate = clause
1746 .kind()
1747 .map_bound(|clause| match clause {
1748 ty::ClauseKind::Trait(trait_pred) => Some(ty::ClauseKind::Trait(
1749 trait_pred.with_replaced_self_ty(fcx.tcx, ty),
1750 )),
1751 ty::ClauseKind::Projection(proj_pred) => {
1752 Some(ty::ClauseKind::Projection(
1753 proj_pred.with_replaced_self_ty(fcx.tcx, ty),
1754 ))
1755 }
1756 _ => None,
1757 })
1758 .transpose()?;
1759 Some(Obligation::new(
1760 fcx.tcx,
1761 ObligationCause::dummy(),
1762 fcx.param_env,
1763 predicate,
1764 ))
1765 }),
1766 );
1767 ocx.try_evaluate_obligations().is_empty()
1768 })
1769 };
1770
1771 if !compatible(a_ty) || !compatible(b_ty) {
1772 return;
1773 }
1774
1775 let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
1776 err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1777 start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1778 end_sp: rpid_def_span.shrink_to_hi(),
1779 });
1780
1781 let (starts, ends) =
1782 arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
1783 err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
1784 }
1785
1786 fn report_return_mismatched_types<'infcx>(
1787 &self,
1788 cause: &ObligationCause<'tcx>,
1789 expected: Ty<'tcx>,
1790 found: Ty<'tcx>,
1791 ty_err: TypeError<'tcx>,
1792 fcx: &'infcx FnCtxt<'_, 'tcx>,
1793 block_or_return_id: hir::HirId,
1794 expression: Option<&'tcx hir::Expr<'tcx>>,
1795 ) -> Diag<'infcx> {
1796 let mut err =
1797 fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err);
1798
1799 let due_to_block = matches!(fcx.tcx.hir_node(block_or_return_id), hir::Node::Block(..));
1800 let parent = fcx.tcx.parent_hir_node(block_or_return_id);
1801 if let Some(expr) = expression
1802 && let hir::Node::Expr(&hir::Expr {
1803 kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
1804 ..
1805 }) = parent
1806 {
1807 let needs_block =
1808 !matches!(fcx.tcx.hir_body(body).value.kind, hir::ExprKind::Block(..));
1809 fcx.suggest_missing_semicolon(&mut err, expr, expected, needs_block, true);
1810 }
1811 // Verify that this is a tail expression of a function, otherwise the
1812 // label pointing out the cause for the type coercion will be wrong
1813 // as prior return coercions would not be relevant (#57664).
1814 if let Some(expr) = expression
1815 && due_to_block
1816 {
1817 fcx.suggest_missing_semicolon(&mut err, expr, expected, false, false);
1818 let pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1819 &mut err,
1820 expr,
1821 expected,
1822 found,
1823 block_or_return_id,
1824 );
1825 if let Some(cond_expr) = fcx.tcx.hir_get_if_cause(expr.hir_id)
1826 && expected.is_unit()
1827 && !pointing_at_return_type
1828 // If the block is from an external macro or try (`?`) desugaring, then
1829 // do not suggest adding a semicolon, because there's nowhere to put it.
1830 // See issues #81943 and #87051.
1831 && matches!(
1832 cond_expr.span.desugaring_kind(),
1833 None | Some(DesugaringKind::WhileLoop)
1834 )
1835 && !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
1836 && !matches!(
1837 cond_expr.kind,
1838 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))
1839 )
1840 {
1841 if let ObligationCauseCode::BlockTailExpression(hir_id, hir::MatchSource::Normal) =
1842 cause.code()
1843 && let hir::Node::Block(block) = fcx.tcx.hir_node(*hir_id)
1844 && let hir::Node::Expr(expr) = fcx.tcx.parent_hir_node(block.hir_id)
1845 && let hir::Node::Expr(if_expr) = fcx.tcx.parent_hir_node(expr.hir_id)
1846 && let hir::ExprKind::If(_cond, _then, None) = if_expr.kind
1847 {
1848 err.span_label(
1849 cond_expr.span,
1850 "`if` expressions without `else` arms expect their inner expression to be `()`",
1851 );
1852 } else {
1853 err.span_label(cond_expr.span, "expected this to be `()`");
1854 }
1855 if expr.can_have_side_effects() {
1856 fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1857 }
1858 }
1859 }
1860
1861 // If this is due to an explicit `return`, suggest adding a return type.
1862 if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
1863 && !due_to_block
1864 {
1865 fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
1866 }
1867
1868 // If this is due to a block, then maybe we forgot a `return`/`break`.
1869 if due_to_block
1870 && let Some(expr) = expression
1871 && let Some(parent_fn_decl) =
1872 fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_id))
1873 {
1874 fcx.suggest_missing_break_or_return_expr(
1875 &mut err,
1876 expr,
1877 parent_fn_decl,
1878 expected,
1879 found,
1880 block_or_return_id,
1881 fcx.body_id,
1882 );
1883 }
1884
1885 let ret_coercion_span = fcx.ret_coercion_span.get();
1886
1887 if let Some(sp) = ret_coercion_span
1888 // If the closure has an explicit return type annotation, or if
1889 // the closure's return type has been inferred from outside
1890 // requirements (such as an Fn* trait bound), then a type error
1891 // may occur at the first return expression we see in the closure
1892 // (if it conflicts with the declared return type). Skip adding a
1893 // note in this case, since it would be incorrect.
1894 && let Some(fn_sig) = fcx.body_fn_sig()
1895 && fn_sig.output().is_ty_var()
1896 {
1897 err.span_note(sp, format!("return type inferred to be `{expected}` here"));
1898 }
1899
1900 err
1901 }
1902
1903 /// Checks whether the return type is unsized via an obligation, which makes
1904 /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
1905 /// false but technically valid for typeck.
1906 fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
1907 if let Some(sig) = fcx.body_fn_sig() {
1908 !fcx.predicate_may_hold(&Obligation::new(
1909 fcx.tcx,
1910 ObligationCause::dummy(),
1911 fcx.param_env,
1912 ty::TraitRef::new(
1913 fcx.tcx,
1914 fcx.tcx.require_lang_item(hir::LangItem::Sized, DUMMY_SP),
1915 [sig.output()],
1916 ),
1917 ))
1918 } else {
1919 false
1920 }
1921 }
1922
1923 pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1924 if let Some(final_ty) = self.final_ty {
1925 final_ty
1926 } else {
1927 // If we only had inputs that were of type `!` (or no
1928 // inputs at all), then the final type is `!`.
1929 assert!(self.expressions.is_empty());
1930 fcx.tcx.types.never
1931 }
1932 }
1933}
1934
1935/// Recursively visit goals to decide whether an unsizing is possible.
1936/// `Break`s when it isn't, and an error should be raised.
1937/// `Continue`s when an unsizing ok based on an implementation of the `Unsize` trait / lang item.
1938struct CoerceVisitor<'a, 'tcx> {
1939 fcx: &'a FnCtxt<'a, 'tcx>,
1940 span: Span,
1941}
1942
1943impl<'tcx> ProofTreeVisitor<'tcx> for CoerceVisitor<'_, 'tcx> {
1944 type Result = ControlFlow<()>;
1945
1946 fn span(&self) -> Span {
1947 self.span
1948 }
1949
1950 fn visit_goal(&mut self, goal: &inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
1951 let Some(pred) = goal.goal().predicate.as_trait_clause() else {
1952 return ControlFlow::Continue(());
1953 };
1954
1955 // Make sure this predicate is referring to either an `Unsize` or `CoerceUnsized` trait,
1956 // Otherwise there's nothing to do.
1957 if !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
1958 && !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::CoerceUnsized)
1959 {
1960 return ControlFlow::Continue(());
1961 }
1962
1963 match goal.result() {
1964 // If we prove the `Unsize` or `CoerceUnsized` goal, continue recursing.
1965 Ok(Certainty::Yes) => ControlFlow::Continue(()),
1966 Err(NoSolution) => {
1967 // Even if we find no solution, continue recursing if we find a single candidate
1968 // for which we're shallowly certain it holds to get the right error source.
1969 if let [only_candidate] = &goal.candidates()[..]
1970 && only_candidate.shallow_certainty() == Certainty::Yes
1971 {
1972 only_candidate.visit_nested_no_probe(self)
1973 } else {
1974 ControlFlow::Break(())
1975 }
1976 }
1977 Ok(Certainty::Maybe { .. }) => {
1978 // FIXME: structurally normalize?
1979 if self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
1980 && let ty::Dynamic(..) = pred.skip_binder().trait_ref.args.type_at(1).kind()
1981 && let ty::Infer(ty::TyVar(vid)) = *pred.self_ty().skip_binder().kind()
1982 && self.fcx.type_var_is_sized(vid)
1983 {
1984 // We get here when trying to unsize a type variable to a `dyn Trait`,
1985 // knowing that that variable is sized. Unsizing definitely has to happen in that case.
1986 // If the variable weren't sized, we may not need an unsizing coercion.
1987 // In general, we don't want to add coercions too eagerly since it makes error messages much worse.
1988 ControlFlow::Continue(())
1989 } else if let Some(cand) = goal.unique_applicable_candidate()
1990 && cand.shallow_certainty() == Certainty::Yes
1991 {
1992 cand.visit_nested_no_probe(self)
1993 } else {
1994 ControlFlow::Break(())
1995 }
1996 }
1997 }
1998 }
1999}