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 return success(simple(Adjust::NeverToAny)(b), b, vec![]);
165 // Coercing *from* an unresolved inference variable means that
166 // we have no information about the source type. This will always
167 // ultimately fall back to some form of subtyping.
169 return self.coerce_from_inference_variable(a, b, identity);
172 // Consider coercing the subtype to a DST
174 // NOTE: this is wrapped in a `commit_if_ok` because it creates
175 // a "spurious" type variable, and we don't want to have that
176 // type variable in memory if the coercion fails.
177 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
180 debug!("coerce: unsize successful");
183 Err(TypeError::ObjectUnsafeCoercion(did)) => {
184 debug!("coerce: unsize not object safe");
185 return Err(TypeError::ObjectUnsafeCoercion(did));
189 debug!("coerce: unsize failed");
191 // Examine the supertype and consider auto-borrowing.
193 ty::RawPtr(mt_b) => {
194 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
196 ty::Ref(r_b, _, mutbl_b) => {
197 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
204 // Function items are coercible to any closure
205 // type; function pointers are not (that would
206 // require double indirection).
207 // Additionally, we permit coercion of function
208 // items to drop the unsafe qualifier.
209 self.coerce_from_fn_item(a, b)
212 // We permit coercion of fn pointers to drop the
214 self.coerce_from_fn_pointer(a, a_f, b)
216 ty::Closure(closure_def_id_a, substs_a) => {
217 // Non-capturing closures are coercible to
218 // function pointers or unsafe function pointers.
219 // It cannot convert closures that require unsafe.
220 self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b)
223 // Otherwise, just use unification rules.
224 self.unify_and(a, b, identity)
229 /// Coercing *from* an inference variable. In this case, we have no information
230 /// about the source type, so we can't really do a true coercion and we always
231 /// fall back to subtyping (`unify_and`).
232 fn coerce_from_inference_variable(
236 make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
237 ) -> CoerceResult<'tcx> {
238 debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
239 assert!(a.is_ty_var() && self.infcx.shallow_resolve(a) == a);
240 assert!(self.infcx.shallow_resolve(b) == b);
243 // Two unresolved type variables: create a `Coerce` predicate.
244 let target_ty = if self.use_lub {
245 self.infcx.next_ty_var(TypeVariableOrigin {
246 kind: TypeVariableOriginKind::LatticeVariable,
247 span: self.cause.span,
253 let mut obligations = Vec::with_capacity(2);
254 for &source_ty in &[a, b] {
255 if source_ty != target_ty {
256 obligations.push(Obligation::new(
259 ty::PredicateKind::Coerce(ty::CoercePredicate {
263 .to_predicate(self.tcx()),
269 "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
270 target_ty, obligations
272 let adjustments = make_adjustments(target_ty);
273 InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations })
275 // One unresolved type variable: just apply subtyping, we may be able
276 // to do something useful.
277 self.unify_and(a, b, make_adjustments)
281 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
282 /// To match `A` with `B`, autoderef will be performed,
283 /// calling `deref`/`deref_mut` where necessary.
284 fn coerce_borrowed_pointer(
288 r_b: ty::Region<'tcx>,
289 mutbl_b: hir::Mutability,
290 ) -> CoerceResult<'tcx> {
291 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
293 // If we have a parameter of type `&M T_a` and the value
294 // provided is `expr`, we will be adding an implicit borrow,
295 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
296 // to type check, we will construct the type that `&M*expr` would
299 let (r_a, mt_a) = match *a.kind() {
300 ty::Ref(r_a, ty, mutbl) => {
301 let mt_a = ty::TypeAndMut { ty, mutbl };
302 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
305 _ => return self.unify_and(a, b, identity),
308 let span = self.cause.span;
310 let mut first_error = None;
311 let mut r_borrow_var = None;
312 let mut autoderef = self.autoderef(span, a);
313 let mut found = None;
315 for (referent_ty, autoderefs) in autoderef.by_ref() {
317 // Don't let this pass, otherwise it would cause
318 // &T to autoref to &&T.
322 // At this point, we have deref'd `a` to `referent_ty`. So
323 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
324 // In the autoderef loop for `&'a mut Vec<T>`, we would get
327 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
328 // - `Vec<T>` -- 1 deref
329 // - `[T]` -- 2 deref
331 // At each point after the first callback, we want to
332 // check to see whether this would match out target type
333 // (`&'b mut [T]`) if we autoref'd it. We can't just
334 // compare the referent types, though, because we still
335 // have to consider the mutability. E.g., in the case
336 // we've been considering, we have an `&mut` reference, so
337 // the `T` in `[T]` needs to be unified with equality.
339 // Therefore, we construct reference types reflecting what
340 // the types will be after we do the final auto-ref and
341 // compare those. Note that this means we use the target
342 // mutability [1], since it may be that we are coercing
343 // from `&mut T` to `&U`.
345 // One fine point concerns the region that we use. We
346 // choose the region such that the region of the final
347 // type that results from `unify` will be the region we
348 // want for the autoref:
350 // - if in sub mode, that means we want to use `'b` (the
351 // region from the target reference) for both
352 // pointers [2]. This is because sub mode (somewhat
353 // arbitrarily) returns the subtype region. In the case
354 // where we are coercing to a target type, we know we
355 // want to use that target type region (`'b`) because --
356 // for the program to type-check -- it must be the
357 // smaller of the two.
358 // - One fine point. It may be surprising that we can
359 // use `'b` without relating `'a` and `'b`. The reason
360 // that this is ok is that what we produce is
361 // effectively a `&'b *x` expression (if you could
362 // annotate the region of a borrow), and regionck has
363 // code that adds edges from the region of a borrow
364 // (`'b`, here) into the regions in the borrowed
365 // expression (`*x`, here). (Search for "link".)
366 // - if in lub mode, things can get fairly complicated. The
367 // easiest thing is just to make a fresh
368 // region variable [4], which effectively means we defer
369 // the decision to region inference (and regionck, which will add
370 // some more edges to this variable). However, this can wind up
371 // creating a crippling number of variables in some cases --
372 // e.g., #32278 -- so we optimize one particular case [3].
373 // Let me try to explain with some examples:
374 // - The "running example" above represents the simple case,
375 // where we have one `&` reference at the outer level and
376 // ownership all the rest of the way down. In this case,
377 // we want `LUB('a, 'b)` as the resulting region.
378 // - However, if there are nested borrows, that region is
379 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
380 // `&'b T`. In this case, `'a` is actually irrelevant.
381 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
382 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
383 // (The errors actually show up in borrowck, typically, because
384 // this extra edge causes the region `'a` to be inferred to something
385 // too big, which then results in borrowck errors.)
386 // - We could track the innermost shared reference, but there is already
387 // code in regionck that has the job of creating links between
388 // the region of a borrow and the regions in the thing being
389 // borrowed (here, `'a` and `'x`), and it knows how to handle
390 // all the various cases. So instead we just make a region variable
391 // and let regionck figure it out.
392 let r = if !self.use_lub {
394 } else if autoderefs == 1 {
397 if r_borrow_var.is_none() {
398 // create var lazily, at most once
399 let coercion = Coercion(span);
400 let r = self.next_region_var(coercion);
401 r_borrow_var = Some(r); // [4] above
403 r_borrow_var.unwrap()
405 let derefd_ty_a = self.tcx.mk_ref(
409 mutbl: mutbl_b, // [1] above
412 match self.unify(derefd_ty_a, b) {
418 if first_error.is_none() {
419 first_error = Some(err);
425 // Extract type or return an error. We return the first error
426 // we got, which should be from relating the "base" type
427 // (e.g., in example above, the failure from relating `Vec<T>`
428 // to the target type), since that should be the least
430 let InferOk { value: ty, mut obligations } = match found {
433 let err = first_error.expect("coerce_borrowed_pointer had no error");
434 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
439 if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 {
440 // As a special case, if we would produce `&'a *x`, that's
441 // a total no-op. We end up with the type `&'a T` just as
442 // we started with. In that case, just skip it
443 // altogether. This is just an optimization.
445 // Note that for `&mut`, we DO want to reborrow --
446 // otherwise, this would be a move, which might be an
447 // error. For example `foo(self.x)` where `self` and
448 // `self.x` both have `&mut `type would be a move of
449 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
450 // which is a borrow.
451 assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U
452 return success(vec![], ty, obligations);
455 let InferOk { value: mut adjustments, obligations: o } =
456 self.adjust_steps_as_infer_ok(&autoderef);
457 obligations.extend(o);
458 obligations.extend(autoderef.into_obligations());
460 // Now apply the autoref. We have to extract the region out of
461 // the final ref type we got.
462 let r_borrow = match ty.kind() {
463 ty::Ref(r_borrow, _, _) => r_borrow,
464 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
466 let mutbl = match mutbl_b {
467 hir::Mutability::Not => AutoBorrowMutability::Not,
468 hir::Mutability::Mut => {
469 AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase }
472 adjustments.push(Adjustment {
473 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
477 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
479 success(adjustments, ty, obligations)
482 // &[T; n] or &mut [T; n] -> &[T]
483 // or &mut [T; n] -> &mut [T]
484 // or &Concrete -> &Trait, etc.
485 fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> {
486 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
488 source = self.shallow_resolve(source);
489 target = self.shallow_resolve(target);
490 debug!("coerce_unsized: resolved source={:?} target={:?}", source, target);
492 // These 'if' statements require some explanation.
493 // The `CoerceUnsized` trait is special - it is only
494 // possible to write `impl CoerceUnsized<B> for A` where
495 // A and B have 'matching' fields. This rules out the following
496 // two types of blanket impls:
498 // `impl<T> CoerceUnsized<T> for SomeType`
499 // `impl<T> CoerceUnsized<SomeType> for T`
501 // Both of these trigger a special `CoerceUnsized`-related error (E0376)
503 // We can take advantage of this fact to avoid performing unnecessary work.
504 // If either `source` or `target` is a type variable, then any applicable impl
505 // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
506 // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
509 // However, these are exactly the kinds of impls which are forbidden by
510 // the compiler! Therefore, we can be sure that coercion will always fail
511 // when either the source or target type is a type variable. This allows us
512 // to skip performing any trait selection, and immediately bail out.
513 if source.is_ty_var() {
514 debug!("coerce_unsized: source is a TyVar, bailing out");
515 return Err(TypeError::Mismatch);
517 if target.is_ty_var() {
518 debug!("coerce_unsized: target is a TyVar, bailing out");
519 return Err(TypeError::Mismatch);
523 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
524 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
527 debug!("missing Unsize or CoerceUnsized traits");
528 return Err(TypeError::Mismatch);
531 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
532 // a DST unless we have to. This currently comes out in the wash since
533 // we can't unify [T] with U. But to properly support DST, we need to allow
534 // that, at which point we will need extra checks on the target here.
536 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
537 let reborrow = match (source.kind(), target.kind()) {
538 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
539 coerce_mutbls(mutbl_a, mutbl_b)?;
541 let coercion = Coercion(self.cause.span);
542 let r_borrow = self.next_region_var(coercion);
543 let mutbl = match mutbl_b {
544 hir::Mutability::Not => AutoBorrowMutability::Not,
545 hir::Mutability::Mut => AutoBorrowMutability::Mut {
546 // We don't allow two-phase borrows here, at least for initial
547 // implementation. If it happens that this coercion is a function argument,
548 // the reborrow in coerce_borrowed_ptr will pick it up.
549 allow_two_phase_borrow: AllowTwoPhase::No,
553 Adjustment { kind: Adjust::Deref(None), target: ty_a },
555 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
558 .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }),
562 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
563 coerce_mutbls(mt_a, mt_b)?;
566 Adjustment { kind: Adjust::Deref(None), target: ty_a },
568 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
569 target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
575 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
577 // Setup either a subtyping or a LUB relationship between
578 // the `CoerceUnsized` target type and the expected type.
579 // We only have the latter, so we use an inference variable
580 // for the former and let type inference do the rest.
581 let origin = TypeVariableOrigin {
582 kind: TypeVariableOriginKind::MiscVariable,
583 span: self.cause.span,
585 let coerce_target = self.next_ty_var(origin);
586 let mut coercion = self.unify_and(coerce_target, target, |target| {
587 let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target };
589 None => vec![unsize],
590 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
594 let mut selcx = traits::SelectionContext::new(self);
596 // Create an obligation for `Source: CoerceUnsized<Target>`.
597 let cause = ObligationCause::new(
600 ObligationCauseCode::Coercion { source, target },
603 // Use a FIFO queue for this custom fulfillment procedure.
605 // A Vec (or SmallVec) is not a natural choice for a queue. However,
606 // this code path is hot, and this queue usually has a max length of 1
607 // and almost never more than 3. By using a SmallVec we avoid an
608 // allocation, at the (very small) cost of (occasionally) having to
609 // shift subsequent elements down when removing the front element.
610 let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def(
617 &[coerce_target.into()]
620 let mut has_unsized_tuple_coercion = false;
621 let mut has_trait_upcasting_coercion = false;
623 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
624 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
625 // inference might unify those two inner type variables later.
626 let traits = [coerce_unsized_did, unsize_did];
627 while !queue.is_empty() {
628 let obligation = queue.remove(0);
629 debug!("coerce_unsized resolve step: {:?}", obligation);
630 let bound_predicate = obligation.predicate.kind();
631 let trait_pred = match bound_predicate.skip_binder() {
632 ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => {
633 if unsize_did == trait_pred.def_id() {
634 let self_ty = trait_pred.self_ty();
635 let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
636 if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) =
637 (self_ty.kind(), unsize_ty.kind())
639 if data_a.principal_def_id() != data_b.principal_def_id() {
640 debug!("coerce_unsized: found trait upcasting coercion");
641 has_trait_upcasting_coercion = true;
644 if let ty::Tuple(..) = unsize_ty.kind() {
645 debug!("coerce_unsized: found unsized tuple coercion");
646 has_unsized_tuple_coercion = true;
649 bound_predicate.rebind(trait_pred)
652 coercion.obligations.push(obligation);
656 match selcx.select(&obligation.with(trait_pred)) {
657 // Uncertain or unimplemented.
659 if trait_pred.def_id() == unsize_did {
660 let trait_pred = self.resolve_vars_if_possible(trait_pred);
661 let self_ty = trait_pred.skip_binder().self_ty();
662 let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty();
663 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
664 match (&self_ty.kind(), &unsize_ty.kind()) {
665 (ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
666 if self.type_var_is_sized(*v) =>
668 debug!("coerce_unsized: have sized infer {:?}", v);
669 coercion.obligations.push(obligation);
670 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
674 // Some other case for `$0: Unsize<Something>`. Note that we
675 // hit this case even if `Something` is a sized type, so just
676 // don't do the coercion.
677 debug!("coerce_unsized: ambiguous unsize");
678 return Err(TypeError::Mismatch);
682 debug!("coerce_unsized: early return - ambiguous");
683 return Err(TypeError::Mismatch);
686 Err(traits::Unimplemented) => {
687 debug!("coerce_unsized: early return - can't prove obligation");
688 return Err(TypeError::Mismatch);
691 // Object safety violations or miscellaneous.
693 self.report_selection_error(obligation.clone(), &obligation, &err, false);
694 // Treat this like an obligation and follow through
695 // with the unsizing - the lack of a coercion should
696 // be silent, as it causes a type mismatch later.
699 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
703 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
705 &self.tcx.sess.parse_sess,
706 sym::unsized_tuple_coercion,
708 "unsized tuple coercion is not stable enough for use and is subject to change",
713 if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting {
715 &self.tcx.sess.parse_sess,
716 sym::trait_upcasting,
718 "trait upcasting coercion is experimental",
726 fn coerce_from_safe_fn<F, G>(
729 fn_ty_a: ty::PolyFnSig<'tcx>,
733 ) -> CoerceResult<'tcx>
735 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
736 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
738 if let ty::FnPtr(fn_ty_b) = b.kind() {
739 if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
740 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
742 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
743 return self.unify_and(unsafe_a, b, to_unsafe);
746 self.unify_and(a, b, normal)
749 fn coerce_from_fn_pointer(
752 fn_ty_a: ty::PolyFnSig<'tcx>,
754 ) -> CoerceResult<'tcx> {
755 //! Attempts to coerce from the type of a Rust function item
756 //! into a closure or a `proc`.
759 let b = self.shallow_resolve(b);
760 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
762 self.coerce_from_safe_fn(
766 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
771 fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
772 //! Attempts to coerce from the type of a Rust function item
773 //! into a closure or a `proc`.
775 let b = self.shallow_resolve(b);
776 let InferOk { value: b, mut obligations } =
777 self.normalize_associated_types_in_as_infer_ok(self.cause.span, b);
778 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
781 ty::FnPtr(b_sig) => {
782 let a_sig = a.fn_sig(self.tcx);
783 // Intrinsics are not coercible to function pointers
784 if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic {
785 return Err(TypeError::IntrinsicCast);
788 // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
789 if let ty::FnDef(def_id, _) = *a.kind() {
790 if b_sig.unsafety() == hir::Unsafety::Normal
791 && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
793 return Err(TypeError::TargetFeatureCast(def_id));
797 let InferOk { value: a_sig, obligations: o1 } =
798 self.normalize_associated_types_in_as_infer_ok(self.cause.span, a_sig);
799 obligations.extend(o1);
801 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
802 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
809 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
810 target: a_fn_pointer,
813 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
818 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
821 obligations.extend(o2);
822 Ok(InferOk { value, obligations })
824 _ => self.unify_and(a, b, identity),
828 fn coerce_closure_to_fn(
831 closure_def_id_a: DefId,
832 substs_a: SubstsRef<'tcx>,
834 ) -> CoerceResult<'tcx> {
835 //! Attempts to coerce from the type of a non-capturing closure
836 //! into a function pointer.
839 let b = self.shallow_resolve(b);
842 // At this point we haven't done capture analysis, which means
843 // that the ClosureSubsts just contains an inference variable instead
844 // of tuple of captured types.
846 // All we care here is if any variable is being captured and not the exact paths,
847 // so we check `upvars_mentioned` for root variables being captured.
851 .upvars_mentioned(closure_def_id_a.expect_local())
852 .map_or(true, |u| u.is_empty()) =>
854 // We coerce the closure, which has fn type
855 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
857 // `fn(arg0,arg1,...) -> _`
859 // `unsafe fn(arg0,arg1,...) -> _`
860 let closure_sig = substs_a.as_closure().sig();
861 let unsafety = fn_ty.unsafety();
863 self.tcx.mk_fn_ptr(self.tcx.signature_unclosure(closure_sig, unsafety));
864 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
868 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
871 _ => self.unify_and(a, b, identity),
875 fn coerce_unsafe_ptr(
879 mutbl_b: hir::Mutability,
880 ) -> CoerceResult<'tcx> {
881 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
883 let (is_ref, mt_a) = match *a.kind() {
884 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
885 ty::RawPtr(mt) => (false, mt),
886 _ => return self.unify_and(a, b, identity),
888 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
890 // Check that the types which they point at are compatible.
891 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
892 // Although references and unsafe ptrs have the same
893 // representation, we still register an Adjust::DerefRef so that
894 // regionck knows that the region for `a` must be valid here.
896 self.unify_and(a_unsafe, b, |target| {
898 Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
899 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
902 } else if mt_a.mutbl != mutbl_b {
903 self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
905 self.unify_and(a_unsafe, b, identity)
910 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
911 /// Attempt to coerce an expression to a type, and return the
912 /// adjusted type of the expression, if successful.
913 /// Adjustments are only recorded if the coercion succeeded.
914 /// The expressions *must not* have any pre-existing adjustments.
917 expr: &hir::Expr<'_>,
920 allow_two_phase: AllowTwoPhase,
921 ) -> RelateResult<'tcx, Ty<'tcx>> {
922 let source = self.resolve_vars_with_obligations(expr_ty);
923 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
925 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
926 let coerce = Coerce::new(self, cause, allow_two_phase);
927 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
929 let (adjustments, _) = self.register_infer_ok_obligations(ok);
930 self.apply_adjustments(expr, adjustments);
931 Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target })
934 /// Same as `try_coerce()`, but without side-effects.
935 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
936 let source = self.resolve_vars_with_obligations(expr_ty);
937 debug!("coercion::can({:?} -> {:?})", source, target);
939 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
940 // We don't ever need two-phase here since we throw out the result of the coercion
941 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
942 self.probe(|_| coerce.coerce(source, target)).is_ok()
945 /// Given a type and a target type, this function will calculate and return
946 /// how many dereference steps needed to achieve `expr_ty <: target`. If
947 /// it's not possible, return `None`.
948 pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
949 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
950 // We don't ever need two-phase here since we throw out the result of the coercion
951 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
953 .autoderef(rustc_span::DUMMY_SP, expr_ty)
954 .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
957 /// Given some expressions, their known unified type and another expression,
958 /// tries to unify the types, potentially inserting coercions on any of the
959 /// provided expressions and returns their LUB (aka "common supertype").
961 /// This is really an internal helper. From outside the coercion
962 /// module, you should instantiate a `CoerceMany` instance.
963 fn try_find_coercion_lub<E>(
965 cause: &ObligationCause<'tcx>,
970 ) -> RelateResult<'tcx, Ty<'tcx>>
974 let prev_ty = self.resolve_vars_with_obligations(prev_ty);
975 let new_ty = self.resolve_vars_with_obligations(new_ty);
977 "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
983 // The following check fixes #88097, where the compiler erroneously
984 // attempted to coerce a closure type to itself via a function pointer.
985 if prev_ty == new_ty {
989 // Special-case that coercion alone cannot handle:
990 // Function items or non-capturing closures of differing IDs or InternalSubsts.
991 let (a_sig, b_sig) = {
992 let is_capturing_closure = |ty| {
993 if let &ty::Closure(closure_def_id, _substs) = ty {
994 self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
999 if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) {
1002 match (prev_ty.kind(), new_ty.kind()) {
1003 (ty::FnDef(..), ty::FnDef(..)) => {
1004 // Don't reify if the function types have a LUB, i.e., they
1005 // are the same function and their parameters have a LUB.
1007 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1009 // We have a LUB of prev_ty and new_ty, just return it.
1010 Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1012 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
1016 (ty::Closure(_, substs), ty::FnDef(..)) => {
1017 let b_sig = new_ty.fn_sig(self.tcx);
1020 .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
1021 (Some(a_sig), Some(b_sig))
1023 (ty::FnDef(..), ty::Closure(_, substs)) => {
1024 let a_sig = prev_ty.fn_sig(self.tcx);
1027 .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
1028 (Some(a_sig), Some(b_sig))
1030 (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => (
1031 Some(self.tcx.signature_unclosure(
1032 substs_a.as_closure().sig(),
1033 hir::Unsafety::Normal,
1035 Some(self.tcx.signature_unclosure(
1036 substs_b.as_closure().sig(),
1037 hir::Unsafety::Normal,
1044 if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
1045 // Intrinsics are not coercible to function pointers.
1046 if a_sig.abi() == Abi::RustIntrinsic
1047 || a_sig.abi() == Abi::PlatformIntrinsic
1048 || b_sig.abi() == Abi::RustIntrinsic
1049 || b_sig.abi() == Abi::PlatformIntrinsic
1051 return Err(TypeError::IntrinsicCast);
1053 // The signature must match.
1054 let a_sig = self.normalize_associated_types_in(new.span, a_sig);
1055 let b_sig = self.normalize_associated_types_in(new.span, b_sig);
1057 .at(cause, self.param_env)
1058 .trace(prev_ty, new_ty)
1060 .map(|ok| self.register_infer_ok_obligations(ok))?;
1062 // Reify both sides and return the reified fn pointer type.
1063 let fn_ptr = self.tcx.mk_fn_ptr(sig);
1064 let prev_adjustment = match prev_ty.kind() {
1065 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.unsafety())),
1066 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1067 _ => unreachable!(),
1069 let next_adjustment = match new_ty.kind() {
1070 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.unsafety())),
1071 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1072 _ => unreachable!(),
1074 for expr in exprs.iter().map(|e| e.as_coercion_site()) {
1075 self.apply_adjustments(
1077 vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1080 self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1084 // Configure a Coerce instance to compute the LUB.
1085 // We don't allow two-phase borrows on any autorefs this creates since we
1086 // probably aren't processing function arguments here and even if we were,
1087 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1089 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
1090 coerce.use_lub = true;
1092 // First try to coerce the new expression to the type of the previous ones,
1093 // but only if the new expression has no coercion already applied to it.
1094 let mut first_error = None;
1095 if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1096 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1099 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1100 self.apply_adjustments(new, adjustments);
1102 "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}",
1107 Err(e) => first_error = Some(e),
1111 // Then try to coerce the previous expressions to the type of the new one.
1112 // This requires ensuring there are no coercions applied to *any* of the
1113 // previous expressions, other than noop reborrows (ignoring lifetimes).
1115 let expr = expr.as_coercion_site();
1116 let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
1117 &[Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }] =>
1119 match *self.node_ty(expr.hir_id).kind() {
1120 ty::Ref(_, _, mt_orig) => {
1121 let mutbl_adj: hir::Mutability = mutbl_adj.into();
1122 // Reborrow that we can safely ignore, because
1123 // the next adjustment can only be a Deref
1124 // which will be merged into it.
1125 mutbl_adj == mt_orig
1130 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1136 "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1141 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1142 .map(|ok| self.register_infer_ok_obligations(ok));
1146 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
1148 // Avoid giving strange errors on failed attempts.
1149 if let Some(e) = first_error {
1152 self.commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
1153 .map(|ok| self.register_infer_ok_obligations(ok))
1158 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?}",
1161 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1163 let expr = expr.as_coercion_site();
1164 self.apply_adjustments(expr, adjustments.clone());
1172 /// CoerceMany encapsulates the pattern you should use when you have
1173 /// many expressions that are all getting coerced to a common
1174 /// type. This arises, for example, when you have a match (the result
1175 /// of each arm is coerced to a common type). It also arises in less
1176 /// obvious places, such as when you have many `break foo` expressions
1177 /// that target the same loop, or the various `return` expressions in
1180 /// The basic protocol is as follows:
1182 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1183 /// This will also serve as the "starting LUB". The expectation is
1184 /// that this type is something which all of the expressions *must*
1185 /// be coercible to. Use a fresh type variable if needed.
1186 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
1187 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1188 /// unit. This happens for example if you have a `break` with no expression,
1189 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1190 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1191 /// from you so that you don't have to worry your pretty head about it.
1192 /// But if an error is reported, the final type will be `err`.
1193 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1194 /// previously coerced expressions.
1195 /// - When all done, invoke `complete()`. This will return the LUB of
1196 /// all your expressions.
1197 /// - WARNING: I don't believe this final type is guaranteed to be
1198 /// related to your initial `expected_ty` in any particular way,
1199 /// although it will typically be a subtype, so you should check it.
1200 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1201 /// previously coerced expressions.
1206 /// let mut coerce = CoerceMany::new(expected_ty);
1207 /// for expr in exprs {
1208 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1209 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1211 /// let final_ty = coerce.complete(fcx);
1213 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1214 expected_ty: Ty<'tcx>,
1215 final_ty: Option<Ty<'tcx>>,
1216 expressions: Expressions<'tcx, 'exprs, E>,
1220 /// The type of a `CoerceMany` that is storing up the expressions into
1221 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1222 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1224 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1225 Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1226 UpFront(&'exprs [E]),
1229 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1230 /// The usual case; collect the set of expressions dynamically.
1231 /// If the full set of coercion sites is known before hand,
1232 /// consider `with_coercion_sites()` instead to avoid allocation.
1233 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1234 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1237 /// As an optimization, you can create a `CoerceMany` with a
1238 /// pre-existing slice of expressions. In this case, you are
1239 /// expected to pass each element in the slice to `coerce(...)` in
1240 /// order. This is used with arrays in particular to avoid
1241 /// needlessly cloning the slice.
1242 pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1243 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1246 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1247 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1250 /// Returns the "expected type" with which this coercion was
1251 /// constructed. This represents the "downward propagated" type
1252 /// that was given to us at the start of typing whatever construct
1253 /// we are typing (e.g., the match expression).
1255 /// Typically, this is used as the expected type when
1256 /// type-checking each of the alternative expressions whose types
1257 /// we are trying to merge.
1258 pub fn expected_ty(&self) -> Ty<'tcx> {
1262 /// Returns the current "merged type", representing our best-guess
1263 /// at the LUB of the expressions we've seen so far (if any). This
1264 /// isn't *final* until you call `self.final()`, which will return
1265 /// the merged type.
1266 pub fn merged_ty(&self) -> Ty<'tcx> {
1267 self.final_ty.unwrap_or(self.expected_ty)
1270 /// Indicates that the value generated by `expression`, which is
1271 /// of type `expression_ty`, is one of the possibilities that we
1272 /// could coerce from. This will record `expression`, and later
1273 /// calls to `coerce` may come back and add adjustments and things
1277 fcx: &FnCtxt<'a, 'tcx>,
1278 cause: &ObligationCause<'tcx>,
1279 expression: &'tcx hir::Expr<'tcx>,
1280 expression_ty: Ty<'tcx>,
1282 self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1285 /// Indicates that one of the inputs is a "forced unit". This
1286 /// occurs in a case like `if foo { ... };`, where the missing else
1287 /// generates a "forced unit". Another example is a `loop { break;
1288 /// }`, where the `break` has no argument expression. We treat
1289 /// these cases slightly differently for error-reporting
1290 /// purposes. Note that these tend to correspond to cases where
1291 /// the `()` expression is implicit in the source, and hence we do
1292 /// not take an expression argument.
1294 /// The `augment_error` gives you a chance to extend the error
1295 /// message, in case any results (e.g., we use this to suggest
1296 /// removing a `;`).
1297 pub fn coerce_forced_unit<'a>(
1299 fcx: &FnCtxt<'a, 'tcx>,
1300 cause: &ObligationCause<'tcx>,
1301 augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1302 label_unit_as_expected: bool,
1309 Some(augment_error),
1310 label_unit_as_expected,
1314 /// The inner coercion "engine". If `expression` is `None`, this
1315 /// is a forced-unit case, and hence `expression_ty` must be
1317 #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1318 crate fn coerce_inner<'a>(
1320 fcx: &FnCtxt<'a, 'tcx>,
1321 cause: &ObligationCause<'tcx>,
1322 expression: Option<&'tcx hir::Expr<'tcx>>,
1323 mut expression_ty: Ty<'tcx>,
1324 augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1325 label_expression_as_expected: bool,
1327 // Incorporate whatever type inference information we have
1328 // until now; in principle we might also want to process
1329 // pending obligations, but doing so should only improve
1330 // compatibility (hopefully that is true) by helping us
1331 // uncover never types better.
1332 if expression_ty.is_ty_var() {
1333 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1336 // If we see any error types, just propagate that error
1338 if expression_ty.references_error() || self.merged_ty().references_error() {
1339 self.final_ty = Some(fcx.tcx.ty_error());
1343 // Handle the actual type unification etc.
1344 let result = if let Some(expression) = expression {
1345 if self.pushed == 0 {
1346 // Special-case the first expression we are coercing.
1347 // To be honest, I'm not entirely sure why we do this.
1348 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1349 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1351 match self.expressions {
1352 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1359 Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1361 &coercion_sites[0..self.pushed],
1369 // this is a hack for cases where we default to `()` because
1370 // the expression etc has been omitted from the source. An
1371 // example is an `if let` without an else:
1373 // if let Some(x) = ... { }
1375 // we wind up with a second match arm that is like `_ =>
1376 // ()`. That is the case we are considering here. We take
1377 // a different path to get the right "expected, found"
1378 // message and so forth (and because we know that
1379 // `expression_ty` will be unit).
1381 // Another example is `break` with no argument expression.
1382 assert!(expression_ty.is_unit(), "if let hack without unit type");
1383 fcx.at(cause, fcx.param_env)
1384 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1386 fcx.register_infer_ok_obligations(infer_ok);
1393 self.final_ty = Some(v);
1394 if let Some(e) = expression {
1395 match self.expressions {
1396 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1397 Expressions::UpFront(coercion_sites) => {
1398 // if the user gave us an array to validate, check that we got
1399 // the next expression in the list, as expected
1401 coercion_sites[self.pushed].as_coercion_site().hir_id,
1409 Err(coercion_error) => {
1410 let (expected, found) = if label_expression_as_expected {
1411 // In the case where this is a "forced unit", like
1412 // `break`, we want to call the `()` "expected"
1413 // since it is implied by the syntax.
1414 // (Note: not all force-units work this way.)"
1415 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1417 // Otherwise, the "expected" type for error
1418 // reporting is the current unification type,
1419 // which is basically the LUB of the expressions
1420 // we've seen so far (combined with the expected
1422 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1426 let mut unsized_return = false;
1428 ObligationCauseCode::ReturnNoExpression => {
1429 err = struct_span_err!(
1433 "`return;` in a function whose return type is not `()`"
1435 err.span_label(cause.span, "return type is not `()`");
1437 ObligationCauseCode::BlockTailExpression(blk_id) => {
1438 let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1439 err = self.report_return_mismatched_types(
1446 expression.map(|expr| (expr, blk_id)),
1448 if !fcx.tcx.features().unsized_locals {
1449 unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1452 ObligationCauseCode::ReturnValue(id) => {
1453 err = self.report_return_mismatched_types(
1462 if !fcx.tcx.features().unsized_locals {
1463 let id = fcx.tcx.hir().get_parent_node(id);
1464 unsized_return = self.is_return_ty_unsized(fcx, id);
1468 err = fcx.report_mismatched_types(cause, expected, found, coercion_error);
1472 if let Some(augment_error) = augment_error {
1473 augment_error(&mut err);
1476 if let Some(expr) = expression {
1477 fcx.emit_coerce_suggestions(&mut err, expr, found, expected, None);
1480 // Error possibly reported in `check_assign` so avoid emitting error again.
1481 let assign_to_bool = expression
1482 // #67273: Use initial expected type as opposed to `expected`.
1483 // Otherwise we end up using prior coercions in e.g. a `match` expression:
1486 // 0 => true, // Because of this...
1487 // 1 => i = 1, // ...`expected == bool` now, but not when checking `i = 1`.
1491 .filter(|e| fcx.is_assign_to_bool(e, self.expected_ty()))
1494 err.emit_unless(assign_to_bool || unsized_return);
1496 self.final_ty = Some(fcx.tcx.ty_error());
1501 fn report_return_mismatched_types<'a>(
1503 cause: &ObligationCause<'tcx>,
1506 ty_err: TypeError<'tcx>,
1507 fcx: &FnCtxt<'a, 'tcx>,
1509 expression: Option<(&'tcx hir::Expr<'tcx>, hir::HirId)>,
1510 ) -> DiagnosticBuilder<'a> {
1511 let mut err = fcx.report_mismatched_types(cause, expected, found, ty_err);
1513 let mut pointing_at_return_type = false;
1514 let mut fn_output = None;
1516 // Verify that this is a tail expression of a function, otherwise the
1517 // label pointing out the cause for the type coercion will be wrong
1518 // as prior return coercions would not be relevant (#57664).
1519 let parent_id = fcx.tcx.hir().get_parent_node(id);
1520 let fn_decl = if let Some((expr, blk_id)) = expression {
1521 pointing_at_return_type =
1522 fcx.suggest_mismatched_types_on_tail(&mut err, expr, expected, found, blk_id);
1523 let parent = fcx.tcx.hir().get(parent_id);
1524 if let (Some(cond_expr), true, false) = (
1525 fcx.tcx.hir().get_if_cause(expr.hir_id),
1527 pointing_at_return_type,
1529 // If the block is from an external macro or try (`?`) desugaring, then
1530 // do not suggest adding a semicolon, because there's nowhere to put it.
1531 // See issues #81943 and #87051.
1532 if cond_expr.span.desugaring_kind().is_none()
1533 && !in_external_macro(fcx.tcx.sess, cond_expr.span)
1536 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar)
1539 err.span_label(cond_expr.span, "expected this to be `()`");
1540 if expr.can_have_side_effects() {
1541 fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1545 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1547 fcx.get_fn_decl(parent_id)
1550 if let Some((fn_decl, can_suggest)) = fn_decl {
1551 if expression.is_none() {
1552 pointing_at_return_type |= fcx.suggest_missing_return_type(
1558 fcx.tcx.hir().get_parent_item(id),
1561 if !pointing_at_return_type {
1562 fn_output = Some(&fn_decl.output); // `impl Trait` return type
1566 let parent_id = fcx.tcx.hir().get_parent_item(id);
1567 let parent_item = fcx.tcx.hir().get(parent_id);
1569 if let (Some((expr, _)), Some((fn_decl, _, _))) =
1570 (expression, fcx.get_node_fn_decl(parent_item))
1572 fcx.suggest_missing_break_or_return_expr(
1573 &mut err, expr, fn_decl, expected, found, id, parent_id,
1577 if let (Some(sp), Some(fn_output)) = (fcx.ret_coercion_span.get(), fn_output) {
1578 self.add_impl_trait_explanation(&mut err, cause, fcx, expected, sp, fn_output);
1583 fn add_impl_trait_explanation<'a>(
1585 err: &mut DiagnosticBuilder<'a>,
1586 cause: &ObligationCause<'tcx>,
1587 fcx: &FnCtxt<'a, 'tcx>,
1590 fn_output: &hir::FnRetTy<'_>,
1592 let return_sp = fn_output.span();
1593 err.span_label(return_sp, "expected because this return type...");
1596 format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1598 let impl_trait_msg = "for information on `impl Trait`, see \
1599 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1600 #returning-types-that-implement-traits>";
1601 let trait_obj_msg = "for information on trait objects, see \
1602 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1603 #using-trait-objects-that-allow-for-values-of-different-types>";
1604 err.note("to return `impl Trait`, all returned values must be of the same type");
1605 err.note(impl_trait_msg);
1610 .span_to_snippet(return_sp)
1611 .unwrap_or_else(|_| "dyn Trait".to_string());
1612 let mut snippet_iter = snippet.split_whitespace();
1613 let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1614 // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1615 let mut is_object_safe = false;
1616 if let hir::FnRetTy::Return(ty) = fn_output {
1617 // Get the return type.
1618 if let hir::TyKind::OpaqueDef(..) = ty.kind {
1619 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1620 // Get the `impl Trait`'s `DefId`.
1621 if let ty::Opaque(def_id, _) = ty.kind() {
1622 let hir_id = fcx.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1623 // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1624 // get the `Trait`'s `DefId`.
1625 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1626 fcx.tcx.hir().expect_item(hir_id).kind
1628 // Are of this `impl Trait`'s traits object safe?
1629 is_object_safe = bounds.iter().all(|bound| {
1632 .and_then(|t| t.trait_def_id())
1633 .map_or(false, |def_id| {
1634 fcx.tcx.object_safety_violations(def_id).is_empty()
1643 err.multipart_suggestion(
1644 "you could change the return type to be a boxed trait object",
1646 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
1647 (return_sp.shrink_to_hi(), ">".to_string()),
1649 Applicability::MachineApplicable,
1651 let sugg = vec![sp, cause.span]
1655 (sp.shrink_to_lo(), "Box::new(".to_string()),
1656 (sp.shrink_to_hi(), ")".to_string()),
1660 .collect::<Vec<_>>();
1661 err.multipart_suggestion(
1662 "if you change the return type to expect trait objects, box the returned \
1665 Applicability::MaybeIncorrect,
1669 "if the trait `{}` were object safe, you could return a boxed trait object",
1673 err.note(trait_obj_msg);
1675 err.help("you could instead create a new `enum` with a variant for each returned type");
1678 fn is_return_ty_unsized(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
1679 if let Some((fn_decl, _)) = fcx.get_fn_decl(blk_id) {
1680 if let hir::FnRetTy::Return(ty) = fn_decl.output {
1681 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(fcx, ty);
1682 if let ty::Dynamic(..) = ty.kind() {
1690 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1691 if let Some(final_ty) = self.final_ty {
1694 // If we only had inputs that were of type `!` (or no
1695 // inputs at all), then the final type is `!`.
1696 assert_eq!(self.pushed, 0);
1702 /// Something that can be converted into an expression to which we can
1703 /// apply a coercion.
1704 pub trait AsCoercionSite {
1705 fn as_coercion_site(&self) -> &hir::Expr<'_>;
1708 impl AsCoercionSite for hir::Expr<'_> {
1709 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1714 impl<'a, T> AsCoercionSite for &'a T
1718 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1719 (**self).as_coercion_site()
1723 impl AsCoercionSite for ! {
1724 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1729 impl AsCoercionSite for hir::Arm<'_> {
1730 fn as_coercion_site(&self) -> &hir::Expr<'_> {