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