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