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).
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.
21 //! When infering the generic arguments of functions, the argument
22 //! order is relevant, which can lead to the following edge case:
25 //! fn foo<T>(a: T, b: T) {
29 //! foo(&7i32, &mut 7i32);
30 //! // This compiles, as we first infer `T` to be `&i32`,
31 //! // and then coerce `&mut 7i32` to `&7i32`.
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`.
38 use crate::astconv::AstConv;
39 use crate::check::FnCtxt;
40 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
42 use rustc_hir::def_id::DefId;
43 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
44 use rustc_infer::infer::{Coercion, InferOk, InferResult};
45 use rustc_infer::traits::Obligation;
46 use rustc_middle::lint::in_external_macro;
47 use rustc_middle::ty::adjustment::{
48 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast,
50 use rustc_middle::ty::error::TypeError;
51 use rustc_middle::ty::fold::TypeFoldable;
52 use rustc_middle::ty::relate::RelateResult;
53 use rustc_middle::ty::subst::SubstsRef;
54 use rustc_middle::ty::{self, ToPredicate, Ty, TypeAndMut};
55 use rustc_session::parse::feature_err;
56 use rustc_span::symbol::sym;
57 use rustc_span::{self, BytePos, Span};
58 use rustc_target::spec::abi::Abi;
59 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
60 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode};
62 use smallvec::{smallvec, SmallVec};
65 struct Coerce<'a, 'tcx> {
66 fcx: &'a FnCtxt<'a, 'tcx>,
67 cause: ObligationCause<'tcx>,
69 /// Determines whether or not allow_two_phase_borrow is set on any
70 /// autoref adjustments we create while coercing. We don't want to
71 /// allow deref coercions to create two-phase borrows, at least initially,
72 /// but we do need two-phase borrows for function argument reborrows.
73 /// See #47489 and #48598
74 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
75 allow_two_phase: AllowTwoPhase,
78 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
79 type Target = FnCtxt<'a, 'tcx>;
80 fn deref(&self) -> &Self::Target {
85 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
87 /// Coercing a mutable reference to an immutable works, while
88 /// coercing `&T` to `&mut T` should be forbidden.
89 fn coerce_mutbls<'tcx>(
90 from_mutbl: hir::Mutability,
91 to_mutbl: hir::Mutability,
92 ) -> RelateResult<'tcx, ()> {
93 match (from_mutbl, to_mutbl) {
94 (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not)
95 | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()),
96 (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability),
100 /// Do not require any adjustments, i.e. coerce `x -> x`.
101 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> {
105 fn simple(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
106 move |target| vec![Adjustment { kind, target }]
109 /// This always returns `Ok(...)`.
111 adj: Vec<Adjustment<'tcx>>,
113 obligations: traits::PredicateObligations<'tcx>,
114 ) -> CoerceResult<'tcx> {
115 Ok(InferOk { value: (adj, target), obligations })
118 impl<'f, 'tcx> Coerce<'f, 'tcx> {
120 fcx: &'f FnCtxt<'f, 'tcx>,
121 cause: ObligationCause<'tcx>,
122 allow_two_phase: AllowTwoPhase,
124 Coerce { fcx, cause, allow_two_phase, use_lub: false }
127 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
128 debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
129 self.commit_if_ok(|_| {
131 self.at(&self.cause, self.fcx.param_env).lub(b, a)
133 self.at(&self.cause, self.fcx.param_env)
135 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
140 /// Unify two types (using sub or lub) and produce a specific coercion.
141 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx>
143 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
146 .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations))
149 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
150 // First, remove any resolved type variables (at the top level, at least):
151 let a = self.shallow_resolve(a);
152 let b = self.shallow_resolve(b);
153 debug!("Coerce.tys({:?} => {:?})", a, b);
155 // Just ignore error types.
156 if a.references_error() || b.references_error() {
157 return success(vec![], self.fcx.tcx.ty_error(), vec![]);
160 // Coercing from `!` to any type is allowed:
162 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
163 // type variable, we want `?T` to fallback to `!` if not
164 // otherwise constrained. An example where this arises:
166 // let _: Option<?T> = Some({ return; });
168 // here, we would coerce from `!` to `?T`.
169 return if b.is_ty_var() {
170 // Micro-optimization: no need for this if `b` is
171 // already resolved in some way.
172 let diverging_ty = self.next_diverging_ty_var(TypeVariableOrigin {
173 kind: TypeVariableOriginKind::AdjustmentType,
174 span: self.cause.span,
176 self.coerce_from_inference_variable(diverging_ty, b, simple(Adjust::NeverToAny))
178 success(simple(Adjust::NeverToAny)(b), b, vec![])
182 // Coercing *from* an unresolved inference variable means that
183 // we have no information about the source type. This will always
184 // ultimately fall back to some form of subtyping.
186 return self.coerce_from_inference_variable(a, b, identity);
189 // Consider coercing the subtype to a DST
191 // NOTE: this is wrapped in a `commit_if_ok` because it creates
192 // a "spurious" type variable, and we don't want to have that
193 // type variable in memory if the coercion fails.
194 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
197 debug!("coerce: unsize successful");
200 Err(TypeError::ObjectUnsafeCoercion(did)) => {
201 debug!("coerce: unsize not object safe");
202 return Err(TypeError::ObjectUnsafeCoercion(did));
206 debug!("coerce: unsize failed");
208 // Examine the supertype and consider auto-borrowing.
210 ty::RawPtr(mt_b) => {
211 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
213 ty::Ref(r_b, _, mutbl_b) => {
214 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
221 // Function items are coercible to any closure
222 // type; function pointers are not (that would
223 // require double indirection).
224 // Additionally, we permit coercion of function
225 // items to drop the unsafe qualifier.
226 self.coerce_from_fn_item(a, b)
229 // We permit coercion of fn pointers to drop the
231 self.coerce_from_fn_pointer(a, a_f, b)
233 ty::Closure(closure_def_id_a, substs_a) => {
234 // Non-capturing closures are coercible to
235 // function pointers or unsafe function pointers.
236 // It cannot convert closures that require unsafe.
237 self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b)
240 // Otherwise, just use unification rules.
241 self.unify_and(a, b, identity)
246 /// Coercing *from* an inference variable. In this case, we have no information
247 /// about the source type, so we can't really do a true coercion and we always
248 /// fall back to subtyping (`unify_and`).
249 fn coerce_from_inference_variable(
253 make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
254 ) -> CoerceResult<'tcx> {
255 debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
256 assert!(a.is_ty_var() && self.infcx.shallow_resolve(a) == a);
257 assert!(self.infcx.shallow_resolve(b) == b);
260 // Two unresolved type variables: create a `Coerce` predicate.
261 let target_ty = if self.use_lub {
262 self.infcx.next_ty_var(TypeVariableOrigin {
263 kind: TypeVariableOriginKind::LatticeVariable,
264 span: self.cause.span,
270 let mut obligations = Vec::with_capacity(2);
271 for &source_ty in &[a, b] {
272 if source_ty != target_ty {
273 obligations.push(Obligation::new(
276 ty::PredicateKind::Coerce(ty::CoercePredicate {
280 .to_predicate(self.tcx()),
286 "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
287 target_ty, obligations
289 let adjustments = make_adjustments(target_ty);
290 InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations })
292 // One unresolved type variable: just apply subtyping, we may be able
293 // to do something useful.
294 self.unify_and(a, b, make_adjustments)
298 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
299 /// To match `A` with `B`, autoderef will be performed,
300 /// calling `deref`/`deref_mut` where necessary.
301 fn coerce_borrowed_pointer(
305 r_b: ty::Region<'tcx>,
306 mutbl_b: hir::Mutability,
307 ) -> CoerceResult<'tcx> {
308 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
310 // If we have a parameter of type `&M T_a` and the value
311 // provided is `expr`, we will be adding an implicit borrow,
312 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
313 // to type check, we will construct the type that `&M*expr` would
316 let (r_a, mt_a) = match *a.kind() {
317 ty::Ref(r_a, ty, mutbl) => {
318 let mt_a = ty::TypeAndMut { ty, mutbl };
319 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
322 _ => return self.unify_and(a, b, identity),
325 let span = self.cause.span;
327 let mut first_error = None;
328 let mut r_borrow_var = None;
329 let mut autoderef = self.autoderef(span, a);
330 let mut found = None;
332 for (referent_ty, autoderefs) in autoderef.by_ref() {
334 // Don't let this pass, otherwise it would cause
335 // &T to autoref to &&T.
339 // At this point, we have deref'd `a` to `referent_ty`. So
340 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
341 // In the autoderef loop for `&'a mut Vec<T>`, we would get
344 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
345 // - `Vec<T>` -- 1 deref
346 // - `[T]` -- 2 deref
348 // At each point after the first callback, we want to
349 // check to see whether this would match out target type
350 // (`&'b mut [T]`) if we autoref'd it. We can't just
351 // compare the referent types, though, because we still
352 // have to consider the mutability. E.g., in the case
353 // we've been considering, we have an `&mut` reference, so
354 // the `T` in `[T]` needs to be unified with equality.
356 // Therefore, we construct reference types reflecting what
357 // the types will be after we do the final auto-ref and
358 // compare those. Note that this means we use the target
359 // mutability [1], since it may be that we are coercing
360 // from `&mut T` to `&U`.
362 // One fine point concerns the region that we use. We
363 // choose the region such that the region of the final
364 // type that results from `unify` will be the region we
365 // want for the autoref:
367 // - if in sub mode, that means we want to use `'b` (the
368 // region from the target reference) for both
369 // pointers [2]. This is because sub mode (somewhat
370 // arbitrarily) returns the subtype region. In the case
371 // where we are coercing to a target type, we know we
372 // want to use that target type region (`'b`) because --
373 // for the program to type-check -- it must be the
374 // smaller of the two.
375 // - One fine point. It may be surprising that we can
376 // use `'b` without relating `'a` and `'b`. The reason
377 // that this is ok is that what we produce is
378 // effectively a `&'b *x` expression (if you could
379 // annotate the region of a borrow), and regionck has
380 // code that adds edges from the region of a borrow
381 // (`'b`, here) into the regions in the borrowed
382 // expression (`*x`, here). (Search for "link".)
383 // - if in lub mode, things can get fairly complicated. The
384 // easiest thing is just to make a fresh
385 // region variable [4], which effectively means we defer
386 // the decision to region inference (and regionck, which will add
387 // some more edges to this variable). However, this can wind up
388 // creating a crippling number of variables in some cases --
389 // e.g., #32278 -- so we optimize one particular case [3].
390 // Let me try to explain with some examples:
391 // - The "running example" above represents the simple case,
392 // where we have one `&` reference at the outer level and
393 // ownership all the rest of the way down. In this case,
394 // we want `LUB('a, 'b)` as the resulting region.
395 // - However, if there are nested borrows, that region is
396 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
397 // `&'b T`. In this case, `'a` is actually irrelevant.
398 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
399 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
400 // (The errors actually show up in borrowck, typically, because
401 // this extra edge causes the region `'a` to be inferred to something
402 // too big, which then results in borrowck errors.)
403 // - We could track the innermost shared reference, but there is already
404 // code in regionck that has the job of creating links between
405 // the region of a borrow and the regions in the thing being
406 // borrowed (here, `'a` and `'x`), and it knows how to handle
407 // all the various cases. So instead we just make a region variable
408 // and let regionck figure it out.
409 let r = if !self.use_lub {
411 } else if autoderefs == 1 {
414 if r_borrow_var.is_none() {
415 // create var lazily, at most once
416 let coercion = Coercion(span);
417 let r = self.next_region_var(coercion);
418 r_borrow_var = Some(r); // [4] above
420 r_borrow_var.unwrap()
422 let derefd_ty_a = self.tcx.mk_ref(
426 mutbl: mutbl_b, // [1] above
429 match self.unify(derefd_ty_a, b) {
435 if first_error.is_none() {
436 first_error = Some(err);
442 // Extract type or return an error. We return the first error
443 // we got, which should be from relating the "base" type
444 // (e.g., in example above, the failure from relating `Vec<T>`
445 // to the target type), since that should be the least
447 let InferOk { value: ty, mut obligations } = match found {
450 let err = first_error.expect("coerce_borrowed_pointer had no error");
451 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
456 if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 {
457 // As a special case, if we would produce `&'a *x`, that's
458 // a total no-op. We end up with the type `&'a T` just as
459 // we started with. In that case, just skip it
460 // altogether. This is just an optimization.
462 // Note that for `&mut`, we DO want to reborrow --
463 // otherwise, this would be a move, which might be an
464 // error. For example `foo(self.x)` where `self` and
465 // `self.x` both have `&mut `type would be a move of
466 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
467 // which is a borrow.
468 assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U
469 return success(vec![], ty, obligations);
472 let InferOk { value: mut adjustments, obligations: o } =
473 self.adjust_steps_as_infer_ok(&autoderef);
474 obligations.extend(o);
475 obligations.extend(autoderef.into_obligations());
477 // Now apply the autoref. We have to extract the region out of
478 // the final ref type we got.
479 let r_borrow = match ty.kind() {
480 ty::Ref(r_borrow, _, _) => r_borrow,
481 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
483 let mutbl = match mutbl_b {
484 hir::Mutability::Not => AutoBorrowMutability::Not,
485 hir::Mutability::Mut => {
486 AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase }
489 adjustments.push(Adjustment {
490 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
494 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
496 success(adjustments, ty, obligations)
499 // &[T; n] or &mut [T; n] -> &[T]
500 // or &mut [T; n] -> &mut [T]
501 // or &Concrete -> &Trait, etc.
502 fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> {
503 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
505 source = self.shallow_resolve(source);
506 target = self.shallow_resolve(target);
507 debug!("coerce_unsized: resolved source={:?} target={:?}", source, target);
509 // These 'if' statements require some explanation.
510 // The `CoerceUnsized` trait is special - it is only
511 // possible to write `impl CoerceUnsized<B> for A` where
512 // A and B have 'matching' fields. This rules out the following
513 // two types of blanket impls:
515 // `impl<T> CoerceUnsized<T> for SomeType`
516 // `impl<T> CoerceUnsized<SomeType> for T`
518 // Both of these trigger a special `CoerceUnsized`-related error (E0376)
520 // We can take advantage of this fact to avoid performing unnecessary work.
521 // If either `source` or `target` is a type variable, then any applicable impl
522 // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
523 // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
526 // However, these are exactly the kinds of impls which are forbidden by
527 // the compiler! Therefore, we can be sure that coercion will always fail
528 // when either the source or target type is a type variable. This allows us
529 // to skip performing any trait selection, and immediately bail out.
530 if source.is_ty_var() {
531 debug!("coerce_unsized: source is a TyVar, bailing out");
532 return Err(TypeError::Mismatch);
534 if target.is_ty_var() {
535 debug!("coerce_unsized: target is a TyVar, bailing out");
536 return Err(TypeError::Mismatch);
540 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
541 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
544 debug!("missing Unsize or CoerceUnsized traits");
545 return Err(TypeError::Mismatch);
548 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
549 // a DST unless we have to. This currently comes out in the wash since
550 // we can't unify [T] with U. But to properly support DST, we need to allow
551 // that, at which point we will need extra checks on the target here.
553 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
554 let reborrow = match (source.kind(), target.kind()) {
555 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
556 coerce_mutbls(mutbl_a, mutbl_b)?;
558 let coercion = Coercion(self.cause.span);
559 let r_borrow = self.next_region_var(coercion);
560 let mutbl = match mutbl_b {
561 hir::Mutability::Not => AutoBorrowMutability::Not,
562 hir::Mutability::Mut => AutoBorrowMutability::Mut {
563 // We don't allow two-phase borrows here, at least for initial
564 // implementation. If it happens that this coercion is a function argument,
565 // the reborrow in coerce_borrowed_ptr will pick it up.
566 allow_two_phase_borrow: AllowTwoPhase::No,
570 Adjustment { kind: Adjust::Deref(None), target: ty_a },
572 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
575 .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }),
579 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
580 coerce_mutbls(mt_a, mt_b)?;
583 Adjustment { kind: Adjust::Deref(None), target: ty_a },
585 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
586 target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
592 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
594 // Setup either a subtyping or a LUB relationship between
595 // the `CoerceUnsized` target type and the expected type.
596 // We only have the latter, so we use an inference variable
597 // for the former and let type inference do the rest.
598 let origin = TypeVariableOrigin {
599 kind: TypeVariableOriginKind::MiscVariable,
600 span: self.cause.span,
602 let coerce_target = self.next_ty_var(origin);
603 let mut coercion = self.unify_and(coerce_target, target, |target| {
604 let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target };
606 None => vec![unsize],
607 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
611 let mut selcx = traits::SelectionContext::new(self);
613 // Create an obligation for `Source: CoerceUnsized<Target>`.
614 let cause = ObligationCause::new(
617 ObligationCauseCode::Coercion { source, target },
620 // Use a FIFO queue for this custom fulfillment procedure.
622 // A Vec (or SmallVec) is not a natural choice for a queue. However,
623 // this code path is hot, and this queue usually has a max length of 1
624 // and almost never more than 3. By using a SmallVec we avoid an
625 // allocation, at the (very small) cost of (occasionally) having to
626 // shift subsequent elements down when removing the front element.
627 let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def(
634 &[coerce_target.into()]
637 let mut has_unsized_tuple_coercion = false;
638 let mut has_trait_upcasting_coercion = false;
640 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
641 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
642 // inference might unify those two inner type variables later.
643 let traits = [coerce_unsized_did, unsize_did];
644 while !queue.is_empty() {
645 let obligation = queue.remove(0);
646 debug!("coerce_unsized resolve step: {:?}", obligation);
647 let bound_predicate = obligation.predicate.kind();
648 let trait_pred = match bound_predicate.skip_binder() {
649 ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => {
650 if unsize_did == trait_pred.def_id() {
651 let self_ty = trait_pred.self_ty();
652 let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
653 if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) =
654 (self_ty.kind(), unsize_ty.kind())
656 if data_a.principal_def_id() != data_b.principal_def_id() {
657 debug!("coerce_unsized: found trait upcasting coercion");
658 has_trait_upcasting_coercion = true;
661 if let ty::Tuple(..) = unsize_ty.kind() {
662 debug!("coerce_unsized: found unsized tuple coercion");
663 has_unsized_tuple_coercion = true;
666 bound_predicate.rebind(trait_pred)
669 coercion.obligations.push(obligation);
673 match selcx.select(&obligation.with(trait_pred)) {
674 // Uncertain or unimplemented.
676 if trait_pred.def_id() == unsize_did {
677 let trait_pred = self.resolve_vars_if_possible(trait_pred);
678 let self_ty = trait_pred.skip_binder().self_ty();
679 let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty();
680 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
681 match (&self_ty.kind(), &unsize_ty.kind()) {
682 (ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
683 if self.type_var_is_sized(*v) =>
685 debug!("coerce_unsized: have sized infer {:?}", v);
686 coercion.obligations.push(obligation);
687 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
691 // Some other case for `$0: Unsize<Something>`. Note that we
692 // hit this case even if `Something` is a sized type, so just
693 // don't do the coercion.
694 debug!("coerce_unsized: ambiguous unsize");
695 return Err(TypeError::Mismatch);
699 debug!("coerce_unsized: early return - ambiguous");
700 return Err(TypeError::Mismatch);
703 Err(traits::Unimplemented) => {
704 debug!("coerce_unsized: early return - can't prove obligation");
705 return Err(TypeError::Mismatch);
708 // Object safety violations or miscellaneous.
710 self.report_selection_error(
717 // Treat this like an obligation and follow through
718 // with the unsizing - the lack of a coercion should
719 // be silent, as it causes a type mismatch later.
722 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
726 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
728 &self.tcx.sess.parse_sess,
729 sym::unsized_tuple_coercion,
731 "unsized tuple coercion is not stable enough for use and is subject to change",
736 if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting {
738 &self.tcx.sess.parse_sess,
739 sym::trait_upcasting,
741 "trait upcasting coercion is experimental",
749 fn coerce_from_safe_fn<F, G>(
752 fn_ty_a: ty::PolyFnSig<'tcx>,
756 ) -> CoerceResult<'tcx>
758 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
759 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
761 if let ty::FnPtr(fn_ty_b) = b.kind() {
762 if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
763 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
765 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
766 return self.unify_and(unsafe_a, b, to_unsafe);
769 self.unify_and(a, b, normal)
772 fn coerce_from_fn_pointer(
775 fn_ty_a: ty::PolyFnSig<'tcx>,
777 ) -> CoerceResult<'tcx> {
778 //! Attempts to coerce from the type of a Rust function item
779 //! into a closure or a `proc`.
782 let b = self.shallow_resolve(b);
783 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
785 self.coerce_from_safe_fn(
789 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
794 fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
795 //! Attempts to coerce from the type of a Rust function item
796 //! into a closure or a `proc`.
798 let b = self.shallow_resolve(b);
799 let InferOk { value: b, mut obligations } =
800 self.normalize_associated_types_in_as_infer_ok(self.cause.span, b);
801 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
804 ty::FnPtr(b_sig) => {
805 let a_sig = a.fn_sig(self.tcx);
806 // Intrinsics are not coercible to function pointers
807 if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic {
808 return Err(TypeError::IntrinsicCast);
811 // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
812 if let ty::FnDef(def_id, _) = *a.kind() {
813 if b_sig.unsafety() == hir::Unsafety::Normal
814 && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
816 return Err(TypeError::TargetFeatureCast(def_id));
820 let InferOk { value: a_sig, obligations: o1 } =
821 self.normalize_associated_types_in_as_infer_ok(self.cause.span, a_sig);
822 obligations.extend(o1);
824 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
825 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
832 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
833 target: a_fn_pointer,
836 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
841 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
844 obligations.extend(o2);
845 Ok(InferOk { value, obligations })
847 _ => self.unify_and(a, b, identity),
851 fn coerce_closure_to_fn(
854 closure_def_id_a: DefId,
855 substs_a: SubstsRef<'tcx>,
857 ) -> CoerceResult<'tcx> {
858 //! Attempts to coerce from the type of a non-capturing closure
859 //! into a function pointer.
862 let b = self.shallow_resolve(b);
865 // At this point we haven't done capture analysis, which means
866 // that the ClosureSubsts just contains an inference variable instead
867 // of tuple of captured types.
869 // All we care here is if any variable is being captured and not the exact paths,
870 // so we check `upvars_mentioned` for root variables being captured.
874 .upvars_mentioned(closure_def_id_a.expect_local())
875 .map_or(true, |u| u.is_empty()) =>
877 // We coerce the closure, which has fn type
878 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
880 // `fn(arg0,arg1,...) -> _`
882 // `unsafe fn(arg0,arg1,...) -> _`
883 let closure_sig = substs_a.as_closure().sig();
884 let unsafety = fn_ty.unsafety();
886 self.tcx.mk_fn_ptr(self.tcx.signature_unclosure(closure_sig, unsafety));
887 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
891 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
894 _ => self.unify_and(a, b, identity),
898 fn coerce_unsafe_ptr(
902 mutbl_b: hir::Mutability,
903 ) -> CoerceResult<'tcx> {
904 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
906 let (is_ref, mt_a) = match *a.kind() {
907 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
908 ty::RawPtr(mt) => (false, mt),
909 _ => return self.unify_and(a, b, identity),
911 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
913 // Check that the types which they point at are compatible.
914 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
915 // Although references and unsafe ptrs have the same
916 // representation, we still register an Adjust::DerefRef so that
917 // regionck knows that the region for `a` must be valid here.
919 self.unify_and(a_unsafe, b, |target| {
921 Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
922 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
925 } else if mt_a.mutbl != mutbl_b {
926 self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
928 self.unify_and(a_unsafe, b, identity)
933 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
934 /// Attempt to coerce an expression to a type, and return the
935 /// adjusted type of the expression, if successful.
936 /// Adjustments are only recorded if the coercion succeeded.
937 /// The expressions *must not* have any pre-existing adjustments.
940 expr: &hir::Expr<'_>,
943 allow_two_phase: AllowTwoPhase,
944 ) -> RelateResult<'tcx, Ty<'tcx>> {
945 let source = self.resolve_vars_with_obligations(expr_ty);
946 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
948 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
949 let coerce = Coerce::new(self, cause, allow_two_phase);
950 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
952 let (adjustments, _) = self.register_infer_ok_obligations(ok);
953 self.apply_adjustments(expr, adjustments);
954 Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target })
957 /// Same as `try_coerce()`, but without side-effects.
958 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
959 let source = self.resolve_vars_with_obligations(expr_ty);
960 debug!("coercion::can({:?} -> {:?})", source, target);
962 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
963 // We don't ever need two-phase here since we throw out the result of the coercion
964 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
965 self.probe(|_| coerce.coerce(source, target)).is_ok()
968 /// Given a type and a target type, this function will calculate and return
969 /// how many dereference steps needed to achieve `expr_ty <: target`. If
970 /// it's not possible, return `None`.
971 pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
972 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
973 // We don't ever need two-phase here since we throw out the result of the coercion
974 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
976 .autoderef(rustc_span::DUMMY_SP, expr_ty)
977 .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
980 /// Given some expressions, their known unified type and another expression,
981 /// tries to unify the types, potentially inserting coercions on any of the
982 /// provided expressions and returns their LUB (aka "common supertype").
984 /// This is really an internal helper. From outside the coercion
985 /// module, you should instantiate a `CoerceMany` instance.
986 fn try_find_coercion_lub<E>(
988 cause: &ObligationCause<'tcx>,
993 ) -> RelateResult<'tcx, Ty<'tcx>>
997 let prev_ty = self.resolve_vars_with_obligations(prev_ty);
998 let new_ty = self.resolve_vars_with_obligations(new_ty);
1000 "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1006 // The following check fixes #88097, where the compiler erroneously
1007 // attempted to coerce a closure type to itself via a function pointer.
1008 if prev_ty == new_ty {
1012 // Special-case that coercion alone cannot handle:
1013 // Function items or non-capturing closures of differing IDs or InternalSubsts.
1014 let (a_sig, b_sig) = {
1015 let is_capturing_closure = |ty| {
1016 if let &ty::Closure(closure_def_id, _substs) = ty {
1017 self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
1022 if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) {
1025 match (prev_ty.kind(), new_ty.kind()) {
1026 (ty::FnDef(..), ty::FnDef(..)) => {
1027 // Don't reify if the function types have a LUB, i.e., they
1028 // are the same function and their parameters have a LUB.
1030 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1032 // We have a LUB of prev_ty and new_ty, just return it.
1033 Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1035 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
1039 (ty::Closure(_, substs), ty::FnDef(..)) => {
1040 let b_sig = new_ty.fn_sig(self.tcx);
1043 .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
1044 (Some(a_sig), Some(b_sig))
1046 (ty::FnDef(..), ty::Closure(_, substs)) => {
1047 let a_sig = prev_ty.fn_sig(self.tcx);
1050 .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
1051 (Some(a_sig), Some(b_sig))
1053 (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => (
1054 Some(self.tcx.signature_unclosure(
1055 substs_a.as_closure().sig(),
1056 hir::Unsafety::Normal,
1058 Some(self.tcx.signature_unclosure(
1059 substs_b.as_closure().sig(),
1060 hir::Unsafety::Normal,
1067 if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
1068 // Intrinsics are not coercible to function pointers.
1069 if a_sig.abi() == Abi::RustIntrinsic
1070 || a_sig.abi() == Abi::PlatformIntrinsic
1071 || b_sig.abi() == Abi::RustIntrinsic
1072 || b_sig.abi() == Abi::PlatformIntrinsic
1074 return Err(TypeError::IntrinsicCast);
1076 // The signature must match.
1077 let a_sig = self.normalize_associated_types_in(new.span, a_sig);
1078 let b_sig = self.normalize_associated_types_in(new.span, b_sig);
1080 .at(cause, self.param_env)
1081 .trace(prev_ty, new_ty)
1083 .map(|ok| self.register_infer_ok_obligations(ok))?;
1085 // Reify both sides and return the reified fn pointer type.
1086 let fn_ptr = self.tcx.mk_fn_ptr(sig);
1087 let prev_adjustment = match prev_ty.kind() {
1088 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.unsafety())),
1089 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1090 _ => unreachable!(),
1092 let next_adjustment = match new_ty.kind() {
1093 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.unsafety())),
1094 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1095 _ => unreachable!(),
1097 for expr in exprs.iter().map(|e| e.as_coercion_site()) {
1098 self.apply_adjustments(
1100 vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1103 self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1107 // Configure a Coerce instance to compute the LUB.
1108 // We don't allow two-phase borrows on any autorefs this creates since we
1109 // probably aren't processing function arguments here and even if we were,
1110 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1112 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
1113 coerce.use_lub = true;
1115 // First try to coerce the new expression to the type of the previous ones,
1116 // but only if the new expression has no coercion already applied to it.
1117 let mut first_error = None;
1118 if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1119 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1122 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1123 self.apply_adjustments(new, adjustments);
1125 "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}",
1130 Err(e) => first_error = Some(e),
1134 // Then try to coerce the previous expressions to the type of the new one.
1135 // This requires ensuring there are no coercions applied to *any* of the
1136 // previous expressions, other than noop reborrows (ignoring lifetimes).
1138 let expr = expr.as_coercion_site();
1139 let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
1140 &[Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }] =>
1142 match *self.node_ty(expr.hir_id).kind() {
1143 ty::Ref(_, _, mt_orig) => {
1144 let mutbl_adj: hir::Mutability = mutbl_adj.into();
1145 // Reborrow that we can safely ignore, because
1146 // the next adjustment can only be a Deref
1147 // which will be merged into it.
1148 mutbl_adj == mt_orig
1153 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1159 "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1164 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1165 .map(|ok| self.register_infer_ok_obligations(ok));
1169 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1171 // Avoid giving strange errors on failed attempts.
1172 if let Some(e) = first_error {
1175 self.commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1176 .map(|ok| self.register_infer_ok_obligations(ok))
1181 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?}",
1184 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1186 let expr = expr.as_coercion_site();
1187 self.apply_adjustments(expr, adjustments.clone());
1195 /// CoerceMany encapsulates the pattern you should use when you have
1196 /// many expressions that are all getting coerced to a common
1197 /// type. This arises, for example, when you have a match (the result
1198 /// of each arm is coerced to a common type). It also arises in less
1199 /// obvious places, such as when you have many `break foo` expressions
1200 /// that target the same loop, or the various `return` expressions in
1203 /// The basic protocol is as follows:
1205 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1206 /// This will also serve as the "starting LUB". The expectation is
1207 /// that this type is something which all of the expressions *must*
1208 /// be coercible to. Use a fresh type variable if needed.
1209 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1210 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1211 /// unit. This happens for example if you have a `break` with no expression,
1212 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1213 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1214 /// from you so that you don't have to worry your pretty head about it.
1215 /// But if an error is reported, the final type will be `err`.
1216 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1217 /// previously coerced expressions.
1218 /// - When all done, invoke `complete()`. This will return the LUB of
1219 /// all your expressions.
1220 /// - WARNING: I don't believe this final type is guaranteed to be
1221 /// related to your initial `expected_ty` in any particular way,
1222 /// although it will typically be a subtype, so you should check it.
1223 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1224 /// previously coerced expressions.
1229 /// let mut coerce = CoerceMany::new(expected_ty);
1230 /// for expr in exprs {
1231 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1232 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1234 /// let final_ty = coerce.complete(fcx);
1236 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1237 expected_ty: Ty<'tcx>,
1238 final_ty: Option<Ty<'tcx>>,
1239 expressions: Expressions<'tcx, 'exprs, E>,
1243 /// The type of a `CoerceMany` that is storing up the expressions into
1244 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1245 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1247 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1248 Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1249 UpFront(&'exprs [E]),
1252 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1253 /// The usual case; collect the set of expressions dynamically.
1254 /// If the full set of coercion sites is known before hand,
1255 /// consider `with_coercion_sites()` instead to avoid allocation.
1256 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1257 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1260 /// As an optimization, you can create a `CoerceMany` with a
1261 /// pre-existing slice of expressions. In this case, you are
1262 /// expected to pass each element in the slice to `coerce(...)` in
1263 /// order. This is used with arrays in particular to avoid
1264 /// needlessly cloning the slice.
1265 pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1266 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1269 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1270 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1273 /// Returns the "expected type" with which this coercion was
1274 /// constructed. This represents the "downward propagated" type
1275 /// that was given to us at the start of typing whatever construct
1276 /// we are typing (e.g., the match expression).
1278 /// Typically, this is used as the expected type when
1279 /// type-checking each of the alternative expressions whose types
1280 /// we are trying to merge.
1281 pub fn expected_ty(&self) -> Ty<'tcx> {
1285 /// Returns the current "merged type", representing our best-guess
1286 /// at the LUB of the expressions we've seen so far (if any). This
1287 /// isn't *final* until you call `self.final()`, which will return
1288 /// the merged type.
1289 pub fn merged_ty(&self) -> Ty<'tcx> {
1290 self.final_ty.unwrap_or(self.expected_ty)
1293 /// Indicates that the value generated by `expression`, which is
1294 /// of type `expression_ty`, is one of the possibilities that we
1295 /// could coerce from. This will record `expression`, and later
1296 /// calls to `coerce` may come back and add adjustments and things
1300 fcx: &FnCtxt<'a, 'tcx>,
1301 cause: &ObligationCause<'tcx>,
1302 expression: &'tcx hir::Expr<'tcx>,
1303 expression_ty: Ty<'tcx>,
1305 self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1308 /// Indicates that one of the inputs is a "forced unit". This
1309 /// occurs in a case like `if foo { ... };`, where the missing else
1310 /// generates a "forced unit". Another example is a `loop { break;
1311 /// }`, where the `break` has no argument expression. We treat
1312 /// these cases slightly differently for error-reporting
1313 /// purposes. Note that these tend to correspond to cases where
1314 /// the `()` expression is implicit in the source, and hence we do
1315 /// not take an expression argument.
1317 /// The `augment_error` gives you a chance to extend the error
1318 /// message, in case any results (e.g., we use this to suggest
1319 /// removing a `;`).
1320 pub fn coerce_forced_unit<'a>(
1322 fcx: &FnCtxt<'a, 'tcx>,
1323 cause: &ObligationCause<'tcx>,
1324 augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1325 label_unit_as_expected: bool,
1332 Some(augment_error),
1333 label_unit_as_expected,
1337 /// The inner coercion "engine". If `expression` is `None`, this
1338 /// is a forced-unit case, and hence `expression_ty` must be
1340 #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1341 crate fn coerce_inner<'a>(
1343 fcx: &FnCtxt<'a, 'tcx>,
1344 cause: &ObligationCause<'tcx>,
1345 expression: Option<&'tcx hir::Expr<'tcx>>,
1346 mut expression_ty: Ty<'tcx>,
1347 augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1348 label_expression_as_expected: bool,
1350 // Incorporate whatever type inference information we have
1351 // until now; in principle we might also want to process
1352 // pending obligations, but doing so should only improve
1353 // compatibility (hopefully that is true) by helping us
1354 // uncover never types better.
1355 if expression_ty.is_ty_var() {
1356 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1359 // If we see any error types, just propagate that error
1361 if expression_ty.references_error() || self.merged_ty().references_error() {
1362 self.final_ty = Some(fcx.tcx.ty_error());
1366 // Handle the actual type unification etc.
1367 let result = if let Some(expression) = expression {
1368 if self.pushed == 0 {
1369 // Special-case the first expression we are coercing.
1370 // To be honest, I'm not entirely sure why we do this.
1371 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1372 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1374 match self.expressions {
1375 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1382 Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1384 &coercion_sites[0..self.pushed],
1392 // this is a hack for cases where we default to `()` because
1393 // the expression etc has been omitted from the source. An
1394 // example is an `if let` without an else:
1396 // if let Some(x) = ... { }
1398 // we wind up with a second match arm that is like `_ =>
1399 // ()`. That is the case we are considering here. We take
1400 // a different path to get the right "expected, found"
1401 // message and so forth (and because we know that
1402 // `expression_ty` will be unit).
1404 // Another example is `break` with no argument expression.
1405 assert!(expression_ty.is_unit(), "if let hack without unit type");
1406 fcx.at(cause, fcx.param_env)
1407 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1409 fcx.register_infer_ok_obligations(infer_ok);
1416 self.final_ty = Some(v);
1417 if let Some(e) = expression {
1418 match self.expressions {
1419 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1420 Expressions::UpFront(coercion_sites) => {
1421 // if the user gave us an array to validate, check that we got
1422 // the next expression in the list, as expected
1424 coercion_sites[self.pushed].as_coercion_site().hir_id,
1432 Err(coercion_error) => {
1433 let (expected, found) = if label_expression_as_expected {
1434 // In the case where this is a "forced unit", like
1435 // `break`, we want to call the `()` "expected"
1436 // since it is implied by the syntax.
1437 // (Note: not all force-units work this way.)"
1438 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1440 // Otherwise, the "expected" type for error
1441 // reporting is the current unification type,
1442 // which is basically the LUB of the expressions
1443 // we've seen so far (combined with the expected
1445 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1449 let mut unsized_return = false;
1451 ObligationCauseCode::ReturnNoExpression => {
1452 err = struct_span_err!(
1456 "`return;` in a function whose return type is not `()`"
1458 err.span_label(cause.span, "return type is not `()`");
1460 ObligationCauseCode::BlockTailExpression(blk_id) => {
1461 let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1462 err = self.report_return_mismatched_types(
1469 expression.map(|expr| (expr, blk_id)),
1471 if !fcx.tcx.features().unsized_locals {
1472 unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1475 ObligationCauseCode::ReturnValue(id) => {
1476 err = self.report_return_mismatched_types(
1485 if !fcx.tcx.features().unsized_locals {
1486 let id = fcx.tcx.hir().get_parent_node(id);
1487 unsized_return = self.is_return_ty_unsized(fcx, id);
1491 err = fcx.report_mismatched_types(cause, expected, found, coercion_error);
1495 if let Some(augment_error) = augment_error {
1496 augment_error(&mut err);
1499 if let Some(expr) = expression {
1500 fcx.emit_coerce_suggestions(&mut err, expr, found, expected, None);
1503 // Error possibly reported in `check_assign` so avoid emitting error again.
1504 let assign_to_bool = expression
1505 // #67273: Use initial expected type as opposed to `expected`.
1506 // Otherwise we end up using prior coercions in e.g. a `match` expression:
1509 // 0 => true, // Because of this...
1510 // 1 => i = 1, // ...`expected == bool` now, but not when checking `i = 1`.
1514 .filter(|e| fcx.is_assign_to_bool(e, self.expected_ty()))
1517 err.emit_unless(assign_to_bool || unsized_return);
1519 self.final_ty = Some(fcx.tcx.ty_error());
1524 fn report_return_mismatched_types<'a>(
1526 cause: &ObligationCause<'tcx>,
1529 ty_err: TypeError<'tcx>,
1530 fcx: &FnCtxt<'a, 'tcx>,
1532 expression: Option<(&'tcx hir::Expr<'tcx>, hir::HirId)>,
1533 ) -> DiagnosticBuilder<'a> {
1534 let mut err = fcx.report_mismatched_types(cause, expected, found, ty_err);
1536 let mut pointing_at_return_type = false;
1537 let mut fn_output = None;
1539 // Verify that this is a tail expression of a function, otherwise the
1540 // label pointing out the cause for the type coercion will be wrong
1541 // as prior return coercions would not be relevant (#57664).
1542 let parent_id = fcx.tcx.hir().get_parent_node(id);
1543 let fn_decl = if let Some((expr, blk_id)) = expression {
1544 pointing_at_return_type =
1545 fcx.suggest_mismatched_types_on_tail(&mut err, expr, expected, found, blk_id);
1546 let parent = fcx.tcx.hir().get(parent_id);
1547 if let (Some(cond_expr), true, false) = (
1548 fcx.tcx.hir().get_if_cause(expr.hir_id),
1550 pointing_at_return_type,
1552 // If the block is from an external macro or try (`?`) desugaring, then
1553 // do not suggest adding a semicolon, because there's nowhere to put it.
1554 // See issues #81943 and #87051.
1555 if cond_expr.span.desugaring_kind().is_none()
1556 && !in_external_macro(fcx.tcx.sess, cond_expr.span)
1559 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar)
1562 err.span_label(cond_expr.span, "expected this to be `()`");
1563 if expr.can_have_side_effects() {
1564 fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1568 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1570 fcx.get_fn_decl(parent_id)
1573 if let Some((fn_decl, can_suggest)) = fn_decl {
1574 if expression.is_none() {
1575 pointing_at_return_type |= fcx.suggest_missing_return_type(
1581 fcx.tcx.hir().get_parent_item(id),
1584 if !pointing_at_return_type {
1585 fn_output = Some(&fn_decl.output); // `impl Trait` return type
1589 let parent_id = fcx.tcx.hir().get_parent_item(id);
1590 let parent_item = fcx.tcx.hir().get(parent_id);
1592 if let (Some((expr, _)), Some((fn_decl, _, _))) =
1593 (expression, fcx.get_node_fn_decl(parent_item))
1595 fcx.suggest_missing_break_or_return_expr(
1596 &mut err, expr, fn_decl, expected, found, id, parent_id,
1600 if let (Some(sp), Some(fn_output)) = (fcx.ret_coercion_span.get(), fn_output) {
1601 self.add_impl_trait_explanation(&mut err, cause, fcx, expected, sp, fn_output);
1606 fn add_impl_trait_explanation<'a>(
1608 err: &mut DiagnosticBuilder<'a>,
1609 cause: &ObligationCause<'tcx>,
1610 fcx: &FnCtxt<'a, 'tcx>,
1613 fn_output: &hir::FnRetTy<'_>,
1615 let return_sp = fn_output.span();
1616 err.span_label(return_sp, "expected because this return type...");
1619 format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1621 let impl_trait_msg = "for information on `impl Trait`, see \
1622 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1623 #returning-types-that-implement-traits>";
1624 let trait_obj_msg = "for information on trait objects, see \
1625 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1626 #using-trait-objects-that-allow-for-values-of-different-types>";
1627 err.note("to return `impl Trait`, all returned values must be of the same type");
1628 err.note(impl_trait_msg);
1633 .span_to_snippet(return_sp)
1634 .unwrap_or_else(|_| "dyn Trait".to_string());
1635 let mut snippet_iter = snippet.split_whitespace();
1636 let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1637 // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1638 let mut is_object_safe = false;
1639 if let hir::FnRetTy::Return(ty) = fn_output {
1640 // Get the return type.
1641 if let hir::TyKind::OpaqueDef(..) = ty.kind {
1642 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1643 // Get the `impl Trait`'s `DefId`.
1644 if let ty::Opaque(def_id, _) = ty.kind() {
1645 let hir_id = fcx.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1646 // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1647 // get the `Trait`'s `DefId`.
1648 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1649 fcx.tcx.hir().expect_item(hir_id).kind
1651 // Are of this `impl Trait`'s traits object safe?
1652 is_object_safe = bounds.iter().all(|bound| {
1655 .and_then(|t| t.trait_def_id())
1656 .map_or(false, |def_id| {
1657 fcx.tcx.object_safety_violations(def_id).is_empty()
1666 err.multipart_suggestion(
1667 "you could change the return type to be a boxed trait object",
1669 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
1670 (return_sp.shrink_to_hi(), ">".to_string()),
1672 Applicability::MachineApplicable,
1674 let sugg = vec![sp, cause.span]
1678 (sp.shrink_to_lo(), "Box::new(".to_string()),
1679 (sp.shrink_to_hi(), ")".to_string()),
1683 .collect::<Vec<_>>();
1684 err.multipart_suggestion(
1685 "if you change the return type to expect trait objects, box the returned \
1688 Applicability::MaybeIncorrect,
1692 "if the trait `{}` were object safe, you could return a boxed trait object",
1696 err.note(trait_obj_msg);
1698 err.help("you could instead create a new `enum` with a variant for each returned type");
1701 fn is_return_ty_unsized(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
1702 if let Some((fn_decl, _)) = fcx.get_fn_decl(blk_id) {
1703 if let hir::FnRetTy::Return(ty) = fn_decl.output {
1704 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1705 if let ty::Dynamic(..) = ty.kind() {
1713 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1714 if let Some(final_ty) = self.final_ty {
1717 // If we only had inputs that were of type `!` (or no
1718 // inputs at all), then the final type is `!`.
1719 assert_eq!(self.pushed, 0);
1725 /// Something that can be converted into an expression to which we can
1726 /// apply a coercion.
1727 pub trait AsCoercionSite {
1728 fn as_coercion_site(&self) -> &hir::Expr<'_>;
1731 impl AsCoercionSite for hir::Expr<'_> {
1732 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1737 impl<'a, T> AsCoercionSite for &'a T
1741 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1742 (**self).as_coercion_site()
1746 impl AsCoercionSite for ! {
1747 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1752 impl AsCoercionSite for hir::Arm<'_> {
1753 fn as_coercion_site(&self) -> &hir::Expr<'_> {