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