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