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, Mutability, TyVariableKind};
9 use hir_def::{expr::ExprId, lang_item::LangItemTarget};
12 autoderef, infer::TypeMismatch, static_lifetime, Canonical, DomainGoal, FnPointer, FnSig,
13 Interner, Solution, Substitution, Ty, TyBuilder, TyExt, TyKind,
16 use super::{InEnvironment, InferOk, InferResult, InferenceContext, TypeError};
18 impl<'a> InferenceContext<'a> {
19 /// Unify two types, but may coerce the first one to the second one
20 /// using "implicit coercion rules" if needed.
21 pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool {
22 let from_ty = self.resolve_ty_shallow(from_ty);
23 let to_ty = self.resolve_ty_shallow(to_ty);
24 match self.coerce_inner(from_ty, &to_ty) {
26 self.table.register_infer_ok(result);
30 // FIXME deal with error
36 /// Merge two types from different branches, with possible coercion.
38 /// Mostly this means trying to coerce one to the other, but
39 /// - if we have two function types for different functions or closures, we need to
40 /// coerce both to function pointers;
41 /// - if we were concerned with lifetime subtyping, we'd need to look for a
42 /// least upper bound.
43 pub(super) fn coerce_merge_branch(&mut self, id: Option<ExprId>, ty1: &Ty, ty2: &Ty) -> Ty {
44 let ty1 = self.resolve_ty_shallow(ty1);
45 let ty2 = self.resolve_ty_shallow(ty2);
46 // Special case: two function types. Try to coerce both to
47 // pointers to have a chance at getting a match. See
48 // https://github.com/rust-lang/rust/blob/7b805396bf46dce972692a6846ce2ad8481c5f85/src/librustc_typeck/check/coercion.rs#L877-L916
49 let sig = match (ty1.kind(&Interner), ty2.kind(&Interner)) {
50 (TyKind::FnDef(..), TyKind::FnDef(..))
51 | (TyKind::Closure(..), TyKind::FnDef(..))
52 | (TyKind::FnDef(..), TyKind::Closure(..))
53 | (TyKind::Closure(..), TyKind::Closure(..)) => {
54 // FIXME: we're ignoring safety here. To be more correct, if we have one FnDef and one Closure,
55 // we should be coercing the closure to a fn pointer of the safety of the FnDef
56 cov_mark::hit!(coerce_fn_reification);
57 let sig = ty1.callable_sig(self.db).expect("FnDef without callable sig");
62 if let Some(sig) = sig {
63 let target_ty = TyKind::Function(sig.to_fn_ptr()).intern(&Interner);
64 let result1 = self.coerce_inner(ty1.clone(), &target_ty);
65 let result2 = self.coerce_inner(ty2.clone(), &target_ty);
66 if let (Ok(result1), Ok(result2)) = (result1, result2) {
67 self.table.register_infer_ok(result1);
68 self.table.register_infer_ok(result2);
73 // It might not seem like it, but order is important here: ty1 is our
74 // "previous" type, ty2 is the "new" one being added. If the previous
75 // type is a type variable and the new one is `!`, trying it the other
76 // way around first would mean we make the type variable `!`, instead of
77 // just marking it as possibly diverging.
78 if self.coerce(&ty2, &ty1) {
80 } else if self.coerce(&ty1, &ty2) {
83 if let Some(id) = id {
86 .insert(id.into(), TypeMismatch { expected: ty1.clone(), actual: ty2 });
88 cov_mark::hit!(coerce_merge_fail_fallback);
93 fn coerce_inner(&mut self, from_ty: Ty, to_ty: &Ty) -> InferResult {
94 if from_ty.is_never() {
95 // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
96 // type variable, we want `?T` to fallback to `!` if not
97 // otherwise constrained. An example where this arises:
99 // let _: Option<?T> = Some({ return; });
101 // here, we would coerce from `!` to `?T`.
102 match to_ty.kind(&Interner) {
103 TyKind::InferenceVar(tv, TyVariableKind::General) => {
104 self.table.set_diverging(*tv, true);
108 return Ok(InferOk { goals: Vec::new() });
111 // Consider coercing the subtype to a DST
112 if let Ok(ret) = self.try_coerce_unsized(&from_ty, &to_ty) {
116 // Examine the supertype and consider auto-borrowing.
117 match to_ty.kind(&Interner) {
118 TyKind::Raw(mt, _) => {
119 return self.coerce_ptr(from_ty, to_ty, *mt);
121 TyKind::Ref(mt, _, _) => {
122 return self.coerce_ref(from_ty, to_ty, *mt);
127 match from_ty.kind(&Interner) {
128 TyKind::FnDef(..) => {
129 // Function items are coercible to any closure
130 // type; function pointers are not (that would
131 // require double indirection).
132 // Additionally, we permit coercion of function
133 // items to drop the unsafe qualifier.
134 self.coerce_from_fn_item(from_ty, to_ty)
136 TyKind::Function(from_fn_ptr) => {
137 // We permit coercion of fn pointers to drop the
139 self.coerce_from_fn_pointer(from_ty.clone(), from_fn_ptr, to_ty)
141 TyKind::Closure(_, from_substs) => {
142 // Non-capturing closures are coercible to
143 // function pointers or unsafe function pointers.
144 // It cannot convert closures that require unsafe.
145 self.coerce_closure_to_fn(from_ty.clone(), from_substs, to_ty)
148 // Otherwise, just use unification rules.
149 self.table.try_unify(&from_ty, to_ty)
154 fn coerce_ptr(&mut self, from_ty: Ty, to_ty: &Ty, to_mt: Mutability) -> InferResult {
155 let (_is_ref, from_mt, from_inner) = match from_ty.kind(&Interner) {
156 TyKind::Ref(mt, _, ty) => (true, mt, ty),
157 TyKind::Raw(mt, ty) => (false, mt, ty),
158 _ => return self.table.try_unify(&from_ty, to_ty),
161 coerce_mutabilities(*from_mt, to_mt)?;
163 // Check that the types which they point at are compatible.
164 let from_raw = TyKind::Raw(to_mt, from_inner.clone()).intern(&Interner);
165 // FIXME: behavior differs based on is_ref once we're computing adjustments
166 self.table.try_unify(&from_raw, to_ty)
169 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
170 /// To match `A` with `B`, autoderef will be performed,
171 /// calling `deref`/`deref_mut` where necessary.
172 fn coerce_ref(&mut self, from_ty: Ty, to_ty: &Ty, to_mt: Mutability) -> InferResult {
173 match from_ty.kind(&Interner) {
174 TyKind::Ref(mt, _, _) => {
175 coerce_mutabilities(*mt, to_mt)?;
177 _ => return self.table.try_unify(&from_ty, to_ty),
180 // NOTE: this code is mostly copied and adapted from rustc, and
181 // currently more complicated than necessary, carrying errors around
182 // etc.. This complication will become necessary when we actually track
183 // details of coercion errors though, so I think it's useful to leave
184 // the structure like it is.
186 let canonicalized = self.canonicalize(from_ty);
187 let autoderef = autoderef::autoderef(
189 self.resolver.krate(),
191 goal: canonicalized.value.clone(),
192 environment: self.trait_env.env.clone(),
195 let mut first_error = None;
196 let mut found = None;
198 for (autoderefs, referent_ty) in autoderef.enumerate() {
200 // Don't let this pass, otherwise it would cause
201 // &T to autoref to &&T.
205 let referent_ty = canonicalized.decanonicalize_ty(referent_ty.value);
207 // At this point, we have deref'd `a` to `referent_ty`. So
208 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
209 // In the autoderef loop for `&'a mut Vec<T>`, we would get
212 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
213 // - `Vec<T>` -- 1 deref
214 // - `[T]` -- 2 deref
216 // At each point after the first callback, we want to
217 // check to see whether this would match out target type
218 // (`&'b mut [T]`) if we autoref'd it. We can't just
219 // compare the referent types, though, because we still
220 // have to consider the mutability. E.g., in the case
221 // we've been considering, we have an `&mut` reference, so
222 // the `T` in `[T]` needs to be unified with equality.
224 // Therefore, we construct reference types reflecting what
225 // the types will be after we do the final auto-ref and
226 // compare those. Note that this means we use the target
227 // mutability [1], since it may be that we are coercing
228 // from `&mut T` to `&U`.
229 let lt = static_lifetime(); // FIXME: handle lifetimes correctly, see rustc
230 let derefd_from_ty = TyKind::Ref(to_mt, lt, referent_ty).intern(&Interner);
231 match self.table.try_unify(&derefd_from_ty, to_ty) {
233 found = Some(result);
237 if first_error.is_none() {
238 first_error = Some(err);
244 // Extract type or return an error. We return the first error
245 // we got, which should be from relating the "base" type
246 // (e.g., in example above, the failure from relating `Vec<T>`
247 // to the target type), since that should be the least
249 let result = match found {
252 let err = first_error.expect("coerce_borrowed_pointer had no error");
260 /// Attempts to coerce from the type of a Rust function item into a function pointer.
261 fn coerce_from_fn_item(&mut self, from_ty: Ty, to_ty: &Ty) -> InferResult {
262 match to_ty.kind(&Interner) {
263 TyKind::Function(_) => {
264 let from_sig = from_ty.callable_sig(self.db).expect("FnDef had no sig");
266 // FIXME check ABI: Intrinsics are not coercible to function pointers
267 // FIXME Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396)
269 // FIXME rustc normalizes assoc types in the sig here, not sure if necessary
271 let from_sig = from_sig.to_fn_ptr();
272 let from_fn_pointer = TyKind::Function(from_sig.clone()).intern(&Interner);
273 let ok = self.coerce_from_safe_fn(from_fn_pointer, &from_sig, to_ty)?;
277 _ => self.table.try_unify(&from_ty, to_ty),
281 fn coerce_from_fn_pointer(
287 self.coerce_from_safe_fn(from_ty, from_f, to_ty)
290 fn coerce_from_safe_fn(
293 from_fn_ptr: &FnPointer,
296 if let TyKind::Function(to_fn_ptr) = to_ty.kind(&Interner) {
297 if let (chalk_ir::Safety::Safe, chalk_ir::Safety::Unsafe) =
298 (from_fn_ptr.sig.safety, to_fn_ptr.sig.safety)
301 TyKind::Function(safe_to_unsafe_fn_ty(from_fn_ptr.clone())).intern(&Interner);
302 return self.table.try_unify(&from_unsafe, to_ty);
305 self.table.try_unify(&from_ty, to_ty)
308 /// Attempts to coerce from the type of a non-capturing closure into a
309 /// function pointer.
310 fn coerce_closure_to_fn(
313 from_substs: &Substitution,
316 match to_ty.kind(&Interner) {
317 TyKind::Function(fn_ty) /* if from_substs is non-capturing (FIXME) */ => {
318 // We coerce the closure, which has fn type
319 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
321 // `fn(arg0,arg1,...) -> _`
323 // `unsafe fn(arg0,arg1,...) -> _`
324 let safety = fn_ty.sig.safety;
325 let pointer_ty = coerce_closure_fn_ty(from_substs, safety);
326 self.table.try_unify(&pointer_ty, to_ty)
328 _ => self.table.try_unify(&from_ty, to_ty),
332 /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>`
334 /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html
335 fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> InferResult {
336 // These 'if' statements require some explanation.
337 // The `CoerceUnsized` trait is special - it is only
338 // possible to write `impl CoerceUnsized<B> for A` where
339 // A and B have 'matching' fields. This rules out the following
340 // two types of blanket impls:
342 // `impl<T> CoerceUnsized<T> for SomeType`
343 // `impl<T> CoerceUnsized<SomeType> for T`
345 // Both of these trigger a special `CoerceUnsized`-related error (E0376)
347 // We can take advantage of this fact to avoid performing unecessary work.
348 // If either `source` or `target` is a type variable, then any applicable impl
349 // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
350 // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
353 // However, these are exactly the kinds of impls which are forbidden by
354 // the compiler! Therefore, we can be sure that coercion will always fail
355 // when either the source or target type is a type variable. This allows us
356 // to skip performing any trait selection, and immediately bail out.
357 if from_ty.is_ty_var() {
358 return Err(TypeError);
360 if to_ty.is_ty_var() {
361 return Err(TypeError);
364 // Handle reborrows before trying to solve `Source: CoerceUnsized<Target>`.
365 let coerce_from = match (from_ty.kind(&Interner), to_ty.kind(&Interner)) {
366 (TyKind::Ref(from_mt, _, from_inner), TyKind::Ref(to_mt, _, _)) => {
367 coerce_mutabilities(*from_mt, *to_mt)?;
369 let lt = static_lifetime();
370 TyKind::Ref(*to_mt, lt, from_inner.clone()).intern(&Interner)
372 (TyKind::Ref(from_mt, _, from_inner), TyKind::Raw(to_mt, _)) => {
373 coerce_mutabilities(*from_mt, *to_mt)?;
375 TyKind::Raw(*to_mt, from_inner.clone()).intern(&Interner)
377 _ => from_ty.clone(),
380 let krate = self.resolver.krate().unwrap();
381 let coerce_unsized_trait = match self.db.lang_item(krate, "coerce_unsized".into()) {
382 Some(LangItemTarget::TraitId(trait_)) => trait_,
383 _ => return Err(TypeError),
387 let b = TyBuilder::trait_ref(self.db, coerce_unsized_trait);
388 if b.remaining() != 2 {
389 // The CoerceUnsized trait should have two generic params: Self and T.
390 return Err(TypeError);
392 b.push(coerce_from).push(to_ty.clone()).build()
395 let goal: InEnvironment<DomainGoal> =
396 InEnvironment::new(&self.trait_env.env, trait_ref.cast(&Interner));
398 let canonicalized = self.canonicalize(goal);
400 // FIXME: rustc's coerce_unsized is more specialized -- it only tries to
401 // solve `CoerceUnsized` and `Unsize` goals at this point and leaves the
402 // rest for later. Also, there's some logic about sized type variables.
403 // Need to find out in what cases this is necessary
406 .trait_solve(krate, canonicalized.value.clone().cast(&Interner))
410 Solution::Unique(v) => {
411 canonicalized.apply_solution(
415 // FIXME handle constraints
416 value: v.value.subst,
420 // FIXME: should we accept ambiguous results here?
421 _ => return Err(TypeError),
424 Ok(InferOk { goals: Vec::new() })
428 fn coerce_closure_fn_ty(closure_substs: &Substitution, safety: chalk_ir::Safety) -> Ty {
429 let closure_sig = closure_substs.at(&Interner, 0).assert_ty_ref(&Interner).clone();
430 match closure_sig.kind(&Interner) {
431 TyKind::Function(fn_ty) => TyKind::Function(FnPointer {
432 num_binders: fn_ty.num_binders,
433 sig: FnSig { safety, ..fn_ty.sig },
434 substitution: fn_ty.substitution.clone(),
437 _ => TyKind::Error.intern(&Interner),
441 fn safe_to_unsafe_fn_ty(fn_ty: FnPointer) -> FnPointer {
443 num_binders: fn_ty.num_binders,
444 sig: FnSig { safety: chalk_ir::Safety::Unsafe, ..fn_ty.sig },
445 substitution: fn_ty.substitution,
449 fn coerce_mutabilities(from: Mutability, to: Mutability) -> Result<(), TypeError> {
451 (Mutability::Mut, Mutability::Mut)
452 | (Mutability::Mut, Mutability::Not)
453 | (Mutability::Not, Mutability::Not) => Ok(()),
454 (Mutability::Not, Mutability::Mut) => Err(TypeError),