• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
38 use crate::FnCtxt;
39 use rustc_errors::{struct_span_err, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan};
40 use rustc_hir as hir;
41 use rustc_hir::def_id::DefId;
42 use rustc_hir::intravisit::{self, Visitor};
43 use rustc_hir::Expr;
44 use rustc_hir_analysis::astconv::AstConv;
45 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
46 use rustc_infer::infer::{Coercion, DefineOpaqueTypes, InferOk, InferResult};
47 use rustc_infer::traits::{Obligation, PredicateObligation};
48 use rustc_middle::lint::in_external_macro;
49 use rustc_middle::ty::adjustment::{
50     Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCoercion,
51 };
52 use rustc_middle::ty::error::TypeError;
53 use rustc_middle::ty::relate::RelateResult;
54 use rustc_middle::ty::subst::SubstsRef;
55 use rustc_middle::ty::visit::TypeVisitableExt;
56 use rustc_middle::ty::{self, Ty, TypeAndMut};
57 use rustc_session::parse::feature_err;
58 use rustc_span::symbol::sym;
59 use rustc_span::{self, DesugaringKind};
60 use rustc_target::spec::abi::Abi;
61 use rustc_trait_selection::infer::InferCtxtExt as _;
62 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
63 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
64 use rustc_trait_selection::traits::{
65     self, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
66 };
67 
68 use smallvec::{smallvec, SmallVec};
69 use std::ops::Deref;
70 
71 struct 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 }
83 
84 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
85     type Target = FnCtxt<'a, 'tcx>;
deref(&self) -> &Self::Target86     fn deref(&self) -> &Self::Target {
87         &self.fcx
88     }
89 }
90 
91 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
92 
93 struct CollectRetsVisitor<'tcx> {
94     ret_exprs: Vec<&'tcx hir::Expr<'tcx>>,
95 }
96 
97 impl<'tcx> Visitor<'tcx> for CollectRetsVisitor<'tcx> {
visit_expr(&mut self, expr: &'tcx Expr<'tcx>)98     fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
99         if let hir::ExprKind::Ret(_) = expr.kind {
100             self.ret_exprs.push(expr);
101         }
102         intravisit::walk_expr(self, expr);
103     }
104 }
105 
106 /// Coercing a mutable reference to an immutable works, while
107 /// coercing `&T` to `&mut T` should be forbidden.
coerce_mutbls<'tcx>( from_mutbl: hir::Mutability, to_mutbl: hir::Mutability, ) -> RelateResult<'tcx, ()>108 fn coerce_mutbls<'tcx>(
109     from_mutbl: hir::Mutability,
110     to_mutbl: hir::Mutability,
111 ) -> RelateResult<'tcx, ()> {
112     if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
113 }
114 
115 /// Do not require any adjustments, i.e. coerce `x -> x`.
identity(_: Ty<'_>) -> Vec<Adjustment<'_>>116 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> {
117     vec![]
118 }
119 
simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'_>>120 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'_>> {
121     move |target| vec![Adjustment { kind, target }]
122 }
123 
124 /// This always returns `Ok(...)`.
success<'tcx>( adj: Vec<Adjustment<'tcx>>, target: Ty<'tcx>, obligations: traits::PredicateObligations<'tcx>, ) -> CoerceResult<'tcx>125 fn success<'tcx>(
126     adj: Vec<Adjustment<'tcx>>,
127     target: Ty<'tcx>,
128     obligations: traits::PredicateObligations<'tcx>,
129 ) -> CoerceResult<'tcx> {
130     Ok(InferOk { value: (adj, target), obligations })
131 }
132 
133 impl<'f, 'tcx> Coerce<'f, 'tcx> {
new( fcx: &'f FnCtxt<'f, 'tcx>, cause: ObligationCause<'tcx>, allow_two_phase: AllowTwoPhase, ) -> Self134     fn new(
135         fcx: &'f FnCtxt<'f, 'tcx>,
136         cause: ObligationCause<'tcx>,
137         allow_two_phase: AllowTwoPhase,
138     ) -> Self {
139         Coerce { fcx, cause, allow_two_phase, use_lub: false }
140     }
141 
unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>>142     fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
143         debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
144         self.commit_if_ok(|_| {
145             let at = self.at(&self.cause, self.fcx.param_env);
146 
147             let res = if self.use_lub {
148                 at.lub(DefineOpaqueTypes::Yes, b, a)
149             } else {
150                 at.sup(DefineOpaqueTypes::Yes, b, a)
151                     .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
152             };
153 
154             // In the new solver, lazy norm may allow us to shallowly equate
155             // more types, but we emit possibly impossible-to-satisfy obligations.
156             // Filter these cases out to make sure our coercion is more accurate.
157             if self.next_trait_solver() {
158                 if let Ok(res) = &res {
159                     for obligation in &res.obligations {
160                         if !self.predicate_may_hold(&obligation) {
161                             return Err(TypeError::Mismatch);
162                         }
163                     }
164                 }
165             }
166 
167             res
168         })
169     }
170 
171     /// Unify two types (using sub or lub) and produce a specific coercion.
unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx> where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,172     fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx>
173     where
174         F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
175     {
176         self.unify(a, b)
177             .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations))
178     }
179 
180     #[instrument(skip(self))]
coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx>181     fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
182         // First, remove any resolved type variables (at the top level, at least):
183         let a = self.shallow_resolve(a);
184         let b = self.shallow_resolve(b);
185         debug!("Coerce.tys({:?} => {:?})", a, b);
186 
187         // Just ignore error types.
188         if let Err(guar) = (a, b).error_reported() {
189             // Best-effort try to unify these types -- we're already on the error path,
190             // so this will have the side-effect of making sure we have no ambiguities
191             // due to `[type error]` and `_` not coercing together.
192             let _ = self.commit_if_ok(|_| {
193                 self.at(&self.cause, self.param_env).eq(DefineOpaqueTypes::Yes, a, b)
194             });
195             return success(vec![], Ty::new_error(self.fcx.tcx, guar), vec![]);
196         }
197 
198         // Coercing from `!` to any type is allowed:
199         if a.is_never() {
200             return success(simple(Adjust::NeverToAny)(b), b, vec![]);
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, identity);
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 auto-borrowing.
227         match *b.kind() {
228             ty::RawPtr(mt_b) => {
229                 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
230             }
231             ty::Ref(r_b, _, mutbl_b) => {
232                 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
233             }
234             ty::Dynamic(predicates, region, ty::DynStar) if self.tcx.features().dyn_star => {
235                 return self.coerce_dyn_star(a, b, predicates, region);
236             }
237             _ => {}
238         }
239 
240         match *a.kind() {
241             ty::FnDef(..) => {
242                 // Function items are coercible to any closure
243                 // type; function pointers are not (that would
244                 // require double indirection).
245                 // Additionally, we permit coercion of function
246                 // items to drop the unsafe qualifier.
247                 self.coerce_from_fn_item(a, b)
248             }
249             ty::FnPtr(a_f) => {
250                 // We permit coercion of fn pointers to drop the
251                 // unsafe qualifier.
252                 self.coerce_from_fn_pointer(a, a_f, b)
253             }
254             ty::Closure(closure_def_id_a, substs_a) => {
255                 // Non-capturing closures are coercible to
256                 // function pointers or unsafe function pointers.
257                 // It cannot convert closures that require unsafe.
258                 self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b)
259             }
260             _ => {
261                 // Otherwise, just use unification rules.
262                 self.unify_and(a, b, identity)
263             }
264         }
265     }
266 
267     /// Coercing *from* an inference variable. In this case, we have no information
268     /// about the source type, so we can't really do a true coercion and we always
269     /// fall back to subtyping (`unify_and`).
coerce_from_inference_variable( &self, a: Ty<'tcx>, b: Ty<'tcx>, make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>, ) -> CoerceResult<'tcx>270     fn coerce_from_inference_variable(
271         &self,
272         a: Ty<'tcx>,
273         b: Ty<'tcx>,
274         make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
275     ) -> CoerceResult<'tcx> {
276         debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
277         assert!(a.is_ty_var() && self.shallow_resolve(a) == a);
278         assert!(self.shallow_resolve(b) == b);
279 
280         if b.is_ty_var() {
281             // Two unresolved type variables: create a `Coerce` predicate.
282             let target_ty = if self.use_lub {
283                 self.next_ty_var(TypeVariableOrigin {
284                     kind: TypeVariableOriginKind::LatticeVariable,
285                     span: self.cause.span,
286                 })
287             } else {
288                 b
289             };
290 
291             let mut obligations = Vec::with_capacity(2);
292             for &source_ty in &[a, b] {
293                 if source_ty != target_ty {
294                     obligations.push(Obligation::new(
295                         self.tcx(),
296                         self.cause.clone(),
297                         self.param_env,
298                         ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate {
299                             a: source_ty,
300                             b: target_ty,
301                         })),
302                     ));
303                 }
304             }
305 
306             debug!(
307                 "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
308                 target_ty, obligations
309             );
310             let adjustments = make_adjustments(target_ty);
311             InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations })
312         } else {
313             // One unresolved type variable: just apply subtyping, we may be able
314             // to do something useful.
315             self.unify_and(a, b, make_adjustments)
316         }
317     }
318 
319     /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
320     /// To match `A` with `B`, autoderef will be performed,
321     /// calling `deref`/`deref_mut` where necessary.
coerce_borrowed_pointer( &self, a: Ty<'tcx>, b: Ty<'tcx>, r_b: ty::Region<'tcx>, mutbl_b: hir::Mutability, ) -> CoerceResult<'tcx>322     fn coerce_borrowed_pointer(
323         &self,
324         a: Ty<'tcx>,
325         b: Ty<'tcx>,
326         r_b: ty::Region<'tcx>,
327         mutbl_b: hir::Mutability,
328     ) -> CoerceResult<'tcx> {
329         debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
330 
331         // If we have a parameter of type `&M T_a` and the value
332         // provided is `expr`, we will be adding an implicit borrow,
333         // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
334         // to type check, we will construct the type that `&M*expr` would
335         // yield.
336 
337         let (r_a, mt_a) = match *a.kind() {
338             ty::Ref(r_a, ty, mutbl) => {
339                 let mt_a = ty::TypeAndMut { ty, mutbl };
340                 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
341                 (r_a, mt_a)
342             }
343             _ => return self.unify_and(a, b, identity),
344         };
345 
346         let span = self.cause.span;
347 
348         let mut first_error = None;
349         let mut r_borrow_var = None;
350         let mut autoderef = self.autoderef(span, a);
351         let mut found = None;
352 
353         for (referent_ty, autoderefs) in autoderef.by_ref() {
354             if autoderefs == 0 {
355                 // Don't let this pass, otherwise it would cause
356                 // &T to autoref to &&T.
357                 continue;
358             }
359 
360             // At this point, we have deref'd `a` to `referent_ty`. So
361             // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
362             // In the autoderef loop for `&'a mut Vec<T>`, we would get
363             // three callbacks:
364             //
365             // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
366             // - `Vec<T>` -- 1 deref
367             // - `[T]` -- 2 deref
368             //
369             // At each point after the first callback, we want to
370             // check to see whether this would match out target type
371             // (`&'b mut [T]`) if we autoref'd it. We can't just
372             // compare the referent types, though, because we still
373             // have to consider the mutability. E.g., in the case
374             // we've been considering, we have an `&mut` reference, so
375             // the `T` in `[T]` needs to be unified with equality.
376             //
377             // Therefore, we construct reference types reflecting what
378             // the types will be after we do the final auto-ref and
379             // compare those. Note that this means we use the target
380             // mutability [1], since it may be that we are coercing
381             // from `&mut T` to `&U`.
382             //
383             // One fine point concerns the region that we use. We
384             // choose the region such that the region of the final
385             // type that results from `unify` will be the region we
386             // want for the autoref:
387             //
388             // - if in sub mode, that means we want to use `'b` (the
389             //   region from the target reference) for both
390             //   pointers [2]. This is because sub mode (somewhat
391             //   arbitrarily) returns the subtype region. In the case
392             //   where we are coercing to a target type, we know we
393             //   want to use that target type region (`'b`) because --
394             //   for the program to type-check -- it must be the
395             //   smaller of the two.
396             //   - One fine point. It may be surprising that we can
397             //     use `'b` without relating `'a` and `'b`. The reason
398             //     that this is ok is that what we produce is
399             //     effectively a `&'b *x` expression (if you could
400             //     annotate the region of a borrow), and regionck has
401             //     code that adds edges from the region of a borrow
402             //     (`'b`, here) into the regions in the borrowed
403             //     expression (`*x`, here). (Search for "link".)
404             // - if in lub mode, things can get fairly complicated. The
405             //   easiest thing is just to make a fresh
406             //   region variable [4], which effectively means we defer
407             //   the decision to region inference (and regionck, which will add
408             //   some more edges to this variable). However, this can wind up
409             //   creating a crippling number of variables in some cases --
410             //   e.g., #32278 -- so we optimize one particular case [3].
411             //   Let me try to explain with some examples:
412             //   - The "running example" above represents the simple case,
413             //     where we have one `&` reference at the outer level and
414             //     ownership all the rest of the way down. In this case,
415             //     we want `LUB('a, 'b)` as the resulting region.
416             //   - However, if there are nested borrows, that region is
417             //     too strong. Consider a coercion from `&'a &'x Rc<T>` to
418             //     `&'b T`. In this case, `'a` is actually irrelevant.
419             //     The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
420             //     we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
421             //     (The errors actually show up in borrowck, typically, because
422             //     this extra edge causes the region `'a` to be inferred to something
423             //     too big, which then results in borrowck errors.)
424             //   - We could track the innermost shared reference, but there is already
425             //     code in regionck that has the job of creating links between
426             //     the region of a borrow and the regions in the thing being
427             //     borrowed (here, `'a` and `'x`), and it knows how to handle
428             //     all the various cases. So instead we just make a region variable
429             //     and let regionck figure it out.
430             let r = if !self.use_lub {
431                 r_b // [2] above
432             } else if autoderefs == 1 {
433                 r_a // [3] above
434             } else {
435                 if r_borrow_var.is_none() {
436                     // create var lazily, at most once
437                     let coercion = Coercion(span);
438                     let r = self.next_region_var(coercion);
439                     r_borrow_var = Some(r); // [4] above
440                 }
441                 r_borrow_var.unwrap()
442             };
443             let derefd_ty_a = Ty::new_ref(
444                 self.tcx,
445                 r,
446                 TypeAndMut {
447                     ty: referent_ty,
448                     mutbl: mutbl_b, // [1] above
449                 },
450             );
451             match self.unify(derefd_ty_a, b) {
452                 Ok(ok) => {
453                     found = Some(ok);
454                     break;
455                 }
456                 Err(err) => {
457                     if first_error.is_none() {
458                         first_error = Some(err);
459                     }
460                 }
461             }
462         }
463 
464         // Extract type or return an error. We return the first error
465         // we got, which should be from relating the "base" type
466         // (e.g., in example above, the failure from relating `Vec<T>`
467         // to the target type), since that should be the least
468         // confusing.
469         let Some(InferOk { value: ty, mut obligations }) = found else {
470             let err = first_error.expect("coerce_borrowed_pointer had no error");
471             debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
472             return Err(err);
473         };
474 
475         if ty == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
476             // As a special case, if we would produce `&'a *x`, that's
477             // a total no-op. We end up with the type `&'a T` just as
478             // we started with. In that case, just skip it
479             // altogether. This is just an optimization.
480             //
481             // Note that for `&mut`, we DO want to reborrow --
482             // otherwise, this would be a move, which might be an
483             // error. For example `foo(self.x)` where `self` and
484             // `self.x` both have `&mut `type would be a move of
485             // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
486             // which is a borrow.
487             assert!(mutbl_b.is_not()); // can only coerce &T -> &U
488             return success(vec![], ty, obligations);
489         }
490 
491         let InferOk { value: mut adjustments, obligations: o } =
492             self.adjust_steps_as_infer_ok(&autoderef);
493         obligations.extend(o);
494         obligations.extend(autoderef.into_obligations());
495 
496         // Now apply the autoref. We have to extract the region out of
497         // the final ref type we got.
498         let ty::Ref(r_borrow, _, _) = ty.kind() else {
499             span_bug!(span, "expected a ref type, got {:?}", ty);
500         };
501         let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
502         adjustments.push(Adjustment {
503             kind: Adjust::Borrow(AutoBorrow::Ref(*r_borrow, mutbl)),
504             target: ty,
505         });
506 
507         debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
508 
509         success(adjustments, ty, obligations)
510     }
511 
512     // &[T; n] or &mut [T; n] -> &[T]
513     // or &mut [T; n] -> &mut [T]
514     // or &Concrete -> &Trait, etc.
515     #[instrument(skip(self), level = "debug")]
coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx>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(r_borrow, mutbl)),
562                         target: Ty::new_ref(
563                             self.tcx,
564                             r_borrow,
565                             ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a },
566                         ),
567                     },
568                 ))
569             }
570             (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
571                 coerce_mutbls(mt_a, mt_b)?;
572 
573                 Some((
574                     Adjustment { kind: Adjust::Deref(None), target: ty_a },
575                     Adjustment {
576                         kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
577                         target: Ty::new_ptr(self.tcx, ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
578                     },
579                 ))
580             }
581             _ => None,
582         };
583         let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
584 
585         // Setup either a subtyping or a LUB relationship between
586         // the `CoerceUnsized` target type and the expected type.
587         // We only have the latter, so we use an inference variable
588         // for the former and let type inference do the rest.
589         let origin = TypeVariableOrigin {
590             kind: TypeVariableOriginKind::MiscVariable,
591             span: self.cause.span,
592         };
593         let coerce_target = self.next_ty_var(origin);
594         let mut coercion = self.unify_and(coerce_target, target, |target| {
595             let unsize = Adjustment { kind: Adjust::Pointer(PointerCoercion::Unsize), target };
596             match reborrow {
597                 None => vec![unsize],
598                 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
599             }
600         })?;
601 
602         let mut selcx = traits::SelectionContext::new(self);
603 
604         // Create an obligation for `Source: CoerceUnsized<Target>`.
605         let cause = ObligationCause::new(
606             self.cause.span,
607             self.body_id,
608             ObligationCauseCode::Coercion { source, target },
609         );
610 
611         // Use a FIFO queue for this custom fulfillment procedure.
612         //
613         // A Vec (or SmallVec) is not a natural choice for a queue. However,
614         // this code path is hot, and this queue usually has a max length of 1
615         // and almost never more than 3. By using a SmallVec we avoid an
616         // allocation, at the (very small) cost of (occasionally) having to
617         // shift subsequent elements down when removing the front element.
618         let mut queue: SmallVec<[PredicateObligation<'tcx>; 4]> = smallvec![Obligation::new(
619             self.tcx,
620             cause,
621             self.fcx.param_env,
622             ty::TraitRef::new(self.tcx, coerce_unsized_did, [coerce_source, coerce_target])
623         )];
624 
625         let mut has_unsized_tuple_coercion = false;
626         let mut has_trait_upcasting_coercion = None;
627 
628         // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
629         // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
630         // inference might unify those two inner type variables later.
631         let traits = [coerce_unsized_did, unsize_did];
632         while !queue.is_empty() {
633             let obligation = queue.remove(0);
634             debug!("coerce_unsized resolve step: {:?}", obligation);
635             let trait_pred = match obligation.predicate.kind().no_bound_vars() {
636                 Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)))
637                     if traits.contains(&trait_pred.def_id()) =>
638                 {
639                     if unsize_did == trait_pred.def_id() {
640                         let self_ty = trait_pred.self_ty();
641                         let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
642                         if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) =
643                             (self_ty.kind(), unsize_ty.kind())
644                             && data_a.principal_def_id() != data_b.principal_def_id()
645                         {
646                             debug!("coerce_unsized: found trait upcasting coercion");
647                             has_trait_upcasting_coercion = Some((self_ty, unsize_ty));
648                         }
649                         if let ty::Tuple(..) = unsize_ty.kind() {
650                             debug!("coerce_unsized: found unsized tuple coercion");
651                             has_unsized_tuple_coercion = true;
652                         }
653                     }
654                     trait_pred
655                 }
656                 _ => {
657                     coercion.obligations.push(obligation);
658                     continue;
659                 }
660             };
661             match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
662                 // Uncertain or unimplemented.
663                 Ok(None) => {
664                     if trait_pred.def_id() == unsize_did {
665                         let trait_pred = self.resolve_vars_if_possible(trait_pred);
666                         let self_ty = trait_pred.self_ty();
667                         let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
668                         debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
669                         match (self_ty.kind(), unsize_ty.kind()) {
670                             (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
671                                 if self.type_var_is_sized(v) =>
672                             {
673                                 debug!("coerce_unsized: have sized infer {:?}", v);
674                                 coercion.obligations.push(obligation);
675                                 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
676                                 // for unsizing.
677                             }
678                             _ => {
679                                 // Some other case for `$0: Unsize<Something>`. Note that we
680                                 // hit this case even if `Something` is a sized type, so just
681                                 // don't do the coercion.
682                                 debug!("coerce_unsized: ambiguous unsize");
683                                 return Err(TypeError::Mismatch);
684                             }
685                         }
686                     } else {
687                         debug!("coerce_unsized: early return - ambiguous");
688                         return Err(TypeError::Mismatch);
689                     }
690                 }
691                 Err(traits::Unimplemented) => {
692                     debug!("coerce_unsized: early return - can't prove obligation");
693                     return Err(TypeError::Mismatch);
694                 }
695 
696                 // Object safety violations or miscellaneous.
697                 Err(err) => {
698                     self.err_ctxt().report_selection_error(obligation.clone(), &obligation, &err);
699                     // Treat this like an obligation and follow through
700                     // with the unsizing - the lack of a coercion should
701                     // be silent, as it causes a type mismatch later.
702                 }
703 
704                 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
705             }
706         }
707 
708         if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
709             feature_err(
710                 &self.tcx.sess.parse_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         if let Some((sub, sup)) = has_trait_upcasting_coercion
719             && !self.tcx().features().trait_upcasting
720         {
721             // Renders better when we erase regions, since they're not really the point here.
722             let (sub, sup) = self.tcx.erase_regions((sub, sup));
723             let mut err = feature_err(
724                 &self.tcx.sess.parse_sess,
725                 sym::trait_upcasting,
726                 self.cause.span,
727                 format!("cannot cast `{sub}` to `{sup}`, trait upcasting coercion is experimental"),
728             );
729             err.note(format!("required when coercing `{source}` into `{target}`"));
730             err.emit();
731         }
732 
733         Ok(coercion)
734     }
735 
coerce_dyn_star( &self, a: Ty<'tcx>, b: Ty<'tcx>, predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>, b_region: ty::Region<'tcx>, ) -> CoerceResult<'tcx>736     fn coerce_dyn_star(
737         &self,
738         a: Ty<'tcx>,
739         b: Ty<'tcx>,
740         predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
741         b_region: ty::Region<'tcx>,
742     ) -> CoerceResult<'tcx> {
743         if !self.tcx.features().dyn_star {
744             return Err(TypeError::Mismatch);
745         }
746 
747         if let ty::Dynamic(a_data, _, _) = a.kind()
748             && let ty::Dynamic(b_data, _, _) = b.kind()
749             && a_data.principal_def_id() == b_data.principal_def_id()
750         {
751             return self.unify_and(a, b, |_| vec![]);
752         }
753 
754         // Check the obligations of the cast -- for example, when casting
755         // `usize` to `dyn* Clone + 'static`:
756         let mut obligations: Vec<_> = predicates
757             .iter()
758             .map(|predicate| {
759                 // For each existential predicate (e.g., `?Self: Clone`) substitute
760                 // the type of the expression (e.g., `usize` in our example above)
761                 // and then require that the resulting predicate (e.g., `usize: Clone`)
762                 // holds (it does).
763                 let predicate = predicate.with_self_ty(self.tcx, a);
764                 Obligation::new(self.tcx, self.cause.clone(), self.param_env, predicate)
765             })
766             .chain([
767                 // Enforce the region bound (e.g., `usize: 'static`, in our example).
768                 Obligation::new(
769                     self.tcx,
770                     self.cause.clone(),
771                     self.param_env,
772                     ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
773                         ty::OutlivesPredicate(a, b_region),
774                     ))),
775                 ),
776             ])
777             .collect();
778 
779         // Enforce that the type is `usize`/pointer-sized.
780         obligations.push(Obligation::new(
781             self.tcx,
782             self.cause.clone(),
783             self.param_env,
784             ty::TraitRef::from_lang_item(
785                 self.tcx,
786                 hir::LangItem::PointerLike,
787                 self.cause.span,
788                 [a],
789             ),
790         ));
791 
792         Ok(InferOk {
793             value: (vec![Adjustment { kind: Adjust::DynStar, target: b }], b),
794             obligations,
795         })
796     }
797 
coerce_from_safe_fn<F, G>( &self, a: Ty<'tcx>, fn_ty_a: ty::PolyFnSig<'tcx>, b: Ty<'tcx>, to_unsafe: F, normal: G, ) -> CoerceResult<'tcx> where F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>, G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,798     fn coerce_from_safe_fn<F, G>(
799         &self,
800         a: Ty<'tcx>,
801         fn_ty_a: ty::PolyFnSig<'tcx>,
802         b: Ty<'tcx>,
803         to_unsafe: F,
804         normal: G,
805     ) -> CoerceResult<'tcx>
806     where
807         F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
808         G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
809     {
810         self.commit_if_ok(|snapshot| {
811             let outer_universe = self.infcx.universe();
812 
813             let result = if let ty::FnPtr(fn_ty_b) = b.kind()
814                 && let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
815                     (fn_ty_a.unsafety(), fn_ty_b.unsafety())
816             {
817                 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
818                 self.unify_and(unsafe_a, b, to_unsafe)
819             } else {
820                 self.unify_and(a, b, normal)
821             };
822 
823             // FIXME(#73154): This is a hack. Currently LUB can generate
824             // unsolvable constraints. Additionally, it returns `a`
825             // unconditionally, even when the "LUB" is `b`. In the future, we
826             // want the coerced type to be the actual supertype of these two,
827             // but for now, we want to just error to ensure we don't lock
828             // ourselves into a specific behavior with NLL.
829             self.leak_check(outer_universe, Some(snapshot))?;
830 
831             result
832         })
833     }
834 
coerce_from_fn_pointer( &self, a: Ty<'tcx>, fn_ty_a: ty::PolyFnSig<'tcx>, b: Ty<'tcx>, ) -> CoerceResult<'tcx>835     fn coerce_from_fn_pointer(
836         &self,
837         a: Ty<'tcx>,
838         fn_ty_a: ty::PolyFnSig<'tcx>,
839         b: Ty<'tcx>,
840     ) -> CoerceResult<'tcx> {
841         //! Attempts to coerce from the type of a Rust function item
842         //! into a closure or a `proc`.
843         //!
844 
845         let b = self.shallow_resolve(b);
846         debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
847 
848         self.coerce_from_safe_fn(
849             a,
850             fn_ty_a,
851             b,
852             simple(Adjust::Pointer(PointerCoercion::UnsafeFnPointer)),
853             identity,
854         )
855     }
856 
coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx>857     fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
858         //! Attempts to coerce from the type of a Rust function item
859         //! into a closure or a `proc`.
860 
861         let b = self.shallow_resolve(b);
862         let InferOk { value: b, mut obligations } =
863             self.at(&self.cause, self.param_env).normalize(b);
864         debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
865 
866         match b.kind() {
867             ty::FnPtr(b_sig) => {
868                 let a_sig = a.fn_sig(self.tcx);
869                 if let ty::FnDef(def_id, _) = *a.kind() {
870                     // Intrinsics are not coercible to function pointers
871                     if self.tcx.is_intrinsic(def_id) {
872                         return Err(TypeError::IntrinsicCast);
873                     }
874 
875                     // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
876 
877                     if b_sig.unsafety() == hir::Unsafety::Normal
878                         && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
879                     {
880                         return Err(TypeError::TargetFeatureCast(def_id));
881                     }
882                 }
883 
884                 let InferOk { value: a_sig, obligations: o1 } =
885                     self.at(&self.cause, self.param_env).normalize(a_sig);
886                 obligations.extend(o1);
887 
888                 let a_fn_pointer = Ty::new_fn_ptr(self.tcx, a_sig);
889                 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
890                     a_fn_pointer,
891                     a_sig,
892                     b,
893                     |unsafe_ty| {
894                         vec![
895                             Adjustment {
896                                 kind: Adjust::Pointer(PointerCoercion::ReifyFnPointer),
897                                 target: a_fn_pointer,
898                             },
899                             Adjustment {
900                                 kind: Adjust::Pointer(PointerCoercion::UnsafeFnPointer),
901                                 target: unsafe_ty,
902                             },
903                         ]
904                     },
905                     simple(Adjust::Pointer(PointerCoercion::ReifyFnPointer)),
906                 )?;
907 
908                 obligations.extend(o2);
909                 Ok(InferOk { value, obligations })
910             }
911             _ => self.unify_and(a, b, identity),
912         }
913     }
914 
coerce_closure_to_fn( &self, a: Ty<'tcx>, closure_def_id_a: DefId, substs_a: SubstsRef<'tcx>, b: Ty<'tcx>, ) -> CoerceResult<'tcx>915     fn coerce_closure_to_fn(
916         &self,
917         a: Ty<'tcx>,
918         closure_def_id_a: DefId,
919         substs_a: SubstsRef<'tcx>,
920         b: Ty<'tcx>,
921     ) -> CoerceResult<'tcx> {
922         //! Attempts to coerce from the type of a non-capturing closure
923         //! into a function pointer.
924         //!
925 
926         let b = self.shallow_resolve(b);
927 
928         match b.kind() {
929             // At this point we haven't done capture analysis, which means
930             // that the ClosureSubsts just contains an inference variable instead
931             // of tuple of captured types.
932             //
933             // All we care here is if any variable is being captured and not the exact paths,
934             // so we check `upvars_mentioned` for root variables being captured.
935             ty::FnPtr(fn_ty)
936                 if self
937                     .tcx
938                     .upvars_mentioned(closure_def_id_a.expect_local())
939                     .map_or(true, |u| u.is_empty()) =>
940             {
941                 // We coerce the closure, which has fn type
942                 //     `extern "rust-call" fn((arg0,arg1,...)) -> _`
943                 // to
944                 //     `fn(arg0,arg1,...) -> _`
945                 // or
946                 //     `unsafe fn(arg0,arg1,...) -> _`
947                 let closure_sig = substs_a.as_closure().sig();
948                 let unsafety = fn_ty.unsafety();
949                 let pointer_ty =
950                     Ty::new_fn_ptr(self.tcx, self.tcx.signature_unclosure(closure_sig, unsafety));
951                 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
952                 self.unify_and(
953                     pointer_ty,
954                     b,
955                     simple(Adjust::Pointer(PointerCoercion::ClosureFnPointer(unsafety))),
956                 )
957             }
958             _ => self.unify_and(a, b, identity),
959         }
960     }
961 
coerce_unsafe_ptr( &self, a: Ty<'tcx>, b: Ty<'tcx>, mutbl_b: hir::Mutability, ) -> CoerceResult<'tcx>962     fn coerce_unsafe_ptr(
963         &self,
964         a: Ty<'tcx>,
965         b: Ty<'tcx>,
966         mutbl_b: hir::Mutability,
967     ) -> CoerceResult<'tcx> {
968         debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
969 
970         let (is_ref, mt_a) = match *a.kind() {
971             ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
972             ty::RawPtr(mt) => (false, mt),
973             _ => return self.unify_and(a, b, identity),
974         };
975         coerce_mutbls(mt_a.mutbl, mutbl_b)?;
976 
977         // Check that the types which they point at are compatible.
978         let a_unsafe = Ty::new_ptr(self.tcx, ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
979         // Although references and unsafe ptrs have the same
980         // representation, we still register an Adjust::DerefRef so that
981         // regionck knows that the region for `a` must be valid here.
982         if is_ref {
983             self.unify_and(a_unsafe, b, |target| {
984                 vec![
985                     Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
986                     Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
987                 ]
988             })
989         } else if mt_a.mutbl != mutbl_b {
990             self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCoercion::MutToConstPointer)))
991         } else {
992             self.unify_and(a_unsafe, b, identity)
993         }
994     }
995 }
996 
997 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
998     /// Attempt to coerce an expression to a type, and return the
999     /// adjusted type of the expression, if successful.
1000     /// Adjustments are only recorded if the coercion succeeded.
1001     /// The expressions *must not* have any preexisting adjustments.
try_coerce( &self, expr: &hir::Expr<'_>, expr_ty: Ty<'tcx>, target: Ty<'tcx>, allow_two_phase: AllowTwoPhase, cause: Option<ObligationCause<'tcx>>, ) -> RelateResult<'tcx, Ty<'tcx>>1002     pub fn try_coerce(
1003         &self,
1004         expr: &hir::Expr<'_>,
1005         expr_ty: Ty<'tcx>,
1006         target: Ty<'tcx>,
1007         allow_two_phase: AllowTwoPhase,
1008         cause: Option<ObligationCause<'tcx>>,
1009     ) -> RelateResult<'tcx, Ty<'tcx>> {
1010         let source = self.try_structurally_resolve_type(expr.span, expr_ty);
1011         debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
1012 
1013         let cause =
1014             cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
1015         let coerce = Coerce::new(self, cause, allow_two_phase);
1016         let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
1017 
1018         let (adjustments, _) = self.register_infer_ok_obligations(ok);
1019         self.apply_adjustments(expr, adjustments);
1020         Ok(if let Err(guar) = expr_ty.error_reported() {
1021             Ty::new_error(self.tcx, guar)
1022         } else {
1023             target
1024         })
1025     }
1026 
1027     /// Same as `try_coerce()`, but without side-effects.
1028     ///
1029     /// Returns false if the coercion creates any obligations that result in
1030     /// errors.
can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool1031     pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
1032         let source = self.resolve_vars_with_obligations(expr_ty);
1033         debug!("coercion::can_with_predicates({:?} -> {:?})", source, target);
1034 
1035         let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
1036         // We don't ever need two-phase here since we throw out the result of the coercion
1037         let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
1038         self.probe(|_| {
1039             let Ok(ok) = coerce.coerce(source, target) else {
1040                 return false;
1041             };
1042             let ocx = ObligationCtxt::new(self);
1043             ocx.register_obligations(ok.obligations);
1044             ocx.select_where_possible().is_empty()
1045         })
1046     }
1047 
1048     /// Given a type and a target type, this function will calculate and return
1049     /// how many dereference steps needed to achieve `expr_ty <: target`. If
1050     /// it's not possible, return `None`.
deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize>1051     pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
1052         let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
1053         // We don't ever need two-phase here since we throw out the result of the coercion
1054         let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
1055         coerce
1056             .autoderef(rustc_span::DUMMY_SP, expr_ty)
1057             .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
1058     }
1059 
1060     /// Given a type, this function will calculate and return the type given
1061     /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1062     ///
1063     /// This function is for diagnostics only, since it does not register
1064     /// trait or region sub-obligations. (presumably we could, but it's not
1065     /// particularly important for diagnostics...)
deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>>1066     pub fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1067         self.autoderef(rustc_span::DUMMY_SP, expr_ty).nth(1).and_then(|(deref_ty, _)| {
1068             self.infcx
1069                 .type_implements_trait(
1070                     self.tcx.lang_items().deref_mut_trait()?,
1071                     [expr_ty],
1072                     self.param_env,
1073                 )
1074                 .may_apply()
1075                 .then_some(deref_ty)
1076         })
1077     }
1078 
1079     /// Given some expressions, their known unified type and another expression,
1080     /// tries to unify the types, potentially inserting coercions on any of the
1081     /// provided expressions and returns their LUB (aka "common supertype").
1082     ///
1083     /// This is really an internal helper. From outside the coercion
1084     /// module, you should instantiate a `CoerceMany` instance.
try_find_coercion_lub<E>( &self, cause: &ObligationCause<'tcx>, exprs: &[E], prev_ty: Ty<'tcx>, new: &hir::Expr<'_>, new_ty: Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> where E: AsCoercionSite,1085     fn try_find_coercion_lub<E>(
1086         &self,
1087         cause: &ObligationCause<'tcx>,
1088         exprs: &[E],
1089         prev_ty: Ty<'tcx>,
1090         new: &hir::Expr<'_>,
1091         new_ty: Ty<'tcx>,
1092     ) -> RelateResult<'tcx, Ty<'tcx>>
1093     where
1094         E: AsCoercionSite,
1095     {
1096         let prev_ty = self.resolve_vars_with_obligations(prev_ty);
1097         let new_ty = self.resolve_vars_with_obligations(new_ty);
1098         debug!(
1099             "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1100             prev_ty,
1101             new_ty,
1102             exprs.len()
1103         );
1104 
1105         // The following check fixes #88097, where the compiler erroneously
1106         // attempted to coerce a closure type to itself via a function pointer.
1107         if prev_ty == new_ty {
1108             return Ok(prev_ty);
1109         }
1110 
1111         // Special-case that coercion alone cannot handle:
1112         // Function items or non-capturing closures of differing IDs or InternalSubsts.
1113         let (a_sig, b_sig) = {
1114             let is_capturing_closure = |ty: Ty<'tcx>| {
1115                 if let &ty::Closure(closure_def_id, _substs) = ty.kind() {
1116                     self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
1117                 } else {
1118                     false
1119                 }
1120             };
1121             if is_capturing_closure(prev_ty) || is_capturing_closure(new_ty) {
1122                 (None, None)
1123             } else {
1124                 match (prev_ty.kind(), new_ty.kind()) {
1125                     (ty::FnDef(..), ty::FnDef(..)) => {
1126                         // Don't reify if the function types have a LUB, i.e., they
1127                         // are the same function and their parameters have a LUB.
1128                         match self.commit_if_ok(|_| {
1129                             self.at(cause, self.param_env).lub(
1130                                 DefineOpaqueTypes::No,
1131                                 prev_ty,
1132                                 new_ty,
1133                             )
1134                         }) {
1135                             // We have a LUB of prev_ty and new_ty, just return it.
1136                             Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1137                             Err(_) => {
1138                                 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
1139                             }
1140                         }
1141                     }
1142                     (ty::Closure(_, substs), ty::FnDef(..)) => {
1143                         let b_sig = new_ty.fn_sig(self.tcx);
1144                         let a_sig = self
1145                             .tcx
1146                             .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
1147                         (Some(a_sig), Some(b_sig))
1148                     }
1149                     (ty::FnDef(..), ty::Closure(_, substs)) => {
1150                         let a_sig = prev_ty.fn_sig(self.tcx);
1151                         let b_sig = self
1152                             .tcx
1153                             .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
1154                         (Some(a_sig), Some(b_sig))
1155                     }
1156                     (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => (
1157                         Some(self.tcx.signature_unclosure(
1158                             substs_a.as_closure().sig(),
1159                             hir::Unsafety::Normal,
1160                         )),
1161                         Some(self.tcx.signature_unclosure(
1162                             substs_b.as_closure().sig(),
1163                             hir::Unsafety::Normal,
1164                         )),
1165                     ),
1166                     _ => (None, None),
1167                 }
1168             }
1169         };
1170         if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
1171             // Intrinsics are not coercible to function pointers.
1172             if a_sig.abi() == Abi::RustIntrinsic
1173                 || a_sig.abi() == Abi::PlatformIntrinsic
1174                 || b_sig.abi() == Abi::RustIntrinsic
1175                 || b_sig.abi() == Abi::PlatformIntrinsic
1176             {
1177                 return Err(TypeError::IntrinsicCast);
1178             }
1179             // The signature must match.
1180             let (a_sig, b_sig) = self.normalize(new.span, (a_sig, b_sig));
1181             let sig = self
1182                 .at(cause, self.param_env)
1183                 .trace(prev_ty, new_ty)
1184                 .lub(DefineOpaqueTypes::No, a_sig, b_sig)
1185                 .map(|ok| self.register_infer_ok_obligations(ok))?;
1186 
1187             // Reify both sides and return the reified fn pointer type.
1188             let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
1189             let prev_adjustment = match prev_ty.kind() {
1190                 ty::Closure(..) => {
1191                     Adjust::Pointer(PointerCoercion::ClosureFnPointer(a_sig.unsafety()))
1192                 }
1193                 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer),
1194                 _ => unreachable!(),
1195             };
1196             let next_adjustment = match new_ty.kind() {
1197                 ty::Closure(..) => {
1198                     Adjust::Pointer(PointerCoercion::ClosureFnPointer(b_sig.unsafety()))
1199                 }
1200                 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer),
1201                 _ => unreachable!(),
1202             };
1203             for expr in exprs.iter().map(|e| e.as_coercion_site()) {
1204                 self.apply_adjustments(
1205                     expr,
1206                     vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1207                 );
1208             }
1209             self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1210             return Ok(fn_ptr);
1211         }
1212 
1213         // Configure a Coerce instance to compute the LUB.
1214         // We don't allow two-phase borrows on any autorefs this creates since we
1215         // probably aren't processing function arguments here and even if we were,
1216         // they're going to get autorefed again anyway and we can apply 2-phase borrows
1217         // at that time.
1218         let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
1219         coerce.use_lub = true;
1220 
1221         // First try to coerce the new expression to the type of the previous ones,
1222         // but only if the new expression has no coercion already applied to it.
1223         let mut first_error = None;
1224         if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1225             let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1226             match result {
1227                 Ok(ok) => {
1228                     let (adjustments, target) = self.register_infer_ok_obligations(ok);
1229                     self.apply_adjustments(new, adjustments);
1230                     debug!(
1231                         "coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1232                         new_ty, prev_ty, target
1233                     );
1234                     return Ok(target);
1235                 }
1236                 Err(e) => first_error = Some(e),
1237             }
1238         }
1239 
1240         // Then try to coerce the previous expressions to the type of the new one.
1241         // This requires ensuring there are no coercions applied to *any* of the
1242         // previous expressions, other than noop reborrows (ignoring lifetimes).
1243         for expr in exprs {
1244             let expr = expr.as_coercion_site();
1245             let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
1246                 &[
1247                     Adjustment { kind: Adjust::Deref(_), .. },
1248                     Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. },
1249                 ] => {
1250                     match *self.node_ty(expr.hir_id).kind() {
1251                         ty::Ref(_, _, mt_orig) => {
1252                             let mutbl_adj: hir::Mutability = mutbl_adj.into();
1253                             // Reborrow that we can safely ignore, because
1254                             // the next adjustment can only be a Deref
1255                             // which will be merged into it.
1256                             mutbl_adj == mt_orig
1257                         }
1258                         _ => false,
1259                     }
1260                 }
1261                 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1262                 _ => false,
1263             };
1264 
1265             if !noop {
1266                 debug!(
1267                     "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1268                     expr,
1269                 );
1270 
1271                 return self
1272                     .commit_if_ok(|_| {
1273                         self.at(cause, self.param_env).lub(DefineOpaqueTypes::No, prev_ty, new_ty)
1274                     })
1275                     .map(|ok| self.register_infer_ok_obligations(ok));
1276             }
1277         }
1278 
1279         match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1280             Err(_) => {
1281                 // Avoid giving strange errors on failed attempts.
1282                 if let Some(e) = first_error {
1283                     Err(e)
1284                 } else {
1285                     self.commit_if_ok(|_| {
1286                         self.at(cause, self.param_env).lub(DefineOpaqueTypes::No, prev_ty, new_ty)
1287                     })
1288                     .map(|ok| self.register_infer_ok_obligations(ok))
1289                 }
1290             }
1291             Ok(ok) => {
1292                 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1293                 for expr in exprs {
1294                     let expr = expr.as_coercion_site();
1295                     self.apply_adjustments(expr, adjustments.clone());
1296                 }
1297                 debug!(
1298                     "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1299                     prev_ty, new_ty, target
1300                 );
1301                 Ok(target)
1302             }
1303         }
1304     }
1305 }
1306 
1307 /// CoerceMany encapsulates the pattern you should use when you have
1308 /// many expressions that are all getting coerced to a common
1309 /// type. This arises, for example, when you have a match (the result
1310 /// of each arm is coerced to a common type). It also arises in less
1311 /// obvious places, such as when you have many `break foo` expressions
1312 /// that target the same loop, or the various `return` expressions in
1313 /// a function.
1314 ///
1315 /// The basic protocol is as follows:
1316 ///
1317 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1318 ///   This will also serve as the "starting LUB". The expectation is
1319 ///   that this type is something which all of the expressions *must*
1320 ///   be coercible to. Use a fresh type variable if needed.
1321 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1322 ///   - In some cases we wish to coerce "non-expressions" whose types are implicitly
1323 ///     unit. This happens for example if you have a `break` with no expression,
1324 ///     or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1325 ///   - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1326 ///     from you so that you don't have to worry your pretty head about it.
1327 ///     But if an error is reported, the final type will be `err`.
1328 ///   - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1329 ///     previously coerced expressions.
1330 /// - When all done, invoke `complete()`. This will return the LUB of
1331 ///   all your expressions.
1332 ///   - WARNING: I don't believe this final type is guaranteed to be
1333 ///     related to your initial `expected_ty` in any particular way,
1334 ///     although it will typically be a subtype, so you should check it.
1335 ///   - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1336 ///     previously coerced expressions.
1337 ///
1338 /// Example:
1339 ///
1340 /// ```ignore (illustrative)
1341 /// let mut coerce = CoerceMany::new(expected_ty);
1342 /// for expr in exprs {
1343 ///     let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1344 ///     coerce.coerce(fcx, &cause, expr, expr_ty);
1345 /// }
1346 /// let final_ty = coerce.complete(fcx);
1347 /// ```
1348 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1349     expected_ty: Ty<'tcx>,
1350     final_ty: Option<Ty<'tcx>>,
1351     expressions: Expressions<'tcx, 'exprs, E>,
1352     pushed: usize,
1353 }
1354 
1355 /// The type of a `CoerceMany` that is storing up the expressions into
1356 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1357 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1358 
1359 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1360     Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1361     UpFront(&'exprs [E]),
1362 }
1363 
1364 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1365     /// The usual case; collect the set of expressions dynamically.
1366     /// If the full set of coercion sites is known before hand,
1367     /// consider `with_coercion_sites()` instead to avoid allocation.
new(expected_ty: Ty<'tcx>) -> Self1368     pub fn new(expected_ty: Ty<'tcx>) -> Self {
1369         Self::make(expected_ty, Expressions::Dynamic(vec![]))
1370     }
1371 
1372     /// As an optimization, you can create a `CoerceMany` with a
1373     /// preexisting slice of expressions. In this case, you are
1374     /// expected to pass each element in the slice to `coerce(...)` in
1375     /// order. This is used with arrays in particular to avoid
1376     /// needlessly cloning the slice.
with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self1377     pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1378         Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1379     }
1380 
make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self1381     fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1382         CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1383     }
1384 
1385     /// Returns the "expected type" with which this coercion was
1386     /// constructed. This represents the "downward propagated" type
1387     /// that was given to us at the start of typing whatever construct
1388     /// we are typing (e.g., the match expression).
1389     ///
1390     /// Typically, this is used as the expected type when
1391     /// type-checking each of the alternative expressions whose types
1392     /// we are trying to merge.
expected_ty(&self) -> Ty<'tcx>1393     pub fn expected_ty(&self) -> Ty<'tcx> {
1394         self.expected_ty
1395     }
1396 
1397     /// Returns the current "merged type", representing our best-guess
1398     /// at the LUB of the expressions we've seen so far (if any). This
1399     /// isn't *final* until you call `self.complete()`, which will return
1400     /// the merged type.
merged_ty(&self) -> Ty<'tcx>1401     pub fn merged_ty(&self) -> Ty<'tcx> {
1402         self.final_ty.unwrap_or(self.expected_ty)
1403     }
1404 
1405     /// Indicates that the value generated by `expression`, which is
1406     /// of type `expression_ty`, is one of the possibilities that we
1407     /// could coerce from. This will record `expression`, and later
1408     /// calls to `coerce` may come back and add adjustments and things
1409     /// if necessary.
coerce<'a>( &mut self, fcx: &FnCtxt<'a, 'tcx>, cause: &ObligationCause<'tcx>, expression: &'tcx hir::Expr<'tcx>, expression_ty: Ty<'tcx>, )1410     pub fn coerce<'a>(
1411         &mut self,
1412         fcx: &FnCtxt<'a, 'tcx>,
1413         cause: &ObligationCause<'tcx>,
1414         expression: &'tcx hir::Expr<'tcx>,
1415         expression_ty: Ty<'tcx>,
1416     ) {
1417         self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1418     }
1419 
1420     /// Indicates that one of the inputs is a "forced unit". This
1421     /// occurs in a case like `if foo { ... };`, where the missing else
1422     /// generates a "forced unit". Another example is a `loop { break;
1423     /// }`, where the `break` has no argument expression. We treat
1424     /// these cases slightly differently for error-reporting
1425     /// purposes. Note that these tend to correspond to cases where
1426     /// the `()` expression is implicit in the source, and hence we do
1427     /// not take an expression argument.
1428     ///
1429     /// The `augment_error` gives you a chance to extend the error
1430     /// message, in case any results (e.g., we use this to suggest
1431     /// removing a `;`).
coerce_forced_unit<'a>( &mut self, fcx: &FnCtxt<'a, 'tcx>, cause: &ObligationCause<'tcx>, augment_error: &mut dyn FnMut(&mut Diagnostic), label_unit_as_expected: bool, )1432     pub fn coerce_forced_unit<'a>(
1433         &mut self,
1434         fcx: &FnCtxt<'a, 'tcx>,
1435         cause: &ObligationCause<'tcx>,
1436         augment_error: &mut dyn FnMut(&mut Diagnostic),
1437         label_unit_as_expected: bool,
1438     ) {
1439         self.coerce_inner(
1440             fcx,
1441             cause,
1442             None,
1443             Ty::new_unit(fcx.tcx),
1444             Some(augment_error),
1445             label_unit_as_expected,
1446         )
1447     }
1448 
1449     /// The inner coercion "engine". If `expression` is `None`, this
1450     /// is a forced-unit case, and hence `expression_ty` must be
1451     /// `Nil`.
1452     #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
coerce_inner<'a>( &mut self, fcx: &FnCtxt<'a, 'tcx>, cause: &ObligationCause<'tcx>, expression: Option<&'tcx hir::Expr<'tcx>>, mut expression_ty: Ty<'tcx>, augment_error: Option<&mut dyn FnMut(&mut Diagnostic)>, label_expression_as_expected: bool, )1453     pub(crate) fn coerce_inner<'a>(
1454         &mut self,
1455         fcx: &FnCtxt<'a, 'tcx>,
1456         cause: &ObligationCause<'tcx>,
1457         expression: Option<&'tcx hir::Expr<'tcx>>,
1458         mut expression_ty: Ty<'tcx>,
1459         augment_error: Option<&mut dyn FnMut(&mut Diagnostic)>,
1460         label_expression_as_expected: bool,
1461     ) {
1462         // Incorporate whatever type inference information we have
1463         // until now; in principle we might also want to process
1464         // pending obligations, but doing so should only improve
1465         // compatibility (hopefully that is true) by helping us
1466         // uncover never types better.
1467         if expression_ty.is_ty_var() {
1468             expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1469         }
1470 
1471         // If we see any error types, just propagate that error
1472         // upwards.
1473         if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1474             self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1475             return;
1476         }
1477 
1478         // Handle the actual type unification etc.
1479         let result = if let Some(expression) = expression {
1480             if self.pushed == 0 {
1481                 // Special-case the first expression we are coercing.
1482                 // To be honest, I'm not entirely sure why we do this.
1483                 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1484                 fcx.try_coerce(
1485                     expression,
1486                     expression_ty,
1487                     self.expected_ty,
1488                     AllowTwoPhase::No,
1489                     Some(cause.clone()),
1490                 )
1491             } else {
1492                 match self.expressions {
1493                     Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1494                         cause,
1495                         exprs,
1496                         self.merged_ty(),
1497                         expression,
1498                         expression_ty,
1499                     ),
1500                     Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1501                         cause,
1502                         &coercion_sites[0..self.pushed],
1503                         self.merged_ty(),
1504                         expression,
1505                         expression_ty,
1506                     ),
1507                 }
1508             }
1509         } else {
1510             // this is a hack for cases where we default to `()` because
1511             // the expression etc has been omitted from the source. An
1512             // example is an `if let` without an else:
1513             //
1514             //     if let Some(x) = ... { }
1515             //
1516             // we wind up with a second match arm that is like `_ =>
1517             // ()`. That is the case we are considering here. We take
1518             // a different path to get the right "expected, found"
1519             // message and so forth (and because we know that
1520             // `expression_ty` will be unit).
1521             //
1522             // Another example is `break` with no argument expression.
1523             assert!(expression_ty.is_unit(), "if let hack without unit type");
1524             fcx.at(cause, fcx.param_env)
1525                 // needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1526                 .eq_exp(
1527                     DefineOpaqueTypes::Yes,
1528                     label_expression_as_expected,
1529                     expression_ty,
1530                     self.merged_ty(),
1531                 )
1532                 .map(|infer_ok| {
1533                     fcx.register_infer_ok_obligations(infer_ok);
1534                     expression_ty
1535                 })
1536         };
1537 
1538         debug!(?result);
1539         match result {
1540             Ok(v) => {
1541                 self.final_ty = Some(v);
1542                 if let Some(e) = expression {
1543                     match self.expressions {
1544                         Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1545                         Expressions::UpFront(coercion_sites) => {
1546                             // if the user gave us an array to validate, check that we got
1547                             // the next expression in the list, as expected
1548                             assert_eq!(
1549                                 coercion_sites[self.pushed].as_coercion_site().hir_id,
1550                                 e.hir_id
1551                             );
1552                         }
1553                     }
1554                     self.pushed += 1;
1555                 }
1556             }
1557             Err(coercion_error) => {
1558                 // Mark that we've failed to coerce the types here to suppress
1559                 // any superfluous errors we might encounter while trying to
1560                 // emit or provide suggestions on how to fix the initial error.
1561                 fcx.set_tainted_by_errors(
1562                     fcx.tcx.sess.delay_span_bug(cause.span, "coercion error but no error emitted"),
1563                 );
1564                 let (expected, found) = if label_expression_as_expected {
1565                     // In the case where this is a "forced unit", like
1566                     // `break`, we want to call the `()` "expected"
1567                     // since it is implied by the syntax.
1568                     // (Note: not all force-units work this way.)"
1569                     (expression_ty, self.merged_ty())
1570                 } else {
1571                     // Otherwise, the "expected" type for error
1572                     // reporting is the current unification type,
1573                     // which is basically the LUB of the expressions
1574                     // we've seen so far (combined with the expected
1575                     // type)
1576                     (self.merged_ty(), expression_ty)
1577                 };
1578                 let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
1579 
1580                 let mut err;
1581                 let mut unsized_return = false;
1582                 let mut visitor = CollectRetsVisitor { ret_exprs: vec![] };
1583                 match *cause.code() {
1584                     ObligationCauseCode::ReturnNoExpression => {
1585                         err = struct_span_err!(
1586                             fcx.tcx.sess,
1587                             cause.span,
1588                             E0069,
1589                             "`return;` in a function whose return type is not `()`"
1590                         );
1591                         err.span_label(cause.span, "return type is not `()`");
1592                     }
1593                     ObligationCauseCode::BlockTailExpression(blk_id) => {
1594                         let parent_id = fcx.tcx.hir().parent_id(blk_id);
1595                         err = self.report_return_mismatched_types(
1596                             cause,
1597                             expected,
1598                             found,
1599                             coercion_error,
1600                             fcx,
1601                             parent_id,
1602                             expression,
1603                             Some(blk_id),
1604                         );
1605                         if !fcx.tcx.features().unsized_locals {
1606                             unsized_return = self.is_return_ty_definitely_unsized(fcx);
1607                         }
1608                         if let Some(expression) = expression
1609                             && let hir::ExprKind::Loop(loop_blk, ..) = expression.kind {
1610                               intravisit::walk_block(& mut visitor, loop_blk);
1611                         }
1612                     }
1613                     ObligationCauseCode::ReturnValue(id) => {
1614                         err = self.report_return_mismatched_types(
1615                             cause,
1616                             expected,
1617                             found,
1618                             coercion_error,
1619                             fcx,
1620                             id,
1621                             expression,
1622                             None,
1623                         );
1624                         if !fcx.tcx.features().unsized_locals {
1625                             unsized_return = self.is_return_ty_definitely_unsized(fcx);
1626                         }
1627                     }
1628                     _ => {
1629                         err = fcx.err_ctxt().report_mismatched_types(
1630                             cause,
1631                             expected,
1632                             found,
1633                             coercion_error,
1634                         );
1635                     }
1636                 }
1637 
1638                 if let Some(augment_error) = augment_error {
1639                     augment_error(&mut err);
1640                 }
1641 
1642                 let is_insufficiently_polymorphic =
1643                     matches!(coercion_error, TypeError::RegionsInsufficientlyPolymorphic(..));
1644 
1645                 if !is_insufficiently_polymorphic && let Some(expr) = expression {
1646                     fcx.emit_coerce_suggestions(
1647                         &mut err,
1648                         expr,
1649                         found,
1650                         expected,
1651                         None,
1652                         Some(coercion_error),
1653                     );
1654                 }
1655 
1656                 if visitor.ret_exprs.len() > 0 && let Some(expr) = expression {
1657                     self.note_unreachable_loop_return(&mut err, &expr, &visitor.ret_exprs);
1658                 }
1659 
1660                 let reported = err.emit_unless(unsized_return);
1661 
1662                 self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
1663             }
1664         }
1665     }
1666 
note_unreachable_loop_return( &self, err: &mut Diagnostic, expr: &hir::Expr<'tcx>, ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>, )1667     fn note_unreachable_loop_return(
1668         &self,
1669         err: &mut Diagnostic,
1670         expr: &hir::Expr<'tcx>,
1671         ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>,
1672     ) {
1673         let hir::ExprKind::Loop(_, _, _, loop_span) = expr.kind else { return;};
1674         let mut span: MultiSpan = vec![loop_span].into();
1675         span.push_span_label(loop_span, "this might have zero elements to iterate on");
1676         const MAXITER: usize = 3;
1677         let iter = ret_exprs.iter().take(MAXITER);
1678         for ret_expr in iter {
1679             span.push_span_label(
1680                 ret_expr.span,
1681                 "if the loop doesn't execute, this value would never get returned",
1682             );
1683         }
1684         err.span_note(
1685             span,
1686             "the function expects a value to always be returned, but loops might run zero times",
1687         );
1688         if MAXITER < ret_exprs.len() {
1689             err.note(format!(
1690                 "if the loop doesn't execute, {} other values would never get returned",
1691                 ret_exprs.len() - MAXITER
1692             ));
1693         }
1694         err.help(
1695             "return a value for the case when the loop has zero elements to iterate on, or \
1696            consider changing the return type to account for that possibility",
1697         );
1698     }
1699 
report_return_mismatched_types<'a>( &self, cause: &ObligationCause<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, ty_err: TypeError<'tcx>, fcx: &FnCtxt<'a, 'tcx>, id: hir::HirId, expression: Option<&'tcx hir::Expr<'tcx>>, blk_id: Option<hir::HirId>, ) -> DiagnosticBuilder<'a, ErrorGuaranteed>1700     fn report_return_mismatched_types<'a>(
1701         &self,
1702         cause: &ObligationCause<'tcx>,
1703         expected: Ty<'tcx>,
1704         found: Ty<'tcx>,
1705         ty_err: TypeError<'tcx>,
1706         fcx: &FnCtxt<'a, 'tcx>,
1707         id: hir::HirId,
1708         expression: Option<&'tcx hir::Expr<'tcx>>,
1709         blk_id: Option<hir::HirId>,
1710     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1711         let mut err = fcx.err_ctxt().report_mismatched_types(cause, expected, found, ty_err);
1712 
1713         let parent_id = fcx.tcx.hir().parent_id(id);
1714         let parent = fcx.tcx.hir().get(parent_id);
1715         if let Some(expr) = expression
1716             && let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { body, .. }), .. }) = parent
1717             && !matches!(fcx.tcx.hir().body(body).value.kind, hir::ExprKind::Block(..))
1718         {
1719             fcx.suggest_missing_semicolon(&mut err, expr, expected, true);
1720         }
1721         // Verify that this is a tail expression of a function, otherwise the
1722         // label pointing out the cause for the type coercion will be wrong
1723         // as prior return coercions would not be relevant (#57664).
1724         let fn_decl = if let (Some(expr), Some(blk_id)) = (expression, blk_id) {
1725             let pointing_at_return_type =
1726                 fcx.suggest_mismatched_types_on_tail(&mut err, expr, expected, found, blk_id);
1727             if let (Some(cond_expr), true, false) = (
1728                 fcx.tcx.hir().get_if_cause(expr.hir_id),
1729                 expected.is_unit(),
1730                 pointing_at_return_type,
1731             )
1732                 // If the block is from an external macro or try (`?`) desugaring, then
1733                 // do not suggest adding a semicolon, because there's nowhere to put it.
1734                 // See issues #81943 and #87051.
1735                 && matches!(
1736                     cond_expr.span.desugaring_kind(),
1737                     None | Some(DesugaringKind::WhileLoop)
1738                 ) && !in_external_macro(fcx.tcx.sess, cond_expr.span)
1739                     && !matches!(
1740                         cond_expr.kind,
1741                         hir::ExprKind::Match(.., hir::MatchSource::TryDesugar)
1742                     )
1743             {
1744                 err.span_label(cond_expr.span, "expected this to be `()`");
1745                 if expr.can_have_side_effects() {
1746                     fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1747                 }
1748             }
1749             fcx.get_node_fn_decl(parent)
1750                 .map(|(fn_id, fn_decl, _, is_main)| (fn_id, fn_decl, is_main))
1751         } else {
1752             fcx.get_fn_decl(parent_id)
1753         };
1754 
1755         if let Some((fn_id, fn_decl, can_suggest)) = fn_decl {
1756             if blk_id.is_none() {
1757                 fcx.suggest_missing_return_type(
1758                     &mut err,
1759                     &fn_decl,
1760                     expected,
1761                     found,
1762                     can_suggest,
1763                     fn_id,
1764                 );
1765             }
1766         }
1767 
1768         let parent_id = fcx.tcx.hir().get_parent_item(id);
1769         let parent_item = fcx.tcx.hir().get_by_def_id(parent_id.def_id);
1770 
1771         if let (Some(expr), Some(_), Some((fn_id, fn_decl, _, _))) =
1772             (expression, blk_id, fcx.get_node_fn_decl(parent_item))
1773         {
1774             fcx.suggest_missing_break_or_return_expr(
1775                 &mut err, expr, fn_decl, expected, found, id, fn_id,
1776             );
1777         }
1778 
1779         let ret_coercion_span = fcx.ret_coercion_span.get();
1780 
1781         if let Some(sp) = ret_coercion_span
1782             // If the closure has an explicit return type annotation, or if
1783             // the closure's return type has been inferred from outside
1784             // requirements (such as an Fn* trait bound), then a type error
1785             // may occur at the first return expression we see in the closure
1786             // (if it conflicts with the declared return type). Skip adding a
1787             // note in this case, since it would be incorrect.
1788             && let Some(fn_sig) = fcx.body_fn_sig()
1789             && fn_sig.output().is_ty_var()
1790         {
1791             err.span_note(
1792                 sp,
1793                 format!(
1794                     "return type inferred to be `{}` here",
1795                     expected
1796                 ),
1797             );
1798         }
1799 
1800         err
1801     }
1802 
1803     /// Checks whether the return type is unsized via an obligation, which makes
1804     /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
1805     /// false but technically valid for typeck.
is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool1806     fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
1807         if let Some(sig) = fcx.body_fn_sig() {
1808             !fcx.predicate_may_hold(&Obligation::new(
1809                 fcx.tcx,
1810                 ObligationCause::dummy(),
1811                 fcx.param_env,
1812                 ty::TraitRef::new(
1813                     fcx.tcx,
1814                     fcx.tcx.require_lang_item(hir::LangItem::Sized, None),
1815                     [sig.output()],
1816                 ),
1817             ))
1818         } else {
1819             false
1820         }
1821     }
1822 
complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx>1823     pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1824         if let Some(final_ty) = self.final_ty {
1825             final_ty
1826         } else {
1827             // If we only had inputs that were of type `!` (or no
1828             // inputs at all), then the final type is `!`.
1829             assert_eq!(self.pushed, 0);
1830             fcx.tcx.types.never
1831         }
1832     }
1833 }
1834 
1835 /// Something that can be converted into an expression to which we can
1836 /// apply a coercion.
1837 pub trait AsCoercionSite {
as_coercion_site(&self) -> &hir::Expr<'_>1838     fn as_coercion_site(&self) -> &hir::Expr<'_>;
1839 }
1840 
1841 impl AsCoercionSite for hir::Expr<'_> {
as_coercion_site(&self) -> &hir::Expr<'_>1842     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1843         self
1844     }
1845 }
1846 
1847 impl<'a, T> AsCoercionSite for &'a T
1848 where
1849     T: AsCoercionSite,
1850 {
as_coercion_site(&self) -> &hir::Expr<'_>1851     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1852         (**self).as_coercion_site()
1853     }
1854 }
1855 
1856 impl AsCoercionSite for ! {
as_coercion_site(&self) -> &hir::Expr<'_>1857     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1858         unreachable!()
1859     }
1860 }
1861 
1862 impl AsCoercionSite for hir::Arm<'_> {
as_coercion_site(&self) -> &hir::Expr<'_>1863     fn as_coercion_site(&self) -> &hir::Expr<'_> {
1864         &self.body
1865     }
1866 }
1867