1 //! Coercion logic. Coercions are certain type conversions that can implicitly
2 //! happen in certain places, e.g. weakening `&mut` to `&` or deref coercions
3 //! like going from `&Vec<T>` to `&[T]`.
5 //! See <https://doc.rust-lang.org/nomicon/coercions.html> and
6 //! `librustc_typeck/check/coercion.rs`.
10 use chalk_ir::{cast::Cast, Goal, Mutability, TyVariableKind};
11 use hir_def::{expr::ExprId, lang_item::LangItemTarget};
15 autoderef::{Autoderef, AutoderefKind},
17 Adjust, Adjustment, AutoBorrow, InferOk, InferResult, InferenceContext, OverloadedDeref,
18 PointerCast, TypeError, TypeMismatch,
20 static_lifetime, Canonical, DomainGoal, FnPointer, FnSig, Guidance, InEnvironment, Interner,
21 Solution, Substitution, Ty, TyBuilder, TyExt, TyKind,
24 pub(crate) type CoerceResult = Result<InferOk<(Vec<Adjustment>, Ty)>, TypeError>;
26 /// Do not require any adjustments, i.e. coerce `x -> x`.
27 fn identity(_: Ty) -> Vec<Adjustment> {
31 fn simple(kind: Adjust) -> impl FnOnce(Ty) -> Vec<Adjustment> {
32 move |target| vec![Adjustment { kind, target }]
35 /// This always returns `Ok(...)`.
39 goals: Vec<InEnvironment<Goal<Interner>>>,
41 Ok(InferOk { goals, value: (adj, target) })
44 #[derive(Clone, Debug)]
45 pub(super) struct CoerceMany {
50 pub(super) fn new(expected: Ty) -> Self {
51 CoerceMany { expected_ty: expected }
54 /// Merge two types from different branches, with possible coercion.
56 /// Mostly this means trying to coerce one to the other, but
57 /// - if we have two function types for different functions or closures, we need to
58 /// coerce both to function pointers;
59 /// - if we were concerned with lifetime subtyping, we'd need to look for a
60 /// least upper bound.
63 ctx: &mut InferenceContext<'_>,
67 let expr_ty = ctx.resolve_ty_shallow(expr_ty);
68 self.expected_ty = ctx.resolve_ty_shallow(&self.expected_ty);
70 // Special case: two function types. Try to coerce both to
71 // pointers to have a chance at getting a match. See
72 // https://github.com/rust-lang/rust/blob/7b805396bf46dce972692a6846ce2ad8481c5f85/src/librustc_typeck/check/coercion.rs#L877-L916
73 let sig = match (self.expected_ty.kind(&Interner), expr_ty.kind(&Interner)) {
74 (TyKind::FnDef(..) | TyKind::Closure(..), TyKind::FnDef(..) | TyKind::Closure(..)) => {
75 // FIXME: we're ignoring safety here. To be more correct, if we have one FnDef and one Closure,
76 // we should be coercing the closure to a fn pointer of the safety of the FnDef
77 cov_mark::hit!(coerce_fn_reification);
79 self.expected_ty.callable_sig(ctx.db).expect("FnDef without callable sig");
84 if let Some(sig) = sig {
85 let target_ty = TyKind::Function(sig.to_fn_ptr()).intern(&Interner);
86 let result1 = ctx.coerce_inner(self.expected_ty.clone(), &target_ty);
87 let result2 = ctx.coerce_inner(expr_ty.clone(), &target_ty);
88 if let (Ok(result1), Ok(result2)) = (result1, result2) {
89 ctx.table.register_infer_ok(result1);
90 ctx.table.register_infer_ok(result2);
91 return self.expected_ty = target_ty;
95 // It might not seem like it, but order is important here: If the expected
96 // type is a type variable and the new one is `!`, trying it the other
97 // way around first would mean we make the type variable `!`, instead of
98 // just marking it as possibly diverging.
99 if ctx.coerce(expr, &expr_ty, &self.expected_ty).is_ok() {
100 /* self.expected_ty is already correct */
101 } else if ctx.coerce(expr, &self.expected_ty, &expr_ty).is_ok() {
102 self.expected_ty = expr_ty;
104 if let Some(id) = expr {
105 ctx.result.type_mismatches.insert(
107 TypeMismatch { expected: self.expected_ty.clone(), actual: expr_ty },
110 cov_mark::hit!(coerce_merge_fail_fallback);
111 /* self.expected_ty is already correct */
115 pub(super) fn complete(self) -> Ty {
120 impl<'a> InferenceContext<'a> {
121 /// Unify two types, but may coerce the first one to the second one
122 /// using "implicit coercion rules" if needed.
123 pub(super) fn coerce(
125 expr: Option<ExprId>,
128 ) -> InferResult<Ty> {
129 let from_ty = self.resolve_ty_shallow(from_ty);
130 let to_ty = self.resolve_ty_shallow(to_ty);
131 match self.coerce_inner(from_ty, &to_ty) {
132 Ok(InferOk { value: (adjustments, ty), goals }) => {
133 if let Some(expr) = expr {
134 self.write_expr_adj(expr, adjustments);
136 self.table.register_infer_ok(InferOk { value: (), goals });
137 Ok(InferOk { value: ty, goals: Vec::new() })
140 // FIXME deal with error
146 fn coerce_inner(&mut self, from_ty: Ty, to_ty: &Ty) -> CoerceResult {
147 if from_ty.is_never() {
148 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
149 // type variable, we want `?T` to fallback to `!` if not
150 // otherwise constrained. An example where this arises:
152 // let _: Option<?T> = Some({ return; });
154 // here, we would coerce from `!` to `?T`.
155 if let TyKind::InferenceVar(tv, TyVariableKind::General) = to_ty.kind(&Interner) {
156 self.table.set_diverging(*tv, true);
158 return success(simple(Adjust::NeverToAny)(to_ty.clone()), to_ty.clone(), vec![]);
161 // Consider coercing the subtype to a DST
162 if let Ok(ret) = self.try_coerce_unsized(&from_ty, to_ty) {
166 // Examine the supertype and consider auto-borrowing.
167 match to_ty.kind(&Interner) {
168 TyKind::Raw(mt, _) => return self.coerce_ptr(from_ty, to_ty, *mt),
169 TyKind::Ref(mt, _, _) => return self.coerce_ref(from_ty, to_ty, *mt),
173 match from_ty.kind(&Interner) {
174 TyKind::FnDef(..) => {
175 // Function items are coercible to any closure
176 // type; function pointers are not (that would
177 // require double indirection).
178 // Additionally, we permit coercion of function
179 // items to drop the unsafe qualifier.
180 self.coerce_from_fn_item(from_ty, to_ty)
182 TyKind::Function(from_fn_ptr) => {
183 // We permit coercion of fn pointers to drop the
185 self.coerce_from_fn_pointer(from_ty.clone(), from_fn_ptr, to_ty)
187 TyKind::Closure(_, from_substs) => {
188 // Non-capturing closures are coercible to
189 // function pointers or unsafe function pointers.
190 // It cannot convert closures that require unsafe.
191 self.coerce_closure_to_fn(from_ty.clone(), from_substs, to_ty)
194 // Otherwise, just use unification rules.
195 self.unify_and(&from_ty, to_ty, identity)
200 /// Unify two types (using sub or lub) and produce a specific coercion.
201 fn unify_and<F>(&mut self, t1: &Ty, t2: &Ty, f: F) -> CoerceResult
203 F: FnOnce(Ty) -> Vec<Adjustment>,
207 .and_then(|InferOk { goals, .. }| success(f(t1.clone()), t1.clone(), goals))
210 fn coerce_ptr(&mut self, from_ty: Ty, to_ty: &Ty, to_mt: Mutability) -> CoerceResult {
211 let (is_ref, from_mt, from_inner) = match from_ty.kind(&Interner) {
212 TyKind::Ref(mt, _, ty) => (true, mt, ty),
213 TyKind::Raw(mt, ty) => (false, mt, ty),
214 _ => return self.unify_and(&from_ty, to_ty, identity),
217 coerce_mutabilities(*from_mt, to_mt)?;
219 // Check that the types which they point at are compatible.
220 let from_raw = TyKind::Raw(to_mt, from_inner.clone()).intern(&Interner);
222 // Although references and unsafe ptrs have the same
223 // representation, we still register an Adjust::DerefRef so that
224 // regionck knows that the region for `a` must be valid here.
226 self.unify_and(&from_raw, to_ty, |target| {
228 Adjustment { kind: Adjust::Deref(None), target: from_inner.clone() },
229 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(to_mt)), target },
232 } else if *from_mt != to_mt {
236 simple(Adjust::Pointer(PointerCast::MutToConstPointer)),
239 self.unify_and(&from_raw, to_ty, identity)
243 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
244 /// To match `A` with `B`, autoderef will be performed,
245 /// calling `deref`/`deref_mut` where necessary.
246 fn coerce_ref(&mut self, from_ty: Ty, to_ty: &Ty, to_mt: Mutability) -> CoerceResult {
247 let from_mt = match from_ty.kind(&Interner) {
248 &TyKind::Ref(mt, _, _) => {
249 coerce_mutabilities(mt, to_mt)?;
252 _ => return self.unify_and(&from_ty, to_ty, identity),
255 // NOTE: this code is mostly copied and adapted from rustc, and
256 // currently more complicated than necessary, carrying errors around
257 // etc.. This complication will become necessary when we actually track
258 // details of coercion errors though, so I think it's useful to leave
259 // the structure like it is.
261 let canonicalized = self.canonicalize(from_ty.clone());
262 let mut autoderef = Autoderef::new(
264 self.resolver.krate(),
266 goal: canonicalized.value.clone(),
267 environment: self.trait_env.env.clone(),
270 let mut first_error = None;
271 let mut found = None;
273 for (referent_ty, autoderefs) in autoderef.by_ref() {
275 // Don't let this pass, otherwise it would cause
276 // &T to autoref to &&T.
280 let referent_ty = canonicalized.decanonicalize_ty(&mut self.table, referent_ty);
282 // At this point, we have deref'd `a` to `referent_ty`. So
283 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
284 // In the autoderef loop for `&'a mut Vec<T>`, we would get
287 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
288 // - `Vec<T>` -- 1 deref
289 // - `[T]` -- 2 deref
291 // At each point after the first callback, we want to
292 // check to see whether this would match out target type
293 // (`&'b mut [T]`) if we autoref'd it. We can't just
294 // compare the referent types, though, because we still
295 // have to consider the mutability. E.g., in the case
296 // we've been considering, we have an `&mut` reference, so
297 // the `T` in `[T]` needs to be unified with equality.
299 // Therefore, we construct reference types reflecting what
300 // the types will be after we do the final auto-ref and
301 // compare those. Note that this means we use the target
302 // mutability [1], since it may be that we are coercing
303 // from `&mut T` to `&U`.
304 let lt = static_lifetime(); // FIXME: handle lifetimes correctly, see rustc
305 let derefd_from_ty = TyKind::Ref(to_mt, lt, referent_ty).intern(&Interner);
306 match self.table.try_unify(&derefd_from_ty, to_ty) {
308 found = Some(result.map(|()| derefd_from_ty));
312 if first_error.is_none() {
313 first_error = Some(err);
319 // Extract type or return an error. We return the first error
320 // we got, which should be from relating the "base" type
321 // (e.g., in example above, the failure from relating `Vec<T>`
322 // to the target type), since that should be the least
324 let InferOk { value: ty, goals } = match found {
327 let err = first_error.expect("coerce_borrowed_pointer had no error");
331 if ty == from_ty && from_mt == Mutability::Not && autoderef.step_count() == 1 {
332 // As a special case, if we would produce `&'a *x`, that's
333 // a total no-op. We end up with the type `&'a T` just as
334 // we started with. In that case, just skip it
335 // altogether. This is just an optimization.
337 // Note that for `&mut`, we DO want to reborrow --
338 // otherwise, this would be a move, which might be an
339 // error. For example `foo(self.x)` where `self` and
340 // `self.x` both have `&mut `type would be a move of
341 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
342 // which is a borrow.
343 always!(to_mt == Mutability::Not); // can only coerce &T -> &U
344 return success(vec![], ty, goals);
347 let mut adjustments = self.auto_deref_adjust_steps(&autoderef);
349 .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(to_mt)), target: ty.clone() });
351 success(adjustments, ty, goals)
354 pub(super) fn auto_deref_adjust_steps(&self, autoderef: &Autoderef<'_>) -> Vec<Adjustment> {
355 let steps = autoderef.steps();
357 steps.iter().skip(1).map(|(_, ty)| ty.clone()).chain(iter::once(autoderef.final_ty()));
360 .map(|(kind, _source)| match kind {
361 // We do not know what kind of deref we require at this point yet
362 AutoderefKind::Overloaded => Some(OverloadedDeref(Mutability::Not)),
363 AutoderefKind::Builtin => None,
366 .map(|(autoderef, target)| Adjustment { kind: Adjust::Deref(autoderef), target })
370 /// Attempts to coerce from the type of a Rust function item into a function pointer.
371 fn coerce_from_fn_item(&mut self, from_ty: Ty, to_ty: &Ty) -> CoerceResult {
372 match to_ty.kind(&Interner) {
373 TyKind::Function(_) => {
374 let from_sig = from_ty.callable_sig(self.db).expect("FnDef had no sig");
376 // FIXME check ABI: Intrinsics are not coercible to function pointers
377 // FIXME Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396)
379 // FIXME rustc normalizes assoc types in the sig here, not sure if necessary
381 let from_sig = from_sig.to_fn_ptr();
382 let from_fn_pointer = TyKind::Function(from_sig.clone()).intern(&Interner);
383 let ok = self.coerce_from_safe_fn(
384 from_fn_pointer.clone(),
390 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
391 target: from_fn_pointer,
394 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
399 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
404 _ => self.unify_and(&from_ty, to_ty, identity),
408 fn coerce_from_fn_pointer(
414 self.coerce_from_safe_fn(
418 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
423 fn coerce_from_safe_fn<F, G>(
426 from_fn_ptr: &FnPointer,
432 F: FnOnce(Ty) -> Vec<Adjustment>,
433 G: FnOnce(Ty) -> Vec<Adjustment>,
435 if let TyKind::Function(to_fn_ptr) = to_ty.kind(&Interner) {
436 if let (chalk_ir::Safety::Safe, chalk_ir::Safety::Unsafe) =
437 (from_fn_ptr.sig.safety, to_fn_ptr.sig.safety)
440 TyKind::Function(safe_to_unsafe_fn_ty(from_fn_ptr.clone())).intern(&Interner);
441 return self.unify_and(&from_unsafe, to_ty, to_unsafe);
444 self.unify_and(&from_ty, to_ty, normal)
447 /// Attempts to coerce from the type of a non-capturing closure into a
448 /// function pointer.
449 fn coerce_closure_to_fn(
452 from_substs: &Substitution,
455 match to_ty.kind(&Interner) {
456 // if from_substs is non-capturing (FIXME)
457 TyKind::Function(fn_ty) => {
458 // We coerce the closure, which has fn type
459 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
461 // `fn(arg0,arg1,...) -> _`
463 // `unsafe fn(arg0,arg1,...) -> _`
464 let safety = fn_ty.sig.safety;
465 let pointer_ty = coerce_closure_fn_ty(from_substs, safety);
469 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(safety))),
472 _ => self.unify_and(&from_ty, to_ty, identity),
476 /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>`
478 /// See: <https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html>
479 fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> CoerceResult {
480 // These 'if' statements require some explanation.
481 // The `CoerceUnsized` trait is special - it is only
482 // possible to write `impl CoerceUnsized<B> for A` where
483 // A and B have 'matching' fields. This rules out the following
484 // two types of blanket impls:
486 // `impl<T> CoerceUnsized<T> for SomeType`
487 // `impl<T> CoerceUnsized<SomeType> for T`
489 // Both of these trigger a special `CoerceUnsized`-related error (E0376)
491 // We can take advantage of this fact to avoid performing unnecessary work.
492 // If either `source` or `target` is a type variable, then any applicable impl
493 // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
494 // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
497 // However, these are exactly the kinds of impls which are forbidden by
498 // the compiler! Therefore, we can be sure that coercion will always fail
499 // when either the source or target type is a type variable. This allows us
500 // to skip performing any trait selection, and immediately bail out.
501 if from_ty.is_ty_var() {
502 return Err(TypeError);
504 if to_ty.is_ty_var() {
505 return Err(TypeError);
508 // Handle reborrows before trying to solve `Source: CoerceUnsized<Target>`.
509 let reborrow = match (from_ty.kind(&Interner), to_ty.kind(&Interner)) {
510 (TyKind::Ref(from_mt, _, from_inner), &TyKind::Ref(to_mt, _, _)) => {
511 coerce_mutabilities(*from_mt, to_mt)?;
513 let lt = static_lifetime();
515 Adjustment { kind: Adjust::Deref(None), target: from_inner.clone() },
517 kind: Adjust::Borrow(AutoBorrow::Ref(to_mt)),
518 target: TyKind::Ref(to_mt, lt, from_inner.clone()).intern(&Interner),
522 (TyKind::Ref(from_mt, _, from_inner), &TyKind::Raw(to_mt, _)) => {
523 coerce_mutabilities(*from_mt, to_mt)?;
526 Adjustment { kind: Adjust::Deref(None), target: from_inner.clone() },
528 kind: Adjust::Borrow(AutoBorrow::RawPtr(to_mt)),
529 target: TyKind::Raw(to_mt, from_inner.clone()).intern(&Interner),
536 reborrow.as_ref().map_or_else(|| from_ty.clone(), |(_, adj)| adj.target.clone());
538 let krate = self.resolver.krate().unwrap();
539 let coerce_unsized_trait = match self.db.lang_item(krate, "coerce_unsized".into()) {
540 Some(LangItemTarget::TraitId(trait_)) => trait_,
541 _ => return Err(TypeError),
544 let coerce_unsized_tref = {
545 let b = TyBuilder::trait_ref(self.db, coerce_unsized_trait);
546 if b.remaining() != 2 {
547 // The CoerceUnsized trait should have two generic params: Self and T.
548 return Err(TypeError);
550 b.push(coerce_from).push(to_ty.clone()).build()
553 let goal: InEnvironment<DomainGoal> =
554 InEnvironment::new(&self.trait_env.env, coerce_unsized_tref.cast(&Interner));
556 let canonicalized = self.canonicalize(goal);
558 // FIXME: rustc's coerce_unsized is more specialized -- it only tries to
559 // solve `CoerceUnsized` and `Unsize` goals at this point and leaves the
560 // rest for later. Also, there's some logic about sized type variables.
561 // Need to find out in what cases this is necessary
564 .trait_solve(krate, canonicalized.value.clone().cast(&Interner))
568 Solution::Unique(v) => {
569 canonicalized.apply_solution(
573 // FIXME handle constraints
574 value: v.value.subst,
578 Solution::Ambig(Guidance::Definite(subst)) => {
579 canonicalized.apply_solution(&mut self.table, subst)
581 _ => return Err(TypeError),
584 Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target: to_ty.clone() };
585 let adjustments = match reborrow {
586 None => vec![unsize],
587 Some((deref, autoref)) => vec![deref, autoref, unsize],
589 success(adjustments, to_ty.clone(), vec![])
593 fn coerce_closure_fn_ty(closure_substs: &Substitution, safety: chalk_ir::Safety) -> Ty {
594 let closure_sig = closure_substs.at(&Interner, 0).assert_ty_ref(&Interner).clone();
595 match closure_sig.kind(&Interner) {
596 TyKind::Function(fn_ty) => TyKind::Function(FnPointer {
597 num_binders: fn_ty.num_binders,
598 sig: FnSig { safety, ..fn_ty.sig },
599 substitution: fn_ty.substitution.clone(),
602 _ => TyKind::Error.intern(&Interner),
606 fn safe_to_unsafe_fn_ty(fn_ty: FnPointer) -> FnPointer {
608 num_binders: fn_ty.num_binders,
609 sig: FnSig { safety: chalk_ir::Safety::Unsafe, ..fn_ty.sig },
610 substitution: fn_ty.substitution,
614 fn coerce_mutabilities(from: Mutability, to: Mutability) -> Result<(), TypeError> {
616 (Mutability::Mut, Mutability::Mut | Mutability::Not)
617 | (Mutability::Not, Mutability::Not) => Ok(()),
618 (Mutability::Not, Mutability::Mut) => Err(TypeError),