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