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