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