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