aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src/ty/infer/coerce.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir/src/ty/infer/coerce.rs')
-rw-r--r--crates/ra_hir/src/ty/infer/coerce.rs336
1 files changed, 336 insertions, 0 deletions
diff --git a/crates/ra_hir/src/ty/infer/coerce.rs b/crates/ra_hir/src/ty/infer/coerce.rs
new file mode 100644
index 000000000..0429a9866
--- /dev/null
+++ b/crates/ra_hir/src/ty/infer/coerce.rs
@@ -0,0 +1,336 @@
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]`.
4//!
5//! See: https://doc.rust-lang.org/nomicon/coercions.html
6
7use rustc_hash::FxHashMap;
8
9use test_utils::tested_by;
10
11use super::{InferTy, InferenceContext, TypeVarValue};
12use crate::{
13 db::HirDatabase,
14 lang_item::LangItemTarget,
15 resolve::Resolver,
16 ty::{autoderef, Substs, Ty, TypeCtor, TypeWalk},
17 type_ref::Mutability,
18 Adt,
19};
20
21impl<'a, D: HirDatabase> InferenceContext<'a, D> {
22 /// Unify two types, but may coerce the first one to the second one
23 /// using "implicit coercion rules" if needed.
24 pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool {
25 let from_ty = self.resolve_ty_shallow(from_ty).into_owned();
26 let to_ty = self.resolve_ty_shallow(to_ty);
27 self.coerce_inner(from_ty, &to_ty)
28 }
29
30 /// Merge two types from different branches, with possible implicit coerce.
31 ///
32 /// Note that it is only possible that one type are coerced to another.
33 /// Coercing both types to another least upper bound type is not possible in rustc,
34 /// which will simply result in "incompatible types" error.
35 pub(super) fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty {
36 if self.coerce(ty1, ty2) {
37 ty2.clone()
38 } else if self.coerce(ty2, ty1) {
39 ty1.clone()
40 } else {
41 tested_by!(coerce_merge_fail_fallback);
42 // For incompatible types, we use the latter one as result
43 // to be better recovery for `if` without `else`.
44 ty2.clone()
45 }
46 }
47
48 pub(super) fn init_coerce_unsized_map(
49 db: &'a D,
50 resolver: &Resolver,
51 ) -> FxHashMap<(TypeCtor, TypeCtor), usize> {
52 let krate = resolver.krate().unwrap();
53 let impls = match db.lang_item(krate, "coerce_unsized".into()) {
54 Some(LangItemTarget::Trait(trait_)) => db.impls_for_trait(krate, trait_),
55 _ => return FxHashMap::default(),
56 };
57
58 impls
59 .iter()
60 .filter_map(|impl_block| {
61 // `CoerseUnsized` has one generic parameter for the target type.
62 let trait_ref = impl_block.target_trait_ref(db)?;
63 let cur_from_ty = trait_ref.substs.0.get(0)?;
64 let cur_to_ty = trait_ref.substs.0.get(1)?;
65
66 match (&cur_from_ty, cur_to_ty) {
67 (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => {
68 // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type.
69 // This works for smart-pointer-like coercion, which covers all impls from std.
70 st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| {
71 match (ty1, ty2) {
72 (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. })
73 if p1 != p2 =>
74 {
75 Some(((*ctor1, *ctor2), i))
76 }
77 _ => None,
78 }
79 })
80 }
81 _ => None,
82 }
83 })
84 .collect()
85 }
86
87 fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool {
88 match (&from_ty, to_ty) {
89 // Never type will make type variable to fallback to Never Type instead of Unknown.
90 (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => {
91 let var = self.new_maybe_never_type_var();
92 self.var_unification_table.union_value(*tv, TypeVarValue::Known(var));
93 return true;
94 }
95 (ty_app!(TypeCtor::Never), _) => return true,
96
97 // Trivial cases, this should go after `never` check to
98 // avoid infer result type to be never
99 _ => {
100 if self.unify_inner_trivial(&from_ty, &to_ty) {
101 return true;
102 }
103 }
104 }
105
106 // Pointer weakening and function to pointer
107 match (&mut from_ty, to_ty) {
108 // `*mut T`, `&mut T, `&T`` -> `*const T`
109 // `&mut T` -> `&T`
110 // `&mut T` -> `*mut T`
111 (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared)))
112 | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared)))
113 | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared)))
114 | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => {
115 *c1 = *c2;
116 }
117
118 // Illegal mutablity conversion
119 (
120 ty_app!(TypeCtor::RawPtr(Mutability::Shared)),
121 ty_app!(TypeCtor::RawPtr(Mutability::Mut)),
122 )
123 | (
124 ty_app!(TypeCtor::Ref(Mutability::Shared)),
125 ty_app!(TypeCtor::Ref(Mutability::Mut)),
126 ) => return false,
127
128 // `{function_type}` -> `fn()`
129 (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => {
130 match from_ty.callable_sig(self.db) {
131 None => return false,
132 Some(sig) => {
133 let num_args = sig.params_and_return.len() as u16 - 1;
134 from_ty =
135 Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return));
136 }
137 }
138 }
139
140 _ => {}
141 }
142
143 if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) {
144 return ret;
145 }
146
147 // Auto Deref if cannot coerce
148 match (&from_ty, to_ty) {
149 // FIXME: DerefMut
150 (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => {
151 self.unify_autoderef_behind_ref(&st1[0], &st2[0])
152 }
153
154 // Otherwise, normal unify
155 _ => self.unify(&from_ty, to_ty),
156 }
157 }
158
159 /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>`
160 ///
161 /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html
162 fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option<bool> {
163 let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) {
164 (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2),
165 _ => return None,
166 };
167
168 let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?;
169
170 // Check `Unsize` first
171 match self.check_unsize_and_coerce(
172 st1.0.get(coerce_generic_index)?,
173 st2.0.get(coerce_generic_index)?,
174 0,
175 ) {
176 Some(true) => {}
177 ret => return ret,
178 }
179
180 let ret = st1
181 .iter()
182 .zip(st2.iter())
183 .enumerate()
184 .filter(|&(idx, _)| idx != coerce_generic_index)
185 .all(|(_, (ty1, ty2))| self.unify(ty1, ty2));
186
187 Some(ret)
188 }
189
190 /// Check if `from_ty: Unsize<to_ty>`, and coerce to `to_ty` if it holds.
191 ///
192 /// It should not be directly called. It is only used by `try_coerce_unsized`.
193 ///
194 /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html
195 fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option<bool> {
196 if depth > 1000 {
197 panic!("Infinite recursion in coercion");
198 }
199
200 match (&from_ty, &to_ty) {
201 // `[T; N]` -> `[T]`
202 (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => {
203 Some(self.unify(&st1[0], &st2[0]))
204 }
205
206 // `T` -> `dyn Trait` when `T: Trait`
207 (_, Ty::Dyn(_)) => {
208 // FIXME: Check predicates
209 Some(true)
210 }
211
212 // `(..., T)` -> `(..., U)` when `T: Unsize<U>`
213 (
214 ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1),
215 ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2),
216 ) => {
217 if len1 != len2 || *len1 == 0 {
218 return None;
219 }
220
221 match self.check_unsize_and_coerce(
222 st1.last().unwrap(),
223 st2.last().unwrap(),
224 depth + 1,
225 ) {
226 Some(true) => {}
227 ret => return ret,
228 }
229
230 let ret = st1[..st1.len() - 1]
231 .iter()
232 .zip(&st2[..st2.len() - 1])
233 .all(|(ty1, ty2)| self.unify(ty1, ty2));
234
235 Some(ret)
236 }
237
238 // Foo<..., T, ...> is Unsize<Foo<..., U, ...>> if:
239 // - T: Unsize<U>
240 // - Foo is a struct
241 // - Only the last field of Foo has a type involving T
242 // - T is not part of the type of any other fields
243 // - Bar<T>: Unsize<Bar<U>>, if the last field of Foo has type Bar<T>
244 (
245 ty_app!(TypeCtor::Adt(Adt::Struct(struct1)), st1),
246 ty_app!(TypeCtor::Adt(Adt::Struct(struct2)), st2),
247 ) if struct1 == struct2 => {
248 let fields = struct1.fields(self.db);
249 let (last_field, prev_fields) = fields.split_last()?;
250
251 // Get the generic parameter involved in the last field.
252 let unsize_generic_index = {
253 let mut index = None;
254 let mut multiple_param = false;
255 last_field.ty(self.db).walk(&mut |ty| match ty {
256 &Ty::Param { idx, .. } => {
257 if index.is_none() {
258 index = Some(idx);
259 } else if Some(idx) != index {
260 multiple_param = true;
261 }
262 }
263 _ => {}
264 });
265
266 if multiple_param {
267 return None;
268 }
269 index?
270 };
271
272 // Check other fields do not involve it.
273 let mut multiple_used = false;
274 prev_fields.iter().for_each(|field| {
275 field.ty(self.db).walk(&mut |ty| match ty {
276 &Ty::Param { idx, .. } if idx == unsize_generic_index => {
277 multiple_used = true
278 }
279 _ => {}
280 })
281 });
282 if multiple_used {
283 return None;
284 }
285
286 let unsize_generic_index = unsize_generic_index as usize;
287
288 // Check `Unsize` first
289 match self.check_unsize_and_coerce(
290 st1.get(unsize_generic_index)?,
291 st2.get(unsize_generic_index)?,
292 depth + 1,
293 ) {
294 Some(true) => {}
295 ret => return ret,
296 }
297
298 // Then unify other parameters
299 let ret = st1
300 .iter()
301 .zip(st2.iter())
302 .enumerate()
303 .filter(|&(idx, _)| idx != unsize_generic_index)
304 .all(|(_, (ty1, ty2))| self.unify(ty1, ty2));
305
306 Some(ret)
307 }
308
309 _ => None,
310 }
311 }
312
313 /// Unify `from_ty` to `to_ty` with optional auto Deref
314 ///
315 /// Note that the parameters are already stripped the outer reference.
316 fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool {
317 let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone());
318 let to_ty = self.resolve_ty_shallow(&to_ty);
319 // FIXME: Auto DerefMut
320 for derefed_ty in
321 autoderef::autoderef(self.db, &self.resolver.clone(), canonicalized.value.clone())
322 {
323 let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value);
324 match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) {
325 // Stop when constructor matches.
326 (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => {
327 // It will not recurse to `coerce`.
328 return self.unify_substs(st1, st2, 0);
329 }
330 _ => {}
331 }
332 }
333
334 false
335 }
336}