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`.
8 use chalk_ir::{cast::Cast, Goal, Mutability, TyVariableKind};
9 use hir_def::{expr::ExprId, lang_item::LangItemTarget};
13 infer::{Adjust, Adjustment, AutoBorrow, InferResult, PointerCast, TypeMismatch},
14 static_lifetime, Canonical, DomainGoal, FnPointer, FnSig, Interner, Solution, Substitution, Ty,
15 TyBuilder, TyExt, TyKind,
18 use super::{InEnvironment, InferOk, InferenceContext, TypeError};
20 pub(crate) type CoerceResult = Result<InferOk<(Vec<Adjustment>, Ty)>, TypeError>;
22 /// Do not require any adjustments, i.e. coerce `x -> x`.
23 fn identity(_: Ty) -> Vec<Adjustment> {
27 fn simple(kind: Adjust) -> impl FnOnce(Ty) -> Vec<Adjustment> {
28 move |target| vec![Adjustment { kind, target }]
31 /// This always returns `Ok(...)`.
35 goals: Vec<InEnvironment<Goal<Interner>>>,
37 Ok(InferOk { goals, value: (adj, target) })
39 #[derive(Clone, Debug)]
40 pub(super) struct CoerceMany {
45 pub(super) fn new(expected: Ty) -> Self {
46 CoerceMany { expected_ty: expected }
50 ctx: &mut InferenceContext<'_>,
55 let mut this = CoerceMany::new(expected);
56 this.coerce(ctx, expr, expr_ty);
60 /// Merge two types from different branches, with possible coercion.
62 /// Mostly this means trying to coerce one to the other, but
63 /// - if we have two function types for different functions or closures, we need to
64 /// coerce both to function pointers;
65 /// - if we were concerned with lifetime subtyping, we'd need to look for a
66 /// least upper bound.
69 ctx: &mut InferenceContext<'_>,
73 let expr_ty = ctx.resolve_ty_shallow(expr_ty);
74 self.expected_ty = ctx.resolve_ty_shallow(&self.expected_ty);
76 // Special case: two function types. Try to coerce both to
77 // pointers to have a chance at getting a match. See
78 // https://github.com/rust-lang/rust/blob/7b805396bf46dce972692a6846ce2ad8481c5f85/src/librustc_typeck/check/coercion.rs#L877-L916
79 let sig = match (self.expected_ty.kind(&Interner), expr_ty.kind(&Interner)) {
80 (TyKind::FnDef(..) | TyKind::Closure(..), TyKind::FnDef(..) | TyKind::Closure(..)) => {
81 // FIXME: we're ignoring safety here. To be more correct, if we have one FnDef and one Closure,
82 // we should be coercing the closure to a fn pointer of the safety of the FnDef
83 cov_mark::hit!(coerce_fn_reification);
85 self.expected_ty.callable_sig(ctx.db).expect("FnDef without callable sig");
90 if let Some(sig) = sig {
91 let target_ty = TyKind::Function(sig.to_fn_ptr()).intern(&Interner);
92 let result1 = ctx.coerce_inner(self.expected_ty.clone(), &target_ty);
93 let result2 = ctx.coerce_inner(expr_ty.clone(), &target_ty);
94 if let (Ok(result1), Ok(result2)) = (result1, result2) {
95 ctx.table.register_infer_ok(result1);
96 ctx.table.register_infer_ok(result2);
97 return self.expected_ty = target_ty;
101 // It might not seem like it, but order is important here: If the expected
102 // type is a type variable and the new one is `!`, trying it the other
103 // way around first would mean we make the type variable `!`, instead of
104 // just marking it as possibly diverging.
105 if ctx.coerce(expr, &expr_ty, &self.expected_ty).is_ok() {
106 /* self.expected_ty is already correct */
107 } else if ctx.coerce(expr, &self.expected_ty, &expr_ty).is_ok() {
108 self.expected_ty = expr_ty;
110 if let Some(id) = expr {
111 ctx.result.type_mismatches.insert(
113 TypeMismatch { expected: self.expected_ty.clone(), actual: expr_ty },
116 cov_mark::hit!(coerce_merge_fail_fallback);
117 /* self.expected_ty is already correct */
121 pub(super) fn complete(self) -> Ty {
126 impl<'a> InferenceContext<'a> {
127 /// Unify two types, but may coerce the first one to the second one
128 /// using "implicit coercion rules" if needed.
129 pub(super) fn coerce(
131 expr: Option<ExprId>,
134 ) -> InferResult<Ty> {
135 let from_ty = self.resolve_ty_shallow(from_ty);
136 let to_ty = self.resolve_ty_shallow(to_ty);
137 match self.coerce_inner(from_ty, &to_ty) {
138 Ok(InferOk { value: (adjustments, ty), goals }) => {
139 if let Some(expr) = expr {
140 self.write_expr_adj(expr, adjustments);
142 self.table.register_infer_ok(InferOk { value: (), goals });
143 Ok(InferOk { value: ty, goals: Vec::new() })
146 // FIXME deal with error
152 fn coerce_inner(&mut self, from_ty: Ty, to_ty: &Ty) -> CoerceResult {
153 if from_ty.is_never() {
154 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
155 // type variable, we want `?T` to fallback to `!` if not
156 // otherwise constrained. An example where this arises:
158 // let _: Option<?T> = Some({ return; });
160 // here, we would coerce from `!` to `?T`.
161 if let TyKind::InferenceVar(tv, TyVariableKind::General) = to_ty.kind(&Interner) {
162 self.table.set_diverging(*tv, true);
164 return success(simple(Adjust::NeverToAny)(to_ty.clone()), to_ty.clone(), vec![]);
167 // Consider coercing the subtype to a DST
168 if let Ok(ret) = self.try_coerce_unsized(&from_ty, to_ty) {
172 // Examine the supertype and consider auto-borrowing.
173 match to_ty.kind(&Interner) {
174 TyKind::Raw(mt, _) => {
175 return self.coerce_ptr(from_ty, to_ty, *mt);
177 TyKind::Ref(mt, _, _) => {
178 return self.coerce_ref(from_ty, to_ty, *mt);
183 match from_ty.kind(&Interner) {
184 TyKind::FnDef(..) => {
185 // Function items are coercible to any closure
186 // type; function pointers are not (that would
187 // require double indirection).
188 // Additionally, we permit coercion of function
189 // items to drop the unsafe qualifier.
190 self.coerce_from_fn_item(from_ty, to_ty)
192 TyKind::Function(from_fn_ptr) => {
193 // We permit coercion of fn pointers to drop the
195 self.coerce_from_fn_pointer(from_ty.clone(), from_fn_ptr, to_ty)
197 TyKind::Closure(_, from_substs) => {
198 // Non-capturing closures are coercible to
199 // function pointers or unsafe function pointers.
200 // It cannot convert closures that require unsafe.
201 self.coerce_closure_to_fn(from_ty.clone(), from_substs, to_ty)
204 // Otherwise, just use unification rules.
205 self.unify_and(&from_ty, to_ty, identity)
210 /// Unify two types (using sub or lub) and produce a specific coercion.
211 fn unify_and<F>(&mut self, t1: &Ty, t2: &Ty, f: F) -> CoerceResult
213 F: FnOnce(Ty) -> Vec<Adjustment>,
217 .and_then(|InferOk { goals, .. }| success(f(t1.clone()), t1.clone(), goals))
220 fn coerce_ptr(&mut self, from_ty: Ty, to_ty: &Ty, to_mt: Mutability) -> CoerceResult {
221 let (is_ref, from_mt, from_inner) = match from_ty.kind(&Interner) {
222 TyKind::Ref(mt, _, ty) => (true, mt, ty),
223 TyKind::Raw(mt, ty) => (false, mt, ty),
224 _ => return self.unify_and(&from_ty, to_ty, identity),
227 coerce_mutabilities(*from_mt, to_mt)?;
229 // Check that the types which they point at are compatible.
230 let from_raw = TyKind::Raw(to_mt, from_inner.clone()).intern(&Interner);
232 // Although references and unsafe ptrs have the same
233 // representation, we still register an Adjust::DerefRef so that
234 // regionck knows that the region for `a` must be valid here.
236 self.unify_and(&from_raw, to_ty, |target| {
238 Adjustment { kind: Adjust::Deref(None), target: from_inner.clone() },
239 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(to_mt)), target },
242 } else if *from_mt != to_mt {
246 simple(Adjust::Pointer(PointerCast::MutToConstPointer)),
249 self.unify_and(&from_raw, to_ty, identity)
253 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
254 /// To match `A` with `B`, autoderef will be performed,
255 /// calling `deref`/`deref_mut` where necessary.
256 fn coerce_ref(&mut self, from_ty: Ty, to_ty: &Ty, to_mt: Mutability) -> CoerceResult {
257 match from_ty.kind(&Interner) {
258 TyKind::Ref(mt, _, _) => {
259 coerce_mutabilities(*mt, to_mt)?;
261 _ => return self.unify_and(&from_ty, to_ty, identity),
264 // NOTE: this code is mostly copied and adapted from rustc, and
265 // currently more complicated than necessary, carrying errors around
266 // etc.. This complication will become necessary when we actually track
267 // details of coercion errors though, so I think it's useful to leave
268 // the structure like it is.
270 let canonicalized = self.canonicalize(from_ty);
271 let autoderef = autoderef::autoderef(
273 self.resolver.krate(),
275 goal: canonicalized.value.clone(),
276 environment: self.trait_env.env.clone(),
279 let mut first_error = None;
280 let mut found = None;
282 for (autoderefs, referent_ty) in autoderef.enumerate() {
284 // Don't let this pass, otherwise it would cause
285 // &T to autoref to &&T.
289 let referent_ty = canonicalized.decanonicalize_ty(referent_ty.value);
291 // At this point, we have deref'd `a` to `referent_ty`. So
292 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
293 // In the autoderef loop for `&'a mut Vec<T>`, we would get
296 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
297 // - `Vec<T>` -- 1 deref
298 // - `[T]` -- 2 deref
300 // At each point after the first callback, we want to
301 // check to see whether this would match out target type
302 // (`&'b mut [T]`) if we autoref'd it. We can't just
303 // compare the referent types, though, because we still
304 // have to consider the mutability. E.g., in the case
305 // we've been considering, we have an `&mut` reference, so
306 // the `T` in `[T]` needs to be unified with equality.
308 // Therefore, we construct reference types reflecting what
309 // the types will be after we do the final auto-ref and
310 // compare those. Note that this means we use the target
311 // mutability [1], since it may be that we are coercing
312 // from `&mut T` to `&U`.
313 let lt = static_lifetime(); // FIXME: handle lifetimes correctly, see rustc
314 let derefd_from_ty = TyKind::Ref(to_mt, lt, referent_ty).intern(&Interner);
315 match self.table.try_unify(&derefd_from_ty, to_ty) {
317 found = Some(result.map(|()| derefd_from_ty));
321 if first_error.is_none() {
322 first_error = Some(err);
328 // Extract type or return an error. We return the first error
329 // we got, which should be from relating the "base" type
330 // (e.g., in example above, the failure from relating `Vec<T>`
331 // to the target type), since that should be the least
333 let InferOk { value: ty, goals } = match found {
336 let err = first_error.expect("coerce_borrowed_pointer had no error");
340 // FIXME: record overloarded deref adjustments
342 vec![Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(to_mt)), target: ty.clone() }],
348 /// Attempts to coerce from the type of a Rust function item into a function pointer.
349 fn coerce_from_fn_item(&mut self, from_ty: Ty, to_ty: &Ty) -> CoerceResult {
350 match to_ty.kind(&Interner) {
351 TyKind::Function(_) => {
352 let from_sig = from_ty.callable_sig(self.db).expect("FnDef had no sig");
354 // FIXME check ABI: Intrinsics are not coercible to function pointers
355 // FIXME Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396)
357 // FIXME rustc normalizes assoc types in the sig here, not sure if necessary
359 let from_sig = from_sig.to_fn_ptr();
360 let from_fn_pointer = TyKind::Function(from_sig.clone()).intern(&Interner);
361 let ok = self.coerce_from_safe_fn(
362 from_fn_pointer.clone(),
368 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
369 target: from_fn_pointer,
372 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
377 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
382 _ => self.unify_and(&from_ty, to_ty, identity),
386 fn coerce_from_fn_pointer(
392 self.coerce_from_safe_fn(
396 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
401 fn coerce_from_safe_fn<F, G>(
404 from_fn_ptr: &FnPointer,
410 F: FnOnce(Ty) -> Vec<Adjustment>,
411 G: FnOnce(Ty) -> Vec<Adjustment>,
413 if let TyKind::Function(to_fn_ptr) = to_ty.kind(&Interner) {
414 if let (chalk_ir::Safety::Safe, chalk_ir::Safety::Unsafe) =
415 (from_fn_ptr.sig.safety, to_fn_ptr.sig.safety)
418 TyKind::Function(safe_to_unsafe_fn_ty(from_fn_ptr.clone())).intern(&Interner);
419 return self.unify_and(&from_unsafe, to_ty, to_unsafe);
422 self.unify_and(&from_ty, to_ty, normal)
425 /// Attempts to coerce from the type of a non-capturing closure into a
426 /// function pointer.
427 fn coerce_closure_to_fn(
430 from_substs: &Substitution,
433 match to_ty.kind(&Interner) {
434 // if from_substs is non-capturing (FIXME)
435 TyKind::Function(fn_ty) => {
436 // We coerce the closure, which has fn type
437 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
439 // `fn(arg0,arg1,...) -> _`
441 // `unsafe fn(arg0,arg1,...) -> _`
442 let safety = fn_ty.sig.safety;
443 let pointer_ty = coerce_closure_fn_ty(from_substs, safety);
447 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(safety))),
450 _ => self.unify_and(&from_ty, to_ty, identity),
454 /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>`
456 /// See: <https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html>
457 fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> CoerceResult {
458 // These 'if' statements require some explanation.
459 // The `CoerceUnsized` trait is special - it is only
460 // possible to write `impl CoerceUnsized<B> for A` where
461 // A and B have 'matching' fields. This rules out the following
462 // two types of blanket impls:
464 // `impl<T> CoerceUnsized<T> for SomeType`
465 // `impl<T> CoerceUnsized<SomeType> for T`
467 // Both of these trigger a special `CoerceUnsized`-related error (E0376)
469 // We can take advantage of this fact to avoid performing unnecessary work.
470 // If either `source` or `target` is a type variable, then any applicable impl
471 // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
472 // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
475 // However, these are exactly the kinds of impls which are forbidden by
476 // the compiler! Therefore, we can be sure that coercion will always fail
477 // when either the source or target type is a type variable. This allows us
478 // to skip performing any trait selection, and immediately bail out.
479 if from_ty.is_ty_var() {
480 return Err(TypeError);
482 if to_ty.is_ty_var() {
483 return Err(TypeError);
486 // Handle reborrows before trying to solve `Source: CoerceUnsized<Target>`.
487 let reborrow = match (from_ty.kind(&Interner), to_ty.kind(&Interner)) {
488 (TyKind::Ref(from_mt, _, from_inner), &TyKind::Ref(to_mt, _, _)) => {
489 coerce_mutabilities(*from_mt, to_mt)?;
491 let lt = static_lifetime();
493 Adjustment { kind: Adjust::Deref(None), target: from_inner.clone() },
495 kind: Adjust::Borrow(AutoBorrow::Ref(to_mt)),
496 target: TyKind::Ref(to_mt, lt, from_inner.clone()).intern(&Interner),
500 (TyKind::Ref(from_mt, _, from_inner), &TyKind::Raw(to_mt, _)) => {
501 coerce_mutabilities(*from_mt, to_mt)?;
504 Adjustment { kind: Adjust::Deref(None), target: from_inner.clone() },
506 kind: Adjust::Borrow(AutoBorrow::RawPtr(to_mt)),
507 target: TyKind::Raw(to_mt, from_inner.clone()).intern(&Interner),
514 reborrow.as_ref().map_or_else(|| from_ty.clone(), |(_, adj)| adj.target.clone());
516 let krate = self.resolver.krate().unwrap();
517 let coerce_unsized_trait = match self.db.lang_item(krate, "coerce_unsized".into()) {
518 Some(LangItemTarget::TraitId(trait_)) => trait_,
519 _ => return Err(TypeError),
523 let b = TyBuilder::trait_ref(self.db, coerce_unsized_trait);
524 if b.remaining() != 2 {
525 // The CoerceUnsized trait should have two generic params: Self and T.
526 return Err(TypeError);
528 b.push(coerce_from).push(to_ty.clone()).build()
531 let goal: InEnvironment<DomainGoal> =
532 InEnvironment::new(&self.trait_env.env, trait_ref.cast(&Interner));
534 let canonicalized = self.canonicalize(goal);
536 // FIXME: rustc's coerce_unsized is more specialized -- it only tries to
537 // solve `CoerceUnsized` and `Unsize` goals at this point and leaves the
538 // rest for later. Also, there's some logic about sized type variables.
539 // Need to find out in what cases this is necessary
542 .trait_solve(krate, canonicalized.value.clone().cast(&Interner))
546 Solution::Unique(v) => {
547 canonicalized.apply_solution(
551 // FIXME handle constraints
552 value: v.value.subst,
556 // FIXME: should we accept ambiguous results here?
557 _ => return Err(TypeError),
560 Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target: to_ty.clone() };
561 let adjustments = match reborrow {
562 None => vec![unsize],
563 Some((deref, autoref)) => vec![deref, autoref, unsize],
565 success(adjustments, to_ty.clone(), vec![])
569 fn coerce_closure_fn_ty(closure_substs: &Substitution, safety: chalk_ir::Safety) -> Ty {
570 let closure_sig = closure_substs.at(&Interner, 0).assert_ty_ref(&Interner).clone();
571 match closure_sig.kind(&Interner) {
572 TyKind::Function(fn_ty) => TyKind::Function(FnPointer {
573 num_binders: fn_ty.num_binders,
574 sig: FnSig { safety, ..fn_ty.sig },
575 substitution: fn_ty.substitution.clone(),
578 _ => TyKind::Error.intern(&Interner),
582 fn safe_to_unsafe_fn_ty(fn_ty: FnPointer) -> FnPointer {
584 num_binders: fn_ty.num_binders,
585 sig: FnSig { safety: chalk_ir::Safety::Unsafe, ..fn_ty.sig },
586 substitution: fn_ty.substitution,
590 fn coerce_mutabilities(from: Mutability, to: Mutability) -> Result<(), TypeError> {
592 (Mutability::Mut, Mutability::Mut | Mutability::Not)
593 | (Mutability::Not, Mutability::Not) => Ok(()),
594 (Mutability::Not, Mutability::Mut) => Err(TypeError),