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