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