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