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