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
7 use hir_def::{lang_item::LangItemTarget, resolver::Resolver, type_ref::Mutability, AdtId};
8 use rustc_hash::FxHashMap;
9 use test_utils::tested_by;
11 use crate::{autoderef, db::HirDatabase, Substs, Ty, TypeCtor, TypeWalk};
13 use super::{unify::TypeVarValue, InEnvironment, InferTy, InferenceContext};
15 impl<'a, D: HirDatabase> InferenceContext<'a, D> {
16 /// Unify two types, but may coerce the first one to the second one
17 /// using "implicit coercion rules" if needed.
18 pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool {
19 let from_ty = self.resolve_ty_shallow(from_ty).into_owned();
20 let to_ty = self.resolve_ty_shallow(to_ty);
21 self.coerce_inner(from_ty, &to_ty)
24 /// Merge two types from different branches, with possible implicit coerce.
26 /// Note that it is only possible that one type are coerced to another.
27 /// Coercing both types to another least upper bound type is not possible in rustc,
28 /// which will simply result in "incompatible types" error.
29 pub(super) fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty {
30 if self.coerce(ty1, ty2) {
32 } else if self.coerce(ty2, ty1) {
35 tested_by!(coerce_merge_fail_fallback);
36 // For incompatible types, we use the latter one as result
37 // to be better recovery for `if` without `else`.
42 pub(super) fn init_coerce_unsized_map(
45 ) -> FxHashMap<(TypeCtor, TypeCtor), usize> {
46 let krate = resolver.krate().unwrap();
47 let impls = match db.lang_item(krate.into(), "coerce_unsized".into()) {
48 Some(LangItemTarget::TraitId(trait_)) => {
49 db.impls_for_trait(krate.into(), trait_.into())
51 _ => return FxHashMap::default(),
56 .filter_map(|&impl_id| {
57 let trait_ref = db.impl_trait(impl_id)?;
59 // `CoerseUnsized` has one generic parameter for the target type.
60 let cur_from_ty = trait_ref.substs.0.get(0)?;
61 let cur_to_ty = trait_ref.substs.0.get(1)?;
63 match (&cur_from_ty, cur_to_ty) {
64 (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => {
65 // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type.
66 // This works for smart-pointer-like coercion, which covers all impls from std.
67 st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| {
69 (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. })
72 Some(((*ctor1, *ctor2), i))
84 fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool {
85 match (&from_ty, to_ty) {
86 // Never type will make type variable to fallback to Never Type instead of Unknown.
87 (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => {
88 let var = self.table.new_maybe_never_type_var();
89 self.table.var_unification_table.union_value(*tv, TypeVarValue::Known(var));
92 (ty_app!(TypeCtor::Never), _) => return true,
94 // Trivial cases, this should go after `never` check to
95 // avoid infer result type to be never
97 if self.table.unify_inner_trivial(&from_ty, &to_ty) {
103 // Pointer weakening and function to pointer
104 match (&mut from_ty, to_ty) {
105 // `*mut T`, `&mut T, `&T`` -> `*const T`
107 // `&mut T` -> `*mut T`
108 (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared)))
109 | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared)))
110 | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared)))
111 | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => {
115 // Illegal mutablity conversion
117 ty_app!(TypeCtor::RawPtr(Mutability::Shared)),
118 ty_app!(TypeCtor::RawPtr(Mutability::Mut)),
121 ty_app!(TypeCtor::Ref(Mutability::Shared)),
122 ty_app!(TypeCtor::Ref(Mutability::Mut)),
125 // `{function_type}` -> `fn()`
126 (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => {
127 match from_ty.callable_sig(self.db) {
128 None => return false,
130 let num_args = sig.params_and_return.len() as u16 - 1;
132 Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return));
137 (ty_app!(TypeCtor::Closure { .. }, params), ty_app!(TypeCtor::FnPtr { .. })) => {
138 from_ty = params[0].clone();
144 if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) {
148 // Auto Deref if cannot coerce
149 match (&from_ty, to_ty) {
151 (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => {
152 self.unify_autoderef_behind_ref(&st1[0], &st2[0])
155 // Otherwise, normal unify
156 _ => self.unify(&from_ty, to_ty),
160 /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>`
162 /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html
163 fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option<bool> {
164 let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) {
165 (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2),
169 let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?;
171 // Check `Unsize` first
172 match self.check_unsize_and_coerce(
173 st1.0.get(coerce_generic_index)?,
174 st2.0.get(coerce_generic_index)?,
185 .filter(|&(idx, _)| idx != coerce_generic_index)
186 .all(|(_, (ty1, ty2))| self.unify(ty1, ty2));
191 /// Check if `from_ty: Unsize<to_ty>`, and coerce to `to_ty` if it holds.
193 /// It should not be directly called. It is only used by `try_coerce_unsized`.
195 /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html
196 fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option<bool> {
198 panic!("Infinite recursion in coercion");
201 match (&from_ty, &to_ty) {
203 (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => {
204 Some(self.unify(&st1[0], &st2[0]))
207 // `T` -> `dyn Trait` when `T: Trait`
209 // FIXME: Check predicates
213 // `(..., T)` -> `(..., U)` when `T: Unsize<U>`
215 ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1),
216 ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2),
218 if len1 != len2 || *len1 == 0 {
222 match self.check_unsize_and_coerce(
231 let ret = st1[..st1.len() - 1]
233 .zip(&st2[..st2.len() - 1])
234 .all(|(ty1, ty2)| self.unify(ty1, ty2));
239 // Foo<..., T, ...> is Unsize<Foo<..., U, ...>> if:
242 // - Only the last field of Foo has a type involving T
243 // - T is not part of the type of any other fields
244 // - Bar<T>: Unsize<Bar<U>>, if the last field of Foo has type Bar<T>
246 ty_app!(TypeCtor::Adt(AdtId::StructId(struct1)), st1),
247 ty_app!(TypeCtor::Adt(AdtId::StructId(struct2)), st2),
248 ) if struct1 == struct2 => {
249 let field_tys = self.db.field_types((*struct1).into());
250 let struct_data = self.db.struct_data(*struct1);
252 let mut fields = struct_data.variant_data.fields().iter();
253 let (last_field_id, _data) = fields.next_back()?;
255 // Get the generic parameter involved in the last field.
256 let unsize_generic_index = {
257 let mut index = None;
258 let mut multiple_param = false;
259 field_tys[last_field_id].walk(&mut |ty| match ty {
260 &Ty::Param { idx, .. } => {
263 } else if Some(idx) != index {
264 multiple_param = true;
276 // Check other fields do not involve it.
277 let mut multiple_used = false;
278 fields.for_each(|(field_id, _data)| {
279 field_tys[field_id].walk(&mut |ty| match ty {
280 &Ty::Param { idx, .. } if idx == unsize_generic_index => {
290 let unsize_generic_index = unsize_generic_index as usize;
292 // Check `Unsize` first
293 match self.check_unsize_and_coerce(
294 st1.get(unsize_generic_index)?,
295 st2.get(unsize_generic_index)?,
302 // Then unify other parameters
307 .filter(|&(idx, _)| idx != unsize_generic_index)
308 .all(|(_, (ty1, ty2))| self.unify(ty1, ty2));
317 /// Unify `from_ty` to `to_ty` with optional auto Deref
319 /// Note that the parameters are already stripped the outer reference.
320 fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool {
321 let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone());
322 let to_ty = self.resolve_ty_shallow(&to_ty);
323 // FIXME: Auto DerefMut
324 for derefed_ty in autoderef::autoderef(
326 self.resolver.krate(),
328 value: canonicalized.value.clone(),
329 environment: self.trait_env.clone(),
332 let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value);
333 match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) {
334 // Stop when constructor matches.
335 (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => {
336 // It will not recurse to `coerce`.
337 return self.table.unify_substs(st1, st2, 0);
340 if self.table.unify_inner_trivial(&derefed_ty, &to_ty) {