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(def_id, ..) => {
1295 // Intrinsics are not coercible to function pointers
1296 if self.tcx.intrinsic(def_id).is_some() {
1297 return Err(TypeError::IntrinsicCast);
1298 }
1299 Adjust::Pointer(PointerCoercion::ReifyFnPointer)
1300 }
1301 _ => span_bug!(cause.span, "should not try to coerce a {prev_ty} to a fn pointer"),
1302 };
1303 let next_adjustment = match new_ty.kind() {
1304 ty::Closure(..) => {
1305 Adjust::Pointer(PointerCoercion::ClosureFnPointer(b_sig.safety()))
1306 }
1307 ty::FnDef(def_id, ..) => {
1308 // Intrinsics are not coercible to function pointers
1309 if self.tcx.intrinsic(def_id).is_some() {
1310 return Err(TypeError::IntrinsicCast);
1311 }
1312 Adjust::Pointer(PointerCoercion::ReifyFnPointer)
1313 }
1314 _ => span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"),
1315 };
1316 for expr in exprs.iter().map(|e| e.as_coercion_site()) {
1317 self.apply_adjustments(
1318 expr,
1319 vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1320 );
1321 }
1322 self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1323 return Ok(fn_ptr);
1324 }
1325
1326 // Configure a Coerce instance to compute the LUB.
1327 // We don't allow two-phase borrows on any autorefs this creates since we
1328 // probably aren't processing function arguments here and even if we were,
1329 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1330 // at that time.
1331 //
1332 // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1333 // operate on values and not places, so a never coercion is valid.
1334 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1335 coerce.use_lub = true;
1336
1337 // First try to coerce the new expression to the type of the previous ones,
1338 // but only if the new expression has no coercion already applied to it.
1339 let mut first_error = None;
1340 if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1341 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1342 match result {
1343 Ok(ok) => {
1344 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1345 self.apply_adjustments(new, adjustments);
1346 debug!(
1347 "coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1348 new_ty, prev_ty, target
1349 );
1350 return Ok(target);
1351 }
1352 Err(e) => first_error = Some(e),
1353 }
1354 }
1355
1356 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1357 Err(_) => {
1358 // Avoid giving strange errors on failed attempts.
1359 if let Some(e) = first_error {
1360 Err(e)
1361 } else {
1362 Err(self
1363 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1364 .unwrap_err())
1365 }
1366 }
1367 Ok(ok) => {
1368 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1369 for expr in exprs {
1370 let expr = expr.as_coercion_site();
1371 self.apply_adjustments(expr, adjustments.clone());
1372 }
1373 debug!(
1374 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1375 prev_ty, new_ty, target
1376 );
1377 Ok(target)
1378 }
1379 }
1380 }
1381}
1382
1383/// Check whether `ty` can be coerced to `output_ty`.
1384/// Used from clippy.
1385pub fn can_coerce<'tcx>(
1386 tcx: TyCtxt<'tcx>,
1387 param_env: ty::ParamEnv<'tcx>,
1388 body_id: LocalDefId,
1389 ty: Ty<'tcx>,
1390 output_ty: Ty<'tcx>,
1391) -> bool {
1392 let root_ctxt = crate::typeck_root_ctxt::TypeckRootCtxt::new(tcx, body_id);
1393 let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, body_id);
1394 fn_ctxt.may_coerce(ty, output_ty)
1395}
1396
1397/// CoerceMany encapsulates the pattern you should use when you have
1398/// many expressions that are all getting coerced to a common
1399/// type. This arises, for example, when you have a match (the result
1400/// of each arm is coerced to a common type). It also arises in less
1401/// obvious places, such as when you have many `break foo` expressions
1402/// that target the same loop, or the various `return` expressions in
1403/// a function.
1404///
1405/// The basic protocol is as follows:
1406///
1407/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1408/// This will also serve as the "starting LUB". The expectation is
1409/// that this type is something which all of the expressions *must*
1410/// be coercible to. Use a fresh type variable if needed.
1411/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1412/// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1413/// unit. This happens for example if you have a `break` with no expression,
1414/// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1415/// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1416/// from you so that you don't have to worry your pretty head about it.
1417/// But if an error is reported, the final type will be `err`.
1418/// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1419/// previously coerced expressions.
1420/// - When all done, invoke `complete()`. This will return the LUB of
1421/// all your expressions.
1422/// - WARNING: I don't believe this final type is guaranteed to be
1423/// related to your initial `expected_ty` in any particular way,
1424/// although it will typically be a subtype, so you should check it.
1425/// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1426/// previously coerced expressions.
1427///
1428/// Example:
1429///
1430/// ```ignore (illustrative)
1431/// let mut coerce = CoerceMany::new(expected_ty);
1432/// for expr in exprs {
1433/// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1434/// coerce.coerce(fcx, &cause, expr, expr_ty);
1435/// }
1436/// let final_ty = coerce.complete(fcx);
1437/// ```
1438pub(crate) struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1439 expected_ty: Ty<'tcx>,
1440 final_ty: Option<Ty<'tcx>>,
1441 expressions: Expressions<'tcx, 'exprs, E>,
1442 pushed: usize,
1443}
1444
1445/// The type of a `CoerceMany` that is storing up the expressions into
1446/// a buffer. We use this in `check/mod.rs` for things like `break`.
1447pub(crate) type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1448
1449enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1450 Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1451 UpFront(&'exprs [E]),
1452}
1453
1454impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1455 /// The usual case; collect the set of expressions dynamically.
1456 /// If the full set of coercion sites is known before hand,
1457 /// consider `with_coercion_sites()` instead to avoid allocation.
1458 pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self {
1459 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1460 }
1461
1462 /// As an optimization, you can create a `CoerceMany` with a
1463 /// preexisting slice of expressions. In this case, you are
1464 /// expected to pass each element in the slice to `coerce(...)` in
1465 /// order. This is used with arrays in particular to avoid
1466 /// needlessly cloning the slice.
1467 pub(crate) fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1468 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1469 }
1470
1471 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1472 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1473 }
1474
1475 /// Returns the "expected type" with which this coercion was
1476 /// constructed. This represents the "downward propagated" type
1477 /// that was given to us at the start of typing whatever construct
1478 /// we are typing (e.g., the match expression).
1479 ///
1480 /// Typically, this is used as the expected type when
1481 /// type-checking each of the alternative expressions whose types
1482 /// we are trying to merge.
1483 pub(crate) fn expected_ty(&self) -> Ty<'tcx> {
1484 self.expected_ty
1485 }
1486
1487 /// Returns the current "merged type", representing our best-guess
1488 /// at the LUB of the expressions we've seen so far (if any). This
1489 /// isn't *final* until you call `self.complete()`, which will return
1490 /// the merged type.
1491 pub(crate) fn merged_ty(&self) -> Ty<'tcx> {
1492 self.final_ty.unwrap_or(self.expected_ty)
1493 }
1494
1495 /// Indicates that the value generated by `expression`, which is
1496 /// of type `expression_ty`, is one of the possibilities that we
1497 /// could coerce from. This will record `expression`, and later
1498 /// calls to `coerce` may come back and add adjustments and things
1499 /// if necessary.
1500 pub(crate) fn coerce<'a>(
1501 &mut self,
1502 fcx: &FnCtxt<'a, 'tcx>,
1503 cause: &ObligationCause<'tcx>,
1504 expression: &'tcx hir::Expr<'tcx>,
1505 expression_ty: Ty<'tcx>,
1506 ) {
1507 self.coerce_inner(fcx, cause, Some(expression), expression_ty, |_| {}, false)
1508 }
1509
1510 /// Indicates that one of the inputs is a "forced unit". This
1511 /// occurs in a case like `if foo { ... };`, where the missing else
1512 /// generates a "forced unit". Another example is a `loop { break;
1513 /// }`, where the `break` has no argument expression. We treat
1514 /// these cases slightly differently for error-reporting
1515 /// purposes. Note that these tend to correspond to cases where
1516 /// the `()` expression is implicit in the source, and hence we do
1517 /// not take an expression argument.
1518 ///
1519 /// The `augment_error` gives you a chance to extend the error
1520 /// message, in case any results (e.g., we use this to suggest
1521 /// removing a `;`).
1522 pub(crate) fn coerce_forced_unit<'a>(
1523 &mut self,
1524 fcx: &FnCtxt<'a, 'tcx>,
1525 cause: &ObligationCause<'tcx>,
1526 augment_error: impl FnOnce(&mut Diag<'_>),
1527 label_unit_as_expected: bool,
1528 ) {
1529 self.coerce_inner(
1530 fcx,
1531 cause,
1532 None,
1533 fcx.tcx.types.unit,
1534 augment_error,
1535 label_unit_as_expected,
1536 )
1537 }
1538
1539 /// The inner coercion "engine". If `expression` is `None`, this
1540 /// is a forced-unit case, and hence `expression_ty` must be
1541 /// `Nil`.
1542 #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1543 pub(crate) fn coerce_inner<'a>(
1544 &mut self,
1545 fcx: &FnCtxt<'a, 'tcx>,
1546 cause: &ObligationCause<'tcx>,
1547 expression: Option<&'tcx hir::Expr<'tcx>>,
1548 mut expression_ty: Ty<'tcx>,
1549 augment_error: impl FnOnce(&mut Diag<'_>),
1550 label_expression_as_expected: bool,
1551 ) {
1552 // Incorporate whatever type inference information we have
1553 // until now; in principle we might also want to process
1554 // pending obligations, but doing so should only improve
1555 // compatibility (hopefully that is true) by helping us
1556 // uncover never types better.
1557 if expression_ty.is_ty_var() {
1558 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1559 }
1560
1561 // If we see any error types, just propagate that error
1562 // upwards.
1563 if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1564 self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1565 return;
1566 }
1567
1568 let (expected, found) = if label_expression_as_expected {
1569 // In the case where this is a "forced unit", like
1570 // `break`, we want to call the `()` "expected"
1571 // since it is implied by the syntax.
1572 // (Note: not all force-units work this way.)"
1573 (expression_ty, self.merged_ty())
1574 } else {
1575 // Otherwise, the "expected" type for error
1576 // reporting is the current unification type,
1577 // which is basically the LUB of the expressions
1578 // we've seen so far (combined with the expected
1579 // type)
1580 (self.merged_ty(), expression_ty)
1581 };
1582
1583 // Handle the actual type unification etc.
1584 let result = if let Some(expression) = expression {
1585 if self.pushed == 0 {
1586 // Special-case the first expression we are coercing.
1587 // To be honest, I'm not entirely sure why we do this.
1588 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1589 fcx.coerce(
1590 expression,
1591 expression_ty,
1592 self.expected_ty,
1593 AllowTwoPhase::No,
1594 Some(cause.clone()),
1595 )
1596 } else {
1597 match self.expressions {
1598 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1599 cause,
1600 exprs,
1601 self.merged_ty(),
1602 expression,
1603 expression_ty,
1604 ),
1605 Expressions::UpFront(coercion_sites) => fcx.try_find_coercion_lub(
1606 cause,
1607 &coercion_sites[0..self.pushed],
1608 self.merged_ty(),
1609 expression,
1610 expression_ty,
1611 ),
1612 }
1613 }
1614 } else {
1615 // this is a hack for cases where we default to `()` because
1616 // the expression etc has been omitted from the source. An
1617 // example is an `if let` without an else:
1618 //
1619 // if let Some(x) = ... { }
1620 //
1621 // we wind up with a second match arm that is like `_ =>
1622 // ()`. That is the case we are considering here. We take
1623 // a different path to get the right "expected, found"
1624 // message and so forth (and because we know that
1625 // `expression_ty` will be unit).
1626 //
1627 // Another example is `break` with no argument expression.
1628 assert!(expression_ty.is_unit(), "if let hack without unit type");
1629 fcx.at(cause, fcx.param_env)
1630 .eq(
1631 // needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1632 DefineOpaqueTypes::Yes,
1633 expected,
1634 found,
1635 )
1636 .map(|infer_ok| {
1637 fcx.register_infer_ok_obligations(infer_ok);
1638 expression_ty
1639 })
1640 };
1641
1642 debug!(?result);
1643 match result {
1644 Ok(v) => {
1645 self.final_ty = Some(v);
1646 if let Some(e) = expression {
1647 match self.expressions {
1648 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1649 Expressions::UpFront(coercion_sites) => {
1650 // if the user gave us an array to validate, check that we got
1651 // the next expression in the list, as expected
1652 assert_eq!(
1653 coercion_sites[self.pushed].as_coercion_site().hir_id,
1654 e.hir_id
1655 );
1656 }
1657 }
1658 self.pushed += 1;
1659 }
1660 }
1661 Err(coercion_error) => {
1662 // Mark that we've failed to coerce the types here to suppress
1663 // any superfluous errors we might encounter while trying to
1664 // emit or provide suggestions on how to fix the initial error.
1665 fcx.set_tainted_by_errors(
1666 fcx.dcx().span_delayed_bug(cause.span, "coercion error but no error emitted"),
1667 );
1668 let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
1669
1670 let mut err;
1671 let mut unsized_return = false;
1672 match *cause.code() {
1673 ObligationCauseCode::ReturnNoExpression => {
1674 err = struct_span_code_err!(
1675 fcx.dcx(),
1676 cause.span,
1677 E0069,
1678 "`return;` in a function whose return type is not `()`"
1679 );
1680 if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1681 {
1682 err.span_suggestion_verbose(
1683 cause.span.shrink_to_hi(),
1684 "give the `return` a value of the expected type",
1685 format!(" {value}"),
1686 Applicability::HasPlaceholders,
1687 );
1688 }
1689 err.span_label(cause.span, "return type is not `()`");
1690 }
1691 ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
1692 err = self.report_return_mismatched_types(
1693 cause,
1694 expected,
1695 found,
1696 coercion_error,
1697 fcx,
1698 blk_id,
1699 expression,
1700 );
1701 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1702 }
1703 ObligationCauseCode::ReturnValue(return_expr_id) => {
1704 err = self.report_return_mismatched_types(
1705 cause,
1706 expected,
1707 found,
1708 coercion_error,
1709 fcx,
1710 return_expr_id,
1711 expression,
1712 );
1713 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1714 }
1715 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1716 arm_span,
1717 arm_ty,
1718 prior_arm_ty,
1719 ref prior_non_diverging_arms,
1720 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1721 ..
1722 }) => {
1723 err = fcx.err_ctxt().report_mismatched_types(
1724 cause,
1725 fcx.param_env,
1726 expected,
1727 found,
1728 coercion_error,
1729 );
1730 // Check that we're actually in the second or later arm
1731 if prior_non_diverging_arms.len() > 0 {
1732 self.suggest_boxing_tail_for_return_position_impl_trait(
1733 fcx,
1734 &mut err,
1735 rpit_def_id,
1736 arm_ty,
1737 prior_arm_ty,
1738 prior_non_diverging_arms
1739 .iter()
1740 .chain(std::iter::once(&arm_span))
1741 .copied(),
1742 );
1743 }
1744 }
1745 ObligationCauseCode::IfExpression {
1746 expr_id,
1747 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1748 } => {
1749 let hir::Node::Expr(hir::Expr {
1750 kind: hir::ExprKind::If(_, then_expr, Some(else_expr)),
1751 ..
1752 }) = fcx.tcx.hir_node(expr_id)
1753 else {
1754 unreachable!();
1755 };
1756 err = fcx.err_ctxt().report_mismatched_types(
1757 cause,
1758 fcx.param_env,
1759 expected,
1760 found,
1761 coercion_error,
1762 );
1763 let then_span = fcx.find_block_span_from_hir_id(then_expr.hir_id);
1764 let else_span = fcx.find_block_span_from_hir_id(else_expr.hir_id);
1765 // Don't suggest wrapping whole block in `Box::new`.
1766 if then_span != then_expr.span && else_span != else_expr.span {
1767 let then_ty = fcx.typeck_results.borrow().expr_ty(then_expr);
1768 let else_ty = fcx.typeck_results.borrow().expr_ty(else_expr);
1769 self.suggest_boxing_tail_for_return_position_impl_trait(
1770 fcx,
1771 &mut err,
1772 rpit_def_id,
1773 then_ty,
1774 else_ty,
1775 [then_span, else_span].into_iter(),
1776 );
1777 }
1778 }
1779 _ => {
1780 err = fcx.err_ctxt().report_mismatched_types(
1781 cause,
1782 fcx.param_env,
1783 expected,
1784 found,
1785 coercion_error,
1786 );
1787 }
1788 }
1789
1790 augment_error(&mut err);
1791
1792 if let Some(expr) = expression {
1793 if let hir::ExprKind::Loop(
1794 _,
1795 _,
1796 loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop),
1797 _,
1798 ) = expr.kind
1799 {
1800 let loop_type = if loop_src == hir::LoopSource::While {
1801 "`while` loops"
1802 } else {
1803 "`for` loops"
1804 };
1805
1806 err.note(format!("{loop_type} evaluate to unit type `()`"));
1807 }
1808
1809 fcx.emit_coerce_suggestions(
1810 &mut err,
1811 expr,
1812 found,
1813 expected,
1814 None,
1815 Some(coercion_error),
1816 );
1817 }
1818
1819 let reported = err.emit_unless_delay(unsized_return);
1820
1821 self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
1822 }
1823 }
1824 }
1825
1826 fn suggest_boxing_tail_for_return_position_impl_trait(
1827 &self,
1828 fcx: &FnCtxt<'_, 'tcx>,
1829 err: &mut Diag<'_>,
1830 rpit_def_id: LocalDefId,
1831 a_ty: Ty<'tcx>,
1832 b_ty: Ty<'tcx>,
1833 arm_spans: impl Iterator<Item = Span>,
1834 ) {
1835 let compatible = |ty: Ty<'tcx>| {
1836 fcx.probe(|_| {
1837 let ocx = ObligationCtxt::new(fcx);
1838 ocx.register_obligations(
1839 fcx.tcx.item_self_bounds(rpit_def_id).iter_identity().filter_map(|clause| {
1840 let predicate = clause
1841 .kind()
1842 .map_bound(|clause| match clause {
1843 ty::ClauseKind::Trait(trait_pred) => Some(ty::ClauseKind::Trait(
1844 trait_pred.with_replaced_self_ty(fcx.tcx, ty),
1845 )),
1846 ty::ClauseKind::Projection(proj_pred) => {
1847 Some(ty::ClauseKind::Projection(
1848 proj_pred.with_replaced_self_ty(fcx.tcx, ty),
1849 ))
1850 }
1851 _ => None,
1852 })
1853 .transpose()?;
1854 Some(Obligation::new(
1855 fcx.tcx,
1856 ObligationCause::dummy(),
1857 fcx.param_env,
1858 predicate,
1859 ))
1860 }),
1861 );
1862 ocx.try_evaluate_obligations().is_empty()
1863 })
1864 };
1865
1866 if !compatible(a_ty) || !compatible(b_ty) {
1867 return;
1868 }
1869
1870 let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
1871 err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1872 start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1873 end_sp: rpid_def_span.shrink_to_hi(),
1874 });
1875
1876 let (starts, ends) =
1877 arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
1878 err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
1879 }
1880
1881 fn report_return_mismatched_types<'infcx>(
1882 &self,
1883 cause: &ObligationCause<'tcx>,
1884 expected: Ty<'tcx>,
1885 found: Ty<'tcx>,
1886 ty_err: TypeError<'tcx>,
1887 fcx: &'infcx FnCtxt<'_, 'tcx>,
1888 block_or_return_id: hir::HirId,
1889 expression: Option<&'tcx hir::Expr<'tcx>>,
1890 ) -> Diag<'infcx> {
1891 let mut err =
1892 fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err);
1893
1894 let due_to_block = matches!(fcx.tcx.hir_node(block_or_return_id), hir::Node::Block(..));
1895 let parent = fcx.tcx.parent_hir_node(block_or_return_id);
1896 if let Some(expr) = expression
1897 && let hir::Node::Expr(&hir::Expr {
1898 kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
1899 ..
1900 }) = parent
1901 {
1902 let needs_block =
1903 !matches!(fcx.tcx.hir_body(body).value.kind, hir::ExprKind::Block(..));
1904 fcx.suggest_missing_semicolon(&mut err, expr, expected, needs_block, true);
1905 }
1906 // Verify that this is a tail expression of a function, otherwise the
1907 // label pointing out the cause for the type coercion will be wrong
1908 // as prior return coercions would not be relevant (#57664).
1909 if let Some(expr) = expression
1910 && due_to_block
1911 {
1912 fcx.suggest_missing_semicolon(&mut err, expr, expected, false, false);
1913 let pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1914 &mut err,
1915 expr,
1916 expected,
1917 found,
1918 block_or_return_id,
1919 );
1920 if let Some(cond_expr) = fcx.tcx.hir_get_if_cause(expr.hir_id)
1921 && expected.is_unit()
1922 && !pointing_at_return_type
1923 // If the block is from an external macro or try (`?`) desugaring, then
1924 // do not suggest adding a semicolon, because there's nowhere to put it.
1925 // See issues #81943 and #87051.
1926 && matches!(
1927 cond_expr.span.desugaring_kind(),
1928 None | Some(DesugaringKind::WhileLoop)
1929 )
1930 && !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
1931 && !matches!(
1932 cond_expr.kind,
1933 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))
1934 )
1935 {
1936 err.span_label(cond_expr.span, "expected this to be `()`");
1937 if expr.can_have_side_effects() {
1938 fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1939 }
1940 }
1941 }
1942
1943 // If this is due to an explicit `return`, suggest adding a return type.
1944 if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
1945 && !due_to_block
1946 {
1947 fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
1948 }
1949
1950 // If this is due to a block, then maybe we forgot a `return`/`break`.
1951 if due_to_block
1952 && let Some(expr) = expression
1953 && let Some(parent_fn_decl) =
1954 fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_id))
1955 {
1956 fcx.suggest_missing_break_or_return_expr(
1957 &mut err,
1958 expr,
1959 parent_fn_decl,
1960 expected,
1961 found,
1962 block_or_return_id,
1963 fcx.body_id,
1964 );
1965 }
1966
1967 let ret_coercion_span = fcx.ret_coercion_span.get();
1968
1969 if let Some(sp) = ret_coercion_span
1970 // If the closure has an explicit return type annotation, or if
1971 // the closure's return type has been inferred from outside
1972 // requirements (such as an Fn* trait bound), then a type error
1973 // may occur at the first return expression we see in the closure
1974 // (if it conflicts with the declared return type). Skip adding a
1975 // note in this case, since it would be incorrect.
1976 && let Some(fn_sig) = fcx.body_fn_sig()
1977 && fn_sig.output().is_ty_var()
1978 {
1979 err.span_note(sp, format!("return type inferred to be `{expected}` here"));
1980 }
1981
1982 err
1983 }
1984
1985 /// Checks whether the return type is unsized via an obligation, which makes
1986 /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
1987 /// false but technically valid for typeck.
1988 fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
1989 if let Some(sig) = fcx.body_fn_sig() {
1990 !fcx.predicate_may_hold(&Obligation::new(
1991 fcx.tcx,
1992 ObligationCause::dummy(),
1993 fcx.param_env,
1994 ty::TraitRef::new(
1995 fcx.tcx,
1996 fcx.tcx.require_lang_item(hir::LangItem::Sized, DUMMY_SP),
1997 [sig.output()],
1998 ),
1999 ))
2000 } else {
2001 false
2002 }
2003 }
2004
2005 pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
2006 if let Some(final_ty) = self.final_ty {
2007 final_ty
2008 } else {
2009 // If we only had inputs that were of type `!` (or no
2010 // inputs at all), then the final type is `!`.
2011 assert_eq!(self.pushed, 0);
2012 fcx.tcx.types.never
2013 }
2014 }
2015}
2016
2017/// Something that can be converted into an expression to which we can
2018/// apply a coercion.
2019pub(crate) trait AsCoercionSite {
2020 fn as_coercion_site(&self) -> &hir::Expr<'_>;
2021}
2022
2023impl AsCoercionSite for hir::Expr<'_> {
2024 fn as_coercion_site(&self) -> &hir::Expr<'_> {
2025 self
2026 }
2027}
2028
2029impl<'a, T> AsCoercionSite for &'a T
2030where
2031 T: AsCoercionSite,
2032{
2033 fn as_coercion_site(&self) -> &hir::Expr<'_> {
2034 (**self).as_coercion_site()
2035 }
2036}
2037
2038impl AsCoercionSite for ! {
2039 fn as_coercion_site(&self) -> &hir::Expr<'_> {
2040 *self
2041 }
2042}
2043
2044impl AsCoercionSite for hir::Arm<'_> {
2045 fn as_coercion_site(&self) -> &hir::Expr<'_> {
2046 self.body
2047 }
2048}
2049
2050/// Recursively visit goals to decide whether an unsizing is possible.
2051/// `Break`s when it isn't, and an error should be raised.
2052/// `Continue`s when an unsizing ok based on an implementation of the `Unsize` trait / lang item.
2053struct CoerceVisitor<'a, 'tcx> {
2054 fcx: &'a FnCtxt<'a, 'tcx>,
2055 span: Span,
2056}
2057
2058impl<'tcx> ProofTreeVisitor<'tcx> for CoerceVisitor<'_, 'tcx> {
2059 type Result = ControlFlow<()>;
2060
2061 fn span(&self) -> Span {
2062 self.span
2063 }
2064
2065 fn visit_goal(&mut self, goal: &inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
2066 let Some(pred) = goal.goal().predicate.as_trait_clause() else {
2067 return ControlFlow::Continue(());
2068 };
2069
2070 // Make sure this predicate is referring to either an `Unsize` or `CoerceUnsized` trait,
2071 // Otherwise there's nothing to do.
2072 if !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2073 && !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::CoerceUnsized)
2074 {
2075 return ControlFlow::Continue(());
2076 }
2077
2078 match goal.result() {
2079 // If we prove the `Unsize` or `CoerceUnsized` goal, continue recursing.
2080 Ok(Certainty::Yes) => ControlFlow::Continue(()),
2081 Err(NoSolution) => {
2082 // Even if we find no solution, continue recursing if we find a single candidate
2083 // for which we're shallowly certain it holds to get the right error source.
2084 if let [only_candidate] = &goal.candidates()[..]
2085 && only_candidate.shallow_certainty() == Certainty::Yes
2086 {
2087 only_candidate.visit_nested_no_probe(self)
2088 } else {
2089 ControlFlow::Break(())
2090 }
2091 }
2092 Ok(Certainty::Maybe { .. }) => {
2093 // FIXME: structurally normalize?
2094 if self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2095 && let ty::Dynamic(..) = pred.skip_binder().trait_ref.args.type_at(1).kind()
2096 && let ty::Infer(ty::TyVar(vid)) = *pred.self_ty().skip_binder().kind()
2097 && self.fcx.type_var_is_sized(vid)
2098 {
2099 // We get here when trying to unsize a type variable to a `dyn Trait`,
2100 // knowing that that variable is sized. Unsizing definitely has to happen in that case.
2101 // If the variable weren't sized, we may not need an unsizing coercion.
2102 // In general, we don't want to add coercions too eagerly since it makes error messages much worse.
2103 ControlFlow::Continue(())
2104 } else if let Some(cand) = goal.unique_applicable_candidate()
2105 && cand.shallow_certainty() == Certainty::Yes
2106 {
2107 cand.visit_nested_no_probe(self)
2108 } else {
2109 ControlFlow::Break(())
2110 }
2111 }
2112 }
2113 }
2114}