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