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