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/const things (that is, when the expected is &T
14 //! but you have &const T or &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-reborrow-*.rs` tests for
17 //! examples of where this is useful.
21 //! When deciding what type coercions to consider, we do not attempt to
22 //! resolve any type variables we may encounter. This is because `b`
23 //! represents the expected type "as the user wrote it", meaning that if
24 //! the user defined a generic function like
26 //! fn foo<A>(a: A, b: A) { ... }
28 //! and then we wrote `foo(&1, @2)`, we will not auto-borrow
29 //! either argument. In older code we went to some lengths to
30 //! resolve the `b` variable, which could mean that we'd
31 //! auto-borrow later arguments but not earlier ones, which
32 //! seems very confusing.
36 //! However, right now, if the user manually specifies the
37 //! values for the type variables, as so:
39 //! foo::<&int>(@1, @2)
41 //! then we *will* auto-borrow, because we can't distinguish this from a
42 //! function that declared `&int`. This is inconsistent but it's easiest
43 //! at the moment. The right thing to do, I think, is to consider the
44 //! *unsubstituted* type when deciding whether to auto-borrow, but the
45 //! *substituted* type when considering the bounds and so forth. But most
46 //! of our methods don't give access to the unsubstituted type, and
47 //! rightly so because they'd be error-prone. So maybe the thing to do is
48 //! to actually determine the kind of coercions that should occur
49 //! separately and pass them in. Or maybe it's ok as is. Anyway, it's
50 //! sort of a minor point so I've opted to leave it for later -- after all,
51 //! we may want to adjust precisely when coercions occur.
53 use crate::astconv::AstConv;
54 use crate::check::{FnCtxt, Needs};
55 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
56 use rustc::infer::{Coercion, InferOk, InferResult};
57 use rustc::session::parse::feature_err;
58 use rustc::traits::object_safety_violations;
59 use rustc::traits::{self, ObligationCause, ObligationCauseCode};
60 use rustc::ty::adjustment::{
61 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast,
63 use rustc::ty::error::TypeError;
64 use rustc::ty::fold::TypeFoldable;
65 use rustc::ty::relate::RelateResult;
66 use rustc::ty::subst::SubstsRef;
67 use rustc::ty::{self, Ty, TypeAndMut};
68 use rustc_error_codes::*;
69 use rustc_errors::{struct_span_err, DiagnosticBuilder};
71 use rustc_hir::def_id::DefId;
72 use rustc_span::symbol::sym;
73 use rustc_span::{self, Span};
74 use rustc_target::spec::abi::Abi;
75 use smallvec::{smallvec, SmallVec};
78 struct Coerce<'a, 'tcx> {
79 fcx: &'a FnCtxt<'a, 'tcx>,
80 cause: ObligationCause<'tcx>,
82 /// Determines whether or not allow_two_phase_borrow is set on any
83 /// autoref adjustments we create while coercing. We don't want to
84 /// allow deref coercions to create two-phase borrows, at least initially,
85 /// but we do need two-phase borrows for function argument reborrows.
86 /// See #47489 and #48598
87 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
88 allow_two_phase: AllowTwoPhase,
91 impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
92 type Target = FnCtxt<'a, 'tcx>;
93 fn deref(&self) -> &Self::Target {
98 type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
100 fn coerce_mutbls<'tcx>(
101 from_mutbl: hir::Mutability,
102 to_mutbl: hir::Mutability,
103 ) -> RelateResult<'tcx, ()> {
104 match (from_mutbl, to_mutbl) {
105 (hir::Mutability::Mut, hir::Mutability::Mut)
106 | (hir::Mutability::Not, hir::Mutability::Not)
107 | (hir::Mutability::Mut, hir::Mutability::Not) => Ok(()),
108 (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability),
112 fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> {
116 fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>> {
117 move |target| vec![Adjustment { kind, target }]
121 adj: Vec<Adjustment<'tcx>>,
123 obligations: traits::PredicateObligations<'tcx>,
124 ) -> CoerceResult<'tcx> {
125 Ok(InferOk { value: (adj, target), obligations })
128 impl<'f, 'tcx> Coerce<'f, 'tcx> {
130 fcx: &'f FnCtxt<'f, 'tcx>,
131 cause: ObligationCause<'tcx>,
132 allow_two_phase: AllowTwoPhase,
134 Coerce { fcx, cause, allow_two_phase, use_lub: false }
137 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
138 self.commit_if_ok(|_| {
140 self.at(&self.cause, self.fcx.param_env).lub(b, a)
142 self.at(&self.cause, self.fcx.param_env)
144 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
149 /// Unify two types (using sub or lub) and produce a specific coercion.
150 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx>
152 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
155 .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations))
158 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
159 let a = self.shallow_resolve(a);
160 debug!("Coerce.tys({:?} => {:?})", a, b);
162 // Just ignore error types.
163 if a.references_error() || b.references_error() {
164 return success(vec![], self.fcx.tcx.types.err, vec![]);
168 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
169 // type variable, we want `?T` to fallback to `!` if not
170 // otherwise constrained. An example where this arises:
172 // let _: Option<?T> = Some({ return; });
174 // here, we would coerce from `!` to `?T`.
175 let b = self.shallow_resolve(b);
176 return if self.shallow_resolve(b).is_ty_var() {
177 // Micro-optimization: no need for this if `b` is
178 // already resolved in some way.
179 let diverging_ty = self.next_diverging_ty_var(TypeVariableOrigin {
180 kind: TypeVariableOriginKind::AdjustmentType,
181 span: self.cause.span,
183 self.unify_and(&b, &diverging_ty, simple(Adjust::NeverToAny))
185 success(simple(Adjust::NeverToAny)(b), b, vec![])
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 // Note: does not attempt to resolve type variables we encounter.
211 // See above for details.
213 ty::RawPtr(mt_b) => {
214 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
217 ty::Ref(r_b, ty, mutbl) => {
218 let mt_b = ty::TypeAndMut { ty, mutbl };
219 return self.coerce_borrowed_pointer(a, b, r_b, mt_b);
227 // Function items are coercible to any closure
228 // type; function pointers are not (that would
229 // require double indirection).
230 // Additionally, we permit coercion of function
231 // items to drop the unsafe qualifier.
232 self.coerce_from_fn_item(a, b)
235 // We permit coercion of fn pointers to drop the
237 self.coerce_from_fn_pointer(a, a_f, b)
239 ty::Closure(def_id_a, substs_a) => {
240 // Non-capturing closures are coercible to
241 // function pointers or unsafe function pointers.
242 // It cannot convert closures that require unsafe.
243 self.coerce_closure_to_fn(a, def_id_a, substs_a, b)
246 // Otherwise, just use unification rules.
247 self.unify_and(a, b, identity)
252 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
253 /// To match `A` with `B`, autoderef will be performed,
254 /// calling `deref`/`deref_mut` where necessary.
255 fn coerce_borrowed_pointer(
259 r_b: ty::Region<'tcx>,
260 mt_b: TypeAndMut<'tcx>,
261 ) -> CoerceResult<'tcx> {
262 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
264 // If we have a parameter of type `&M T_a` and the value
265 // provided is `expr`, we will be adding an implicit borrow,
266 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
267 // to type check, we will construct the type that `&M*expr` would
270 let (r_a, mt_a) = match a.kind {
271 ty::Ref(r_a, ty, mutbl) => {
272 let mt_a = ty::TypeAndMut { ty, mutbl };
273 coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?;
276 _ => return self.unify_and(a, b, identity),
279 let span = self.cause.span;
281 let mut first_error = None;
282 let mut r_borrow_var = None;
283 let mut autoderef = self.autoderef(span, a);
284 let mut found = None;
286 for (referent_ty, autoderefs) in autoderef.by_ref() {
288 // Don't let this pass, otherwise it would cause
289 // &T to autoref to &&T.
293 // At this point, we have deref'd `a` to `referent_ty`. So
294 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
295 // In the autoderef loop for `&'a mut Vec<T>`, we would get
298 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
299 // - `Vec<T>` -- 1 deref
300 // - `[T]` -- 2 deref
302 // At each point after the first callback, we want to
303 // check to see whether this would match out target type
304 // (`&'b mut [T]`) if we autoref'd it. We can't just
305 // compare the referent types, though, because we still
306 // have to consider the mutability. E.g., in the case
307 // we've been considering, we have an `&mut` reference, so
308 // the `T` in `[T]` needs to be unified with equality.
310 // Therefore, we construct reference types reflecting what
311 // the types will be after we do the final auto-ref and
312 // compare those. Note that this means we use the target
313 // mutability [1], since it may be that we are coercing
314 // from `&mut T` to `&U`.
316 // One fine point concerns the region that we use. We
317 // choose the region such that the region of the final
318 // type that results from `unify` will be the region we
319 // want for the autoref:
321 // - if in sub mode, that means we want to use `'b` (the
322 // region from the target reference) for both
323 // pointers [2]. This is because sub mode (somewhat
324 // arbitrarily) returns the subtype region. In the case
325 // where we are coercing to a target type, we know we
326 // want to use that target type region (`'b`) because --
327 // for the program to type-check -- it must be the
328 // smaller of the two.
329 // - One fine point. It may be surprising that we can
330 // use `'b` without relating `'a` and `'b`. The reason
331 // that this is ok is that what we produce is
332 // effectively a `&'b *x` expression (if you could
333 // annotate the region of a borrow), and regionck has
334 // code that adds edges from the region of a borrow
335 // (`'b`, here) into the regions in the borrowed
336 // expression (`*x`, here). (Search for "link".)
337 // - if in lub mode, things can get fairly complicated. The
338 // easiest thing is just to make a fresh
339 // region variable [4], which effectively means we defer
340 // the decision to region inference (and regionck, which will add
341 // some more edges to this variable). However, this can wind up
342 // creating a crippling number of variables in some cases --
343 // e.g., #32278 -- so we optimize one particular case [3].
344 // Let me try to explain with some examples:
345 // - The "running example" above represents the simple case,
346 // where we have one `&` reference at the outer level and
347 // ownership all the rest of the way down. In this case,
348 // we want `LUB('a, 'b)` as the resulting region.
349 // - However, if there are nested borrows, that region is
350 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
351 // `&'b T`. In this case, `'a` is actually irrelevant.
352 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
353 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
354 // (The errors actually show up in borrowck, typically, because
355 // this extra edge causes the region `'a` to be inferred to something
356 // too big, which then results in borrowck errors.)
357 // - We could track the innermost shared reference, but there is already
358 // code in regionck that has the job of creating links between
359 // the region of a borrow and the regions in the thing being
360 // borrowed (here, `'a` and `'x`), and it knows how to handle
361 // all the various cases. So instead we just make a region variable
362 // and let regionck figure it out.
363 let r = if !self.use_lub {
365 } else if autoderefs == 1 {
368 if r_borrow_var.is_none() {
369 // create var lazilly, at most once
370 let coercion = Coercion(span);
371 let r = self.next_region_var(coercion);
372 r_borrow_var = Some(r); // [4] above
374 r_borrow_var.unwrap()
376 let derefd_ty_a = self.tcx.mk_ref(
380 mutbl: mt_b.mutbl, // [1] above
383 match self.unify(derefd_ty_a, b) {
389 if first_error.is_none() {
390 first_error = Some(err);
396 // Extract type or return an error. We return the first error
397 // we got, which should be from relating the "base" type
398 // (e.g., in example above, the failure from relating `Vec<T>`
399 // to the target type), since that should be the least
401 let InferOk { value: ty, mut obligations } = match found {
404 let err = first_error.expect("coerce_borrowed_pointer had no error");
405 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
410 if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 {
411 // As a special case, if we would produce `&'a *x`, that's
412 // a total no-op. We end up with the type `&'a T` just as
413 // we started with. In that case, just skip it
414 // altogether. This is just an optimization.
416 // Note that for `&mut`, we DO want to reborrow --
417 // otherwise, this would be a move, which might be an
418 // error. For example `foo(self.x)` where `self` and
419 // `self.x` both have `&mut `type would be a move of
420 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
421 // which is a borrow.
422 assert_eq!(mt_b.mutbl, hir::Mutability::Not); // can only coerce &T -> &U
423 return success(vec![], ty, obligations);
426 let needs = Needs::maybe_mut_place(mt_b.mutbl);
427 let InferOk { value: mut adjustments, obligations: o } =
428 autoderef.adjust_steps_as_infer_ok(self, needs);
429 obligations.extend(o);
430 obligations.extend(autoderef.into_obligations());
432 // Now apply the autoref. We have to extract the region out of
433 // the final ref type we got.
434 let r_borrow = match ty.kind {
435 ty::Ref(r_borrow, _, _) => r_borrow,
436 _ => span_bug!(span, "expected a ref type, got {:?}", ty),
438 let mutbl = match mt_b.mutbl {
439 hir::Mutability::Not => AutoBorrowMutability::Not,
440 hir::Mutability::Mut => {
441 AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase }
444 adjustments.push(Adjustment {
445 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
449 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
451 success(adjustments, ty, obligations)
454 // &[T; n] or &mut [T; n] -> &[T]
455 // or &mut [T; n] -> &mut [T]
456 // or &Concrete -> &Trait, etc.
457 fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
458 debug!("coerce_unsized(source={:?}, target={:?})", source, target);
461 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
462 let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
465 debug!("missing Unsize or CoerceUnsized traits");
466 return Err(TypeError::Mismatch);
469 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
470 // a DST unless we have to. This currently comes out in the wash since
471 // we can't unify [T] with U. But to properly support DST, we need to allow
472 // that, at which point we will need extra checks on the target here.
474 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
475 let reborrow = match (&source.kind, &target.kind) {
476 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
477 coerce_mutbls(mutbl_a, mutbl_b)?;
479 let coercion = Coercion(self.cause.span);
480 let r_borrow = self.next_region_var(coercion);
481 let mutbl = match mutbl_b {
482 hir::Mutability::Not => AutoBorrowMutability::Not,
483 hir::Mutability::Mut => AutoBorrowMutability::Mut {
484 // We don't allow two-phase borrows here, at least for initial
485 // implementation. If it happens that this coercion is a function argument,
486 // the reborrow in coerce_borrowed_ptr will pick it up.
487 allow_two_phase_borrow: AllowTwoPhase::No,
491 Adjustment { kind: Adjust::Deref(None), target: ty_a },
493 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
496 .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }),
500 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
501 coerce_mutbls(mt_a, mt_b)?;
504 Adjustment { kind: Adjust::Deref(None), target: ty_a },
506 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
507 target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
513 let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target);
515 // Setup either a subtyping or a LUB relationship between
516 // the `CoerceUnsized` target type and the expected type.
517 // We only have the latter, so we use an inference variable
518 // for the former and let type inference do the rest.
519 let origin = TypeVariableOrigin {
520 kind: TypeVariableOriginKind::MiscVariable,
521 span: self.cause.span,
523 let coerce_target = self.next_ty_var(origin);
524 let mut coercion = self.unify_and(coerce_target, target, |target| {
525 let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target };
527 None => vec![unsize],
528 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
532 let mut selcx = traits::SelectionContext::new(self);
534 // Create an obligation for `Source: CoerceUnsized<Target>`.
535 let cause = ObligationCause::new(
538 ObligationCauseCode::Coercion { source, target },
541 // Use a FIFO queue for this custom fulfillment procedure.
543 // A Vec (or SmallVec) is not a natural choice for a queue. However,
544 // this code path is hot, and this queue usually has a max length of 1
545 // and almost never more than 3. By using a SmallVec we avoid an
546 // allocation, at the (very small) cost of (occasionally) having to
547 // shift subsequent elements down when removing the front element.
548 let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def(
555 &[coerce_target.into()]
558 let mut has_unsized_tuple_coercion = false;
560 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
561 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
562 // inference might unify those two inner type variables later.
563 let traits = [coerce_unsized_did, unsize_did];
564 while !queue.is_empty() {
565 let obligation = queue.remove(0);
566 debug!("coerce_unsized resolve step: {:?}", obligation);
567 let trait_ref = match obligation.predicate {
568 ty::Predicate::Trait(ref tr, _) if traits.contains(&tr.def_id()) => {
569 if unsize_did == tr.def_id() {
570 let sty = &tr.skip_binder().input_types().nth(1).unwrap().kind;
571 if let ty::Tuple(..) = sty {
572 debug!("coerce_unsized: found unsized tuple coercion");
573 has_unsized_tuple_coercion = true;
579 coercion.obligations.push(obligation);
583 match selcx.select(&obligation.with(trait_ref)) {
584 // Uncertain or unimplemented.
586 if trait_ref.def_id() == unsize_did {
587 let trait_ref = self.resolve_vars_if_possible(&trait_ref);
588 let self_ty = trait_ref.skip_binder().self_ty();
589 let unsize_ty = trait_ref.skip_binder().input_types().nth(1).unwrap();
590 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_ref);
591 match (&self_ty.kind, &unsize_ty.kind) {
592 (ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
593 if self.type_var_is_sized(*v) =>
595 debug!("coerce_unsized: have sized infer {:?}", v);
596 coercion.obligations.push(obligation);
597 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
601 // Some other case for `$0: Unsize<Something>`. Note that we
602 // hit this case even if `Something` is a sized type, so just
603 // don't do the coercion.
604 debug!("coerce_unsized: ambiguous unsize");
605 return Err(TypeError::Mismatch);
609 debug!("coerce_unsized: early return - ambiguous");
610 return Err(TypeError::Mismatch);
613 Err(traits::Unimplemented) => {
614 debug!("coerce_unsized: early return - can't prove obligation");
615 return Err(TypeError::Mismatch);
618 // Object safety violations or miscellaneous.
620 self.report_selection_error(&obligation, &err, false, false);
621 // Treat this like an obligation and follow through
622 // with the unsizing - the lack of a coercion should
623 // be silent, as it causes a type mismatch later.
626 Ok(Some(vtable)) => queue.extend(vtable.nested_obligations()),
630 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
632 &self.tcx.sess.parse_sess,
633 sym::unsized_tuple_coercion,
635 "unsized tuple coercion is not stable enough for use and is subject to change",
643 fn coerce_from_safe_fn<F, G>(
646 fn_ty_a: ty::PolyFnSig<'tcx>,
650 ) -> CoerceResult<'tcx>
652 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
653 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
655 if let ty::FnPtr(fn_ty_b) = b.kind {
656 if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
657 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
659 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
660 return self.unify_and(unsafe_a, b, to_unsafe);
663 self.unify_and(a, b, normal)
666 fn coerce_from_fn_pointer(
669 fn_ty_a: ty::PolyFnSig<'tcx>,
671 ) -> CoerceResult<'tcx> {
672 //! Attempts to coerce from the type of a Rust function item
673 //! into a closure or a `proc`.
676 let b = self.shallow_resolve(b);
677 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
679 self.coerce_from_safe_fn(
683 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
688 fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
689 //! Attempts to coerce from the type of a Rust function item
690 //! into a closure or a `proc`.
692 let b = self.shallow_resolve(b);
693 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
697 let a_sig = a.fn_sig(self.tcx);
698 // Intrinsics are not coercible to function pointers
699 if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic {
700 return Err(TypeError::IntrinsicCast);
702 let InferOk { value: a_sig, mut obligations } =
703 self.normalize_associated_types_in_as_infer_ok(self.cause.span, &a_sig);
705 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
706 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
713 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
714 target: a_fn_pointer,
717 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
722 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
725 obligations.extend(o2);
726 Ok(InferOk { value, obligations })
728 _ => self.unify_and(a, b, identity),
732 fn coerce_closure_to_fn(
736 substs_a: SubstsRef<'tcx>,
738 ) -> CoerceResult<'tcx> {
739 //! Attempts to coerce from the type of a non-capturing closure
740 //! into a function pointer.
743 let b = self.shallow_resolve(b);
746 ty::FnPtr(fn_ty) if self.tcx.upvars(def_id_a).map_or(true, |v| v.is_empty()) => {
747 // We coerce the closure, which has fn type
748 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
750 // `fn(arg0,arg1,...) -> _`
752 // `unsafe fn(arg0,arg1,...) -> _`
753 let sig = self.closure_sig(def_id_a, substs_a);
754 let unsafety = fn_ty.unsafety();
755 let pointer_ty = self.tcx.coerce_closure_fn_ty(sig, unsafety);
756 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
760 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
763 _ => self.unify_and(a, b, identity),
767 fn coerce_unsafe_ptr(
771 mutbl_b: hir::Mutability,
772 ) -> CoerceResult<'tcx> {
773 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
775 let (is_ref, mt_a) = match a.kind {
776 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
777 ty::RawPtr(mt) => (false, mt),
778 _ => return self.unify_and(a, b, identity),
781 // Check that the types which they point at are compatible.
782 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
783 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
784 // Although references and unsafe ptrs have the same
785 // representation, we still register an Adjust::DerefRef so that
786 // regionck knows that the region for `a` must be valid here.
788 self.unify_and(a_unsafe, b, |target| {
790 Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
791 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
794 } else if mt_a.mutbl != mutbl_b {
795 self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
797 self.unify_and(a_unsafe, b, identity)
802 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
803 /// Attempt to coerce an expression to a type, and return the
804 /// adjusted type of the expression, if successful.
805 /// Adjustments are only recorded if the coercion succeeded.
806 /// The expressions *must not* have any pre-existing adjustments.
809 expr: &hir::Expr<'_>,
812 allow_two_phase: AllowTwoPhase,
813 ) -> RelateResult<'tcx, Ty<'tcx>> {
814 let source = self.resolve_vars_with_obligations(expr_ty);
815 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
817 let cause = self.cause(expr.span, ObligationCauseCode::ExprAssignable);
818 let coerce = Coerce::new(self, cause, allow_two_phase);
819 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
821 let (adjustments, _) = self.register_infer_ok_obligations(ok);
822 self.apply_adjustments(expr, adjustments);
823 Ok(if expr_ty.references_error() { self.tcx.types.err } else { target })
826 /// Same as `try_coerce()`, but without side-effects.
827 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
828 let source = self.resolve_vars_with_obligations(expr_ty);
829 debug!("coercion::can({:?} -> {:?})", source, target);
831 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
832 // We don't ever need two-phase here since we throw out the result of the coercion
833 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
834 self.probe(|_| coerce.coerce(source, target)).is_ok()
837 /// Given some expressions, their known unified type and another expression,
838 /// tries to unify the types, potentially inserting coercions on any of the
839 /// provided expressions and returns their LUB (aka "common supertype").
841 /// This is really an internal helper. From outside the coercion
842 /// module, you should instantiate a `CoerceMany` instance.
843 fn try_find_coercion_lub<E>(
845 cause: &ObligationCause<'tcx>,
850 ) -> RelateResult<'tcx, Ty<'tcx>>
854 let prev_ty = self.resolve_vars_with_obligations(prev_ty);
855 let new_ty = self.resolve_vars_with_obligations(new_ty);
856 debug!("coercion::try_find_coercion_lub({:?}, {:?})", prev_ty, new_ty);
858 // Special-case that coercion alone cannot handle:
859 // Two function item types of differing IDs or InternalSubsts.
860 if let (&ty::FnDef(..), &ty::FnDef(..)) = (&prev_ty.kind, &new_ty.kind) {
861 // Don't reify if the function types have a LUB, i.e., they
862 // are the same function and their parameters have a LUB.
864 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
865 .map(|ok| self.register_infer_ok_obligations(ok));
868 // We have a LUB of prev_ty and new_ty, just return it.
872 // The signature must match.
873 let a_sig = prev_ty.fn_sig(self.tcx);
874 let a_sig = self.normalize_associated_types_in(new.span, &a_sig);
875 let b_sig = new_ty.fn_sig(self.tcx);
876 let b_sig = self.normalize_associated_types_in(new.span, &b_sig);
878 .at(cause, self.param_env)
879 .trace(prev_ty, new_ty)
881 .map(|ok| self.register_infer_ok_obligations(ok))?;
883 // Reify both sides and return the reified fn pointer type.
884 let fn_ptr = self.tcx.mk_fn_ptr(sig);
885 for expr in exprs.iter().map(|e| e.as_coercion_site()).chain(Some(new)) {
886 // The only adjustment that can produce an fn item is
887 // `NeverToAny`, so this should always be valid.
888 self.apply_adjustments(
891 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
899 // Configure a Coerce instance to compute the LUB.
900 // We don't allow two-phase borrows on any autorefs this creates since we
901 // probably aren't processing function arguments here and even if we were,
902 // they're going to get autorefed again anyway and we can apply 2-phase borrows
904 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
905 coerce.use_lub = true;
907 // First try to coerce the new expression to the type of the previous ones,
908 // but only if the new expression has no coercion already applied to it.
909 let mut first_error = None;
910 if !self.tables.borrow().adjustments().contains_key(new.hir_id) {
911 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
914 let (adjustments, target) = self.register_infer_ok_obligations(ok);
915 self.apply_adjustments(new, adjustments);
918 Err(e) => first_error = Some(e),
922 // Then try to coerce the previous expressions to the type of the new one.
923 // This requires ensuring there are no coercions applied to *any* of the
924 // previous expressions, other than noop reborrows (ignoring lifetimes).
926 let expr = expr.as_coercion_site();
927 let noop = match self.tables.borrow().expr_adjustments(expr) {
928 &[Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }] =>
930 match self.node_ty(expr.hir_id).kind {
931 ty::Ref(_, _, mt_orig) => {
932 let mutbl_adj: hir::Mutability = mutbl_adj.into();
933 // Reborrow that we can safely ignore, because
934 // the next adjustment can only be a Deref
935 // which will be merged into it.
941 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
947 .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
948 .map(|ok| self.register_infer_ok_obligations(ok));
952 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
954 // Avoid giving strange errors on failed attempts.
955 if let Some(e) = first_error {
958 self.commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty))
959 .map(|ok| self.register_infer_ok_obligations(ok))
963 let (adjustments, target) = self.register_infer_ok_obligations(ok);
965 let expr = expr.as_coercion_site();
966 self.apply_adjustments(expr, adjustments.clone());
974 /// CoerceMany encapsulates the pattern you should use when you have
975 /// many expressions that are all getting coerced to a common
976 /// type. This arises, for example, when you have a match (the result
977 /// of each arm is coerced to a common type). It also arises in less
978 /// obvious places, such as when you have many `break foo` expressions
979 /// that target the same loop, or the various `return` expressions in
982 /// The basic protocol is as follows:
984 /// - Instantiate the `CoerceMany` with an initial `expected_ty`.
985 /// This will also serve as the "starting LUB". The expectation is
986 /// that this type is something which all of the expressions *must*
987 /// be coercible to. Use a fresh type variable if needed.
988 /// - For each expression whose result is to be coerced, invoke `coerce()` with.
989 /// - In some cases we wish to coerce "non-expressions" whose types are implicitly
990 /// unit. This happens for example if you have a `break` with no expression,
991 /// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
992 /// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
993 /// from you so that you don't have to worry your pretty head about it.
994 /// But if an error is reported, the final type will be `err`.
995 /// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
996 /// previously coerced expressions.
997 /// - When all done, invoke `complete()`. This will return the LUB of
998 /// all your expressions.
999 /// - WARNING: I don't believe this final type is guaranteed to be
1000 /// related to your initial `expected_ty` in any particular way,
1001 /// although it will typically be a subtype, so you should check it.
1002 /// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1003 /// previously coerced expressions.
1008 /// let mut coerce = CoerceMany::new(expected_ty);
1009 /// for expr in exprs {
1010 /// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1011 /// coerce.coerce(fcx, &cause, expr, expr_ty);
1013 /// let final_ty = coerce.complete(fcx);
1015 pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
1016 expected_ty: Ty<'tcx>,
1017 final_ty: Option<Ty<'tcx>>,
1018 expressions: Expressions<'tcx, 'exprs, E>,
1022 /// The type of a `CoerceMany` that is storing up the expressions into
1023 /// a buffer. We use this in `check/mod.rs` for things like `break`.
1024 pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
1026 enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
1027 Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
1028 UpFront(&'exprs [E]),
1031 impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
1032 /// The usual case; collect the set of expressions dynamically.
1033 /// If the full set of coercion sites is known before hand,
1034 /// consider `with_coercion_sites()` instead to avoid allocation.
1035 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1036 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1039 /// As an optimization, you can create a `CoerceMany` with a
1040 /// pre-existing slice of expressions. In this case, you are
1041 /// expected to pass each element in the slice to `coerce(...)` in
1042 /// order. This is used with arrays in particular to avoid
1043 /// needlessly cloning the slice.
1044 pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
1045 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1048 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
1049 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1052 /// Returns the "expected type" with which this coercion was
1053 /// constructed. This represents the "downward propagated" type
1054 /// that was given to us at the start of typing whatever construct
1055 /// we are typing (e.g., the match expression).
1057 /// Typically, this is used as the expected type when
1058 /// type-checking each of the alternative expressions whose types
1059 /// we are trying to merge.
1060 pub fn expected_ty(&self) -> Ty<'tcx> {
1064 /// Returns the current "merged type", representing our best-guess
1065 /// at the LUB of the expressions we've seen so far (if any). This
1066 /// isn't *final* until you call `self.final()`, which will return
1067 /// the merged type.
1068 pub fn merged_ty(&self) -> Ty<'tcx> {
1069 self.final_ty.unwrap_or(self.expected_ty)
1072 /// Indicates that the value generated by `expression`, which is
1073 /// of type `expression_ty`, is one of the possibilities that we
1074 /// could coerce from. This will record `expression`, and later
1075 /// calls to `coerce` may come back and add adjustments and things
1079 fcx: &FnCtxt<'a, 'tcx>,
1080 cause: &ObligationCause<'tcx>,
1081 expression: &'tcx hir::Expr<'tcx>,
1082 expression_ty: Ty<'tcx>,
1084 self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
1087 /// Indicates that one of the inputs is a "forced unit". This
1088 /// occurs in a case like `if foo { ... };`, where the missing else
1089 /// generates a "forced unit". Another example is a `loop { break;
1090 /// }`, where the `break` has no argument expression. We treat
1091 /// these cases slightly differently for error-reporting
1092 /// purposes. Note that these tend to correspond to cases where
1093 /// the `()` expression is implicit in the source, and hence we do
1094 /// not take an expression argument.
1096 /// The `augment_error` gives you a chance to extend the error
1097 /// message, in case any results (e.g., we use this to suggest
1098 /// removing a `;`).
1099 pub fn coerce_forced_unit<'a>(
1101 fcx: &FnCtxt<'a, 'tcx>,
1102 cause: &ObligationCause<'tcx>,
1103 augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>),
1104 label_unit_as_expected: bool,
1111 Some(augment_error),
1112 label_unit_as_expected,
1116 /// The inner coercion "engine". If `expression` is `None`, this
1117 /// is a forced-unit case, and hence `expression_ty` must be
1119 fn coerce_inner<'a>(
1121 fcx: &FnCtxt<'a, 'tcx>,
1122 cause: &ObligationCause<'tcx>,
1123 expression: Option<&'tcx hir::Expr<'tcx>>,
1124 mut expression_ty: Ty<'tcx>,
1125 augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>,
1126 label_expression_as_expected: bool,
1128 // Incorporate whatever type inference information we have
1129 // until now; in principle we might also want to process
1130 // pending obligations, but doing so should only improve
1131 // compatibility (hopefully that is true) by helping us
1132 // uncover never types better.
1133 if expression_ty.is_ty_var() {
1134 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1137 // If we see any error types, just propagate that error
1139 if expression_ty.references_error() || self.merged_ty().references_error() {
1140 self.final_ty = Some(fcx.tcx.types.err);
1144 // Handle the actual type unification etc.
1145 let result = if let Some(expression) = expression {
1146 if self.pushed == 0 {
1147 // Special-case the first expression we are coercing.
1148 // To be honest, I'm not entirely sure why we do this.
1149 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1150 fcx.try_coerce(expression, expression_ty, self.expected_ty, AllowTwoPhase::No)
1152 match self.expressions {
1153 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1160 Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1162 &coercion_sites[0..self.pushed],
1170 // this is a hack for cases where we default to `()` because
1171 // the expression etc has been omitted from the source. An
1172 // example is an `if let` without an else:
1174 // if let Some(x) = ... { }
1176 // we wind up with a second match arm that is like `_ =>
1177 // ()`. That is the case we are considering here. We take
1178 // a different path to get the right "expected, found"
1179 // message and so forth (and because we know that
1180 // `expression_ty` will be unit).
1182 // Another example is `break` with no argument expression.
1183 assert!(expression_ty.is_unit(), "if let hack without unit type");
1184 fcx.at(cause, fcx.param_env)
1185 .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty())
1187 fcx.register_infer_ok_obligations(infer_ok);
1194 self.final_ty = Some(v);
1195 if let Some(e) = expression {
1196 match self.expressions {
1197 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1198 Expressions::UpFront(coercion_sites) => {
1199 // if the user gave us an array to validate, check that we got
1200 // the next expression in the list, as expected
1202 coercion_sites[self.pushed].as_coercion_site().hir_id,
1210 Err(coercion_error) => {
1211 let (expected, found) = if label_expression_as_expected {
1212 // In the case where this is a "forced unit", like
1213 // `break`, we want to call the `()` "expected"
1214 // since it is implied by the syntax.
1215 // (Note: not all force-units work this way.)"
1216 (expression_ty, self.final_ty.unwrap_or(self.expected_ty))
1218 // Otherwise, the "expected" type for error
1219 // reporting is the current unification type,
1220 // which is basically the LUB of the expressions
1221 // we've seen so far (combined with the expected
1223 (self.final_ty.unwrap_or(self.expected_ty), expression_ty)
1227 let mut unsized_return = false;
1229 ObligationCauseCode::ReturnNoExpression => {
1230 err = struct_span_err!(
1234 "`return;` in a function whose return type is not `()`"
1236 err.span_label(cause.span, "return type is not `()`");
1238 ObligationCauseCode::BlockTailExpression(blk_id) => {
1239 let parent_id = fcx.tcx.hir().get_parent_node(blk_id);
1240 err = self.report_return_mismatched_types(
1247 expression.map(|expr| (expr, blk_id)),
1249 if !fcx.tcx.features().unsized_locals {
1250 unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1253 ObligationCauseCode::ReturnValue(id) => {
1254 err = self.report_return_mismatched_types(
1263 if !fcx.tcx.features().unsized_locals {
1264 let id = fcx.tcx.hir().get_parent_node(id);
1265 unsized_return = self.is_return_ty_unsized(fcx, id);
1269 err = fcx.report_mismatched_types(cause, expected, found, coercion_error);
1273 if let Some(augment_error) = augment_error {
1274 augment_error(&mut err);
1277 if let Some(expr) = expression {
1278 fcx.emit_coerce_suggestions(&mut err, expr, found, expected);
1281 // Error possibly reported in `check_assign` so avoid emitting error again.
1282 let assign_to_bool = expression
1283 // #67273: Use initial expected type as opposed to `expected`.
1284 // Otherwise we end up using prior coercions in e.g. a `match` expression:
1287 // 0 => true, // Because of this...
1288 // 1 => i = 1, // ...`expected == bool` now, but not when checking `i = 1`.
1292 .filter(|e| fcx.is_assign_to_bool(e, self.expected_ty()))
1295 err.emit_unless(assign_to_bool || unsized_return);
1297 self.final_ty = Some(fcx.tcx.types.err);
1302 fn report_return_mismatched_types<'a>(
1304 cause: &ObligationCause<'tcx>,
1307 ty_err: TypeError<'tcx>,
1308 fcx: &FnCtxt<'a, 'tcx>,
1310 expression: Option<(&'tcx hir::Expr<'tcx>, hir::HirId)>,
1311 ) -> DiagnosticBuilder<'a> {
1312 let mut err = fcx.report_mismatched_types(cause, expected, found, ty_err);
1314 let mut pointing_at_return_type = false;
1315 let mut fn_output = None;
1317 // Verify that this is a tail expression of a function, otherwise the
1318 // label pointing out the cause for the type coercion will be wrong
1319 // as prior return coercions would not be relevant (#57664).
1320 let parent_id = fcx.tcx.hir().get_parent_node(id);
1321 let fn_decl = if let Some((expr, blk_id)) = expression {
1322 pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1323 &mut err, expr, expected, found, cause.span, blk_id,
1325 let parent = fcx.tcx.hir().get(parent_id);
1326 if let (Some(match_expr), true, false) = (
1327 fcx.tcx.hir().get_match_if_cause(expr.hir_id),
1329 pointing_at_return_type,
1331 if match_expr.span.desugaring_kind().is_none() {
1332 err.span_label(match_expr.span, "expected this to be `()`");
1333 fcx.suggest_semicolon_at_end(match_expr.span, &mut err);
1336 fcx.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
1338 fcx.get_fn_decl(parent_id)
1341 if let (Some((fn_decl, can_suggest)), _) = (fn_decl, pointing_at_return_type) {
1342 if expression.is_none() {
1343 pointing_at_return_type |= fcx.suggest_missing_return_type(
1351 if !pointing_at_return_type {
1352 fn_output = Some(&fn_decl.output); // `impl Trait` return type
1355 if let (Some(sp), Some(fn_output)) = (fcx.ret_coercion_span.borrow().as_ref(), fn_output) {
1356 self.add_impl_trait_explanation(&mut err, fcx, expected, *sp, fn_output);
1361 fn add_impl_trait_explanation<'a>(
1363 err: &mut DiagnosticBuilder<'a>,
1364 fcx: &FnCtxt<'a, 'tcx>,
1367 fn_output: &hir::FunctionRetTy<'_>,
1369 let return_sp = fn_output.span();
1370 err.span_label(return_sp, "expected because this return type...");
1373 format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1375 let impl_trait_msg = "for information on `impl Trait`, see \
1376 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1377 #returning-types-that-implement-traits>";
1378 let trait_obj_msg = "for information on trait objects, see \
1379 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1380 #using-trait-objects-that-allow-for-values-of-different-types>";
1381 err.note("to return `impl Trait`, all returned values must be of the same type");
1382 err.note(impl_trait_msg);
1387 .span_to_snippet(return_sp)
1388 .unwrap_or_else(|_| "dyn Trait".to_string());
1389 let mut snippet_iter = snippet.split_whitespace();
1390 let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1391 // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1392 let mut is_object_safe = false;
1393 if let hir::FunctionRetTy::Return(ty) = fn_output {
1394 // Get the return type.
1395 if let hir::TyKind::Def(..) = ty.kind {
1396 let ty = AstConv::ast_ty_to_ty(fcx, ty);
1397 // Get the `impl Trait`'s `DefId`.
1398 if let ty::Opaque(def_id, _) = ty.kind {
1399 let hir_id = fcx.tcx.hir().as_local_hir_id(def_id).unwrap();
1400 // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1401 // get the `Trait`'s `DefId`.
1402 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1403 fcx.tcx.hir().expect_item(hir_id).kind
1405 // Are of this `impl Trait`'s traits object safe?
1406 is_object_safe = bounds.iter().all(|bound| {
1407 bound.trait_def_id().map_or(false, |def_id| {
1408 object_safety_violations(fcx.tcx, def_id).is_empty()
1418 "you can instead return a boxed trait object using `Box<dyn {}>`",
1423 "if the trait `{}` were object safe, you could return a boxed trait object",
1427 err.note(trait_obj_msg);
1429 err.help("alternatively, create a new `enum` with a variant for each returned type");
1432 fn is_return_ty_unsized(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
1433 if let Some((fn_decl, _)) = fcx.get_fn_decl(blk_id) {
1434 if let hir::FunctionRetTy::Return(ty) = fn_decl.output {
1435 let ty = AstConv::ast_ty_to_ty(fcx, ty);
1436 if let ty::Dynamic(..) = ty.kind {
1444 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1445 if let Some(final_ty) = self.final_ty {
1448 // If we only had inputs that were of type `!` (or no
1449 // inputs at all), then the final type is `!`.
1450 assert_eq!(self.pushed, 0);
1456 /// Something that can be converted into an expression to which we can
1457 /// apply a coercion.
1458 pub trait AsCoercionSite {
1459 fn as_coercion_site(&self) -> &hir::Expr<'_>;
1462 impl AsCoercionSite for hir::Expr<'_> {
1463 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1468 impl<'a, T> AsCoercionSite for &'a T
1472 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1473 (**self).as_coercion_site()
1477 impl AsCoercionSite for ! {
1478 fn as_coercion_site(&self) -> &hir::Expr<'_> {
1483 impl AsCoercionSite for hir::Arm<'_> {
1484 fn as_coercion_site(&self) -> &hir::Expr<'_> {