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