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