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