aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src/ty/infer
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2019-11-27 14:46:02 +0000
committerAleksey Kladov <[email protected]>2019-11-27 18:16:00 +0000
commita87579500a2c35597071efd0ad6983927f0c1815 (patch)
tree9805b3dcbf8d767b2fc0623f42794068f3660d44 /crates/ra_hir/src/ty/infer
parent368653081558ab389c6543d6b5027859e26beb3b (diff)
Move Ty
Diffstat (limited to 'crates/ra_hir/src/ty/infer')
-rw-r--r--crates/ra_hir/src/ty/infer/coerce.rs357
-rw-r--r--crates/ra_hir/src/ty/infer/expr.rs689
-rw-r--r--crates/ra_hir/src/ty/infer/pat.rs189
-rw-r--r--crates/ra_hir/src/ty/infer/path.rs273
-rw-r--r--crates/ra_hir/src/ty/infer/unify.rs166
5 files changed, 0 insertions, 1674 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}
diff --git a/crates/ra_hir/src/ty/infer/expr.rs b/crates/ra_hir/src/ty/infer/expr.rs
deleted file mode 100644
index f9ededa23..000000000
--- a/crates/ra_hir/src/ty/infer/expr.rs
+++ /dev/null
@@ -1,689 +0,0 @@
1//! Type inference for expressions.
2
3use std::iter::{repeat, repeat_with};
4use std::sync::Arc;
5
6use hir_def::{
7 builtin_type::Signedness,
8 expr::{Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp},
9 generics::GenericParams,
10 path::{GenericArg, GenericArgs},
11 resolver::resolver_for_expr,
12 AdtId, ContainerId, Lookup, StructFieldId,
13};
14use hir_expand::name::{self, Name};
15
16use crate::{
17 db::HirDatabase,
18 ty::{
19 autoderef, method_resolution, op, traits::InEnvironment, utils::variant_data, CallableDef,
20 InferTy, IntTy, Mutability, Obligation, ProjectionPredicate, ProjectionTy, Substs,
21 TraitRef, Ty, TypeCtor, TypeWalk, Uncertain,
22 },
23};
24
25use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch};
26
27impl<'a, D: HirDatabase> InferenceContext<'a, D> {
28 pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
29 let ty = self.infer_expr_inner(tgt_expr, expected);
30 let could_unify = self.unify(&ty, &expected.ty);
31 if !could_unify {
32 self.result.type_mismatches.insert(
33 tgt_expr,
34 TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() },
35 );
36 }
37 let ty = self.resolve_ty_as_possible(&mut vec![], ty);
38 ty
39 }
40
41 /// Infer type of expression with possibly implicit coerce to the expected type.
42 /// Return the type after possible coercion.
43 fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty {
44 let ty = self.infer_expr_inner(expr, &expected);
45 let ty = if !self.coerce(&ty, &expected.ty) {
46 self.result
47 .type_mismatches
48 .insert(expr, TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() });
49 // Return actual type when type mismatch.
50 // This is needed for diagnostic when return type mismatch.
51 ty
52 } else if expected.ty == Ty::Unknown {
53 ty
54 } else {
55 expected.ty.clone()
56 };
57
58 self.resolve_ty_as_possible(&mut vec![], ty)
59 }
60
61 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
62 let body = Arc::clone(&self.body); // avoid borrow checker problem
63 let ty = match &body[tgt_expr] {
64 Expr::Missing => Ty::Unknown,
65 Expr::If { condition, then_branch, else_branch } => {
66 // if let is desugared to match, so this is always simple if
67 self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool)));
68
69 let then_ty = self.infer_expr_inner(*then_branch, &expected);
70 let else_ty = match else_branch {
71 Some(else_branch) => self.infer_expr_inner(*else_branch, &expected),
72 None => Ty::unit(),
73 };
74
75 self.coerce_merge_branch(&then_ty, &else_ty)
76 }
77 Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected),
78 Expr::TryBlock { body } => {
79 let _inner = self.infer_expr(*body, expected);
80 // FIXME should be std::result::Result<{inner}, _>
81 Ty::Unknown
82 }
83 Expr::Loop { body } => {
84 self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
85 // FIXME handle break with value
86 Ty::simple(TypeCtor::Never)
87 }
88 Expr::While { condition, body } => {
89 // while let is desugared to a match loop, so this is always simple while
90 self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool)));
91 self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
92 Ty::unit()
93 }
94 Expr::For { iterable, body, pat } => {
95 let iterable_ty = self.infer_expr(*iterable, &Expectation::none());
96
97 let pat_ty = match self.resolve_into_iter_item() {
98 Some(into_iter_item_alias) => {
99 let pat_ty = self.new_type_var();
100 let projection = ProjectionPredicate {
101 ty: pat_ty.clone(),
102 projection_ty: ProjectionTy {
103 associated_ty: into_iter_item_alias,
104 parameters: Substs::single(iterable_ty),
105 },
106 };
107 self.obligations.push(Obligation::Projection(projection));
108 self.resolve_ty_as_possible(&mut vec![], pat_ty)
109 }
110 None => Ty::Unknown,
111 };
112
113 self.infer_pat(*pat, &pat_ty, BindingMode::default());
114 self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
115 Ty::unit()
116 }
117 Expr::Lambda { body, args, arg_types } => {
118 assert_eq!(args.len(), arg_types.len());
119
120 let mut sig_tys = Vec::new();
121
122 for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) {
123 let expected = if let Some(type_ref) = arg_type {
124 self.make_ty(type_ref)
125 } else {
126 Ty::Unknown
127 };
128 let arg_ty = self.infer_pat(*arg_pat, &expected, BindingMode::default());
129 sig_tys.push(arg_ty);
130 }
131
132 // add return type
133 let ret_ty = self.new_type_var();
134 sig_tys.push(ret_ty.clone());
135 let sig_ty = Ty::apply(
136 TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 },
137 Substs(sig_tys.into()),
138 );
139 let closure_ty = Ty::apply_one(
140 TypeCtor::Closure { def: self.owner.into(), expr: tgt_expr },
141 sig_ty,
142 );
143
144 // Eagerly try to relate the closure type with the expected
145 // type, otherwise we often won't have enough information to
146 // infer the body.
147 self.coerce(&closure_ty, &expected.ty);
148
149 self.infer_expr(*body, &Expectation::has_type(ret_ty));
150 closure_ty
151 }
152 Expr::Call { callee, args } => {
153 let callee_ty = self.infer_expr(*callee, &Expectation::none());
154 let (param_tys, ret_ty) = match callee_ty.callable_sig(self.db) {
155 Some(sig) => (sig.params().to_vec(), sig.ret().clone()),
156 None => {
157 // Not callable
158 // FIXME: report an error
159 (Vec::new(), Ty::Unknown)
160 }
161 };
162 self.register_obligations_for_call(&callee_ty);
163 self.check_call_arguments(args, &param_tys);
164 let ret_ty = self.normalize_associated_types_in(ret_ty);
165 ret_ty
166 }
167 Expr::MethodCall { receiver, args, method_name, generic_args } => self
168 .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()),
169 Expr::Match { expr, arms } => {
170 let input_ty = self.infer_expr(*expr, &Expectation::none());
171
172 let mut result_ty = self.new_maybe_never_type_var();
173
174 for arm in arms {
175 for &pat in &arm.pats {
176 let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default());
177 }
178 if let Some(guard_expr) = arm.guard {
179 self.infer_expr(
180 guard_expr,
181 &Expectation::has_type(Ty::simple(TypeCtor::Bool)),
182 );
183 }
184
185 let arm_ty = self.infer_expr_inner(arm.expr, &expected);
186 result_ty = self.coerce_merge_branch(&result_ty, &arm_ty);
187 }
188
189 result_ty
190 }
191 Expr::Path(p) => {
192 // FIXME this could be more efficient...
193 let resolver = resolver_for_expr(self.db, self.owner.into(), tgt_expr);
194 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown)
195 }
196 Expr::Continue => Ty::simple(TypeCtor::Never),
197 Expr::Break { expr } => {
198 if let Some(expr) = expr {
199 // FIXME handle break with value
200 self.infer_expr(*expr, &Expectation::none());
201 }
202 Ty::simple(TypeCtor::Never)
203 }
204 Expr::Return { expr } => {
205 if let Some(expr) = expr {
206 self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone()));
207 }
208 Ty::simple(TypeCtor::Never)
209 }
210 Expr::RecordLit { path, fields, spread } => {
211 let (ty, def_id) = self.resolve_variant(path.as_ref());
212 if let Some(variant) = def_id {
213 self.write_variant_resolution(tgt_expr.into(), variant);
214 }
215
216 self.unify(&ty, &expected.ty);
217
218 let substs = ty.substs().unwrap_or_else(Substs::empty);
219 let field_types =
220 def_id.map(|it| self.db.field_types(it.into())).unwrap_or_default();
221 let variant_data = def_id.map(|it| variant_data(self.db, it));
222 for (field_idx, field) in fields.iter().enumerate() {
223 let field_def =
224 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
225 Some(local_id) => {
226 Some(StructFieldId { parent: def_id.unwrap(), local_id })
227 }
228 None => {
229 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
230 expr: tgt_expr,
231 field: field_idx,
232 });
233 None
234 }
235 });
236 if let Some(field_def) = field_def {
237 self.result.record_field_resolutions.insert(field.expr, field_def);
238 }
239 let field_ty = field_def
240 .map_or(Ty::Unknown, |it| field_types[it.local_id].clone())
241 .subst(&substs);
242 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
243 }
244 if let Some(expr) = spread {
245 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
246 }
247 ty
248 }
249 Expr::Field { expr, name } => {
250 let receiver_ty = self.infer_expr(*expr, &Expectation::none());
251 let canonicalized = self.canonicalizer().canonicalize_ty(receiver_ty);
252 let ty = autoderef::autoderef(
253 self.db,
254 self.resolver.krate(),
255 InEnvironment {
256 value: canonicalized.value.clone(),
257 environment: self.trait_env.clone(),
258 },
259 )
260 .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) {
261 Ty::Apply(a_ty) => match a_ty.ctor {
262 TypeCtor::Tuple { .. } => name
263 .as_tuple_index()
264 .and_then(|idx| a_ty.parameters.0.get(idx).cloned()),
265 TypeCtor::Adt(AdtId::StructId(s)) => {
266 self.db.struct_data(s).variant_data.field(name).map(|local_id| {
267 let field = StructFieldId { parent: s.into(), local_id }.into();
268 self.write_field_resolution(tgt_expr, field);
269 self.db.field_types(s.into())[field.local_id]
270 .clone()
271 .subst(&a_ty.parameters)
272 })
273 }
274 // FIXME:
275 TypeCtor::Adt(AdtId::UnionId(_)) => None,
276 _ => None,
277 },
278 _ => None,
279 })
280 .unwrap_or(Ty::Unknown);
281 let ty = self.insert_type_vars(ty);
282 self.normalize_associated_types_in(ty)
283 }
284 Expr::Await { expr } => {
285 let inner_ty = self.infer_expr(*expr, &Expectation::none());
286 let ty = match self.resolve_future_future_output() {
287 Some(future_future_output_alias) => {
288 let ty = self.new_type_var();
289 let projection = ProjectionPredicate {
290 ty: ty.clone(),
291 projection_ty: ProjectionTy {
292 associated_ty: future_future_output_alias,
293 parameters: Substs::single(inner_ty),
294 },
295 };
296 self.obligations.push(Obligation::Projection(projection));
297 self.resolve_ty_as_possible(&mut vec![], ty)
298 }
299 None => Ty::Unknown,
300 };
301 ty
302 }
303 Expr::Try { expr } => {
304 let inner_ty = self.infer_expr(*expr, &Expectation::none());
305 let ty = match self.resolve_ops_try_ok() {
306 Some(ops_try_ok_alias) => {
307 let ty = self.new_type_var();
308 let projection = ProjectionPredicate {
309 ty: ty.clone(),
310 projection_ty: ProjectionTy {
311 associated_ty: ops_try_ok_alias,
312 parameters: Substs::single(inner_ty),
313 },
314 };
315 self.obligations.push(Obligation::Projection(projection));
316 self.resolve_ty_as_possible(&mut vec![], ty)
317 }
318 None => Ty::Unknown,
319 };
320 ty
321 }
322 Expr::Cast { expr, type_ref } => {
323 let _inner_ty = self.infer_expr(*expr, &Expectation::none());
324 let cast_ty = self.make_ty(type_ref);
325 // FIXME check the cast...
326 cast_ty
327 }
328 Expr::Ref { expr, mutability } => {
329 let expectation =
330 if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() {
331 if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared {
332 // FIXME: throw type error - expected mut reference but found shared ref,
333 // which cannot be coerced
334 }
335 Expectation::has_type(Ty::clone(exp_inner))
336 } else {
337 Expectation::none()
338 };
339 // FIXME reference coercions etc.
340 let inner_ty = self.infer_expr(*expr, &expectation);
341 Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty)
342 }
343 Expr::Box { expr } => {
344 let inner_ty = self.infer_expr(*expr, &Expectation::none());
345 if let Some(box_) = self.resolve_boxed_box() {
346 Ty::apply_one(TypeCtor::Adt(box_), inner_ty)
347 } else {
348 Ty::Unknown
349 }
350 }
351 Expr::UnaryOp { expr, op } => {
352 let inner_ty = self.infer_expr(*expr, &Expectation::none());
353 match op {
354 UnaryOp::Deref => match self.resolver.krate() {
355 Some(krate) => {
356 let canonicalized = self.canonicalizer().canonicalize_ty(inner_ty);
357 match autoderef::deref(
358 self.db,
359 krate,
360 InEnvironment {
361 value: &canonicalized.value,
362 environment: self.trait_env.clone(),
363 },
364 ) {
365 Some(derefed_ty) => {
366 canonicalized.decanonicalize_ty(derefed_ty.value)
367 }
368 None => Ty::Unknown,
369 }
370 }
371 None => Ty::Unknown,
372 },
373 UnaryOp::Neg => {
374 match &inner_ty {
375 Ty::Apply(a_ty) => match a_ty.ctor {
376 TypeCtor::Int(Uncertain::Unknown)
377 | TypeCtor::Int(Uncertain::Known(IntTy {
378 signedness: Signedness::Signed,
379 ..
380 }))
381 | TypeCtor::Float(..) => inner_ty,
382 _ => Ty::Unknown,
383 },
384 Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => {
385 inner_ty
386 }
387 // FIXME: resolve ops::Neg trait
388 _ => Ty::Unknown,
389 }
390 }
391 UnaryOp::Not => {
392 match &inner_ty {
393 Ty::Apply(a_ty) => match a_ty.ctor {
394 TypeCtor::Bool | TypeCtor::Int(_) => inner_ty,
395 _ => Ty::Unknown,
396 },
397 Ty::Infer(InferTy::IntVar(..)) => inner_ty,
398 // FIXME: resolve ops::Not trait for inner_ty
399 _ => Ty::Unknown,
400 }
401 }
402 }
403 }
404 Expr::BinaryOp { lhs, rhs, op } => match op {
405 Some(op) => {
406 let lhs_expectation = match op {
407 BinaryOp::LogicOp(..) => Expectation::has_type(Ty::simple(TypeCtor::Bool)),
408 _ => Expectation::none(),
409 };
410 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
411 // FIXME: find implementation of trait corresponding to operation
412 // symbol and resolve associated `Output` type
413 let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty);
414 let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation));
415
416 // FIXME: similar as above, return ty is often associated trait type
417 op::binary_op_return_ty(*op, rhs_ty)
418 }
419 _ => Ty::Unknown,
420 },
421 Expr::Index { base, index } => {
422 let _base_ty = self.infer_expr(*base, &Expectation::none());
423 let _index_ty = self.infer_expr(*index, &Expectation::none());
424 // FIXME: use `std::ops::Index::Output` to figure out the real return type
425 Ty::Unknown
426 }
427 Expr::Tuple { exprs } => {
428 let mut tys = match &expected.ty {
429 ty_app!(TypeCtor::Tuple { .. }, st) => st
430 .iter()
431 .cloned()
432 .chain(repeat_with(|| self.new_type_var()))
433 .take(exprs.len())
434 .collect::<Vec<_>>(),
435 _ => (0..exprs.len()).map(|_| self.new_type_var()).collect(),
436 };
437
438 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
439 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
440 }
441
442 Ty::apply(TypeCtor::Tuple { cardinality: tys.len() as u16 }, Substs(tys.into()))
443 }
444 Expr::Array(array) => {
445 let elem_ty = match &expected.ty {
446 ty_app!(TypeCtor::Array, st) | ty_app!(TypeCtor::Slice, st) => {
447 st.as_single().clone()
448 }
449 _ => self.new_type_var(),
450 };
451
452 match array {
453 Array::ElementList(items) => {
454 for expr in items.iter() {
455 self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone()));
456 }
457 }
458 Array::Repeat { initializer, repeat } => {
459 self.infer_expr_coerce(
460 *initializer,
461 &Expectation::has_type(elem_ty.clone()),
462 );
463 self.infer_expr(
464 *repeat,
465 &Expectation::has_type(Ty::simple(TypeCtor::Int(Uncertain::Known(
466 IntTy::usize(),
467 )))),
468 );
469 }
470 }
471
472 Ty::apply_one(TypeCtor::Array, elem_ty)
473 }
474 Expr::Literal(lit) => match lit {
475 Literal::Bool(..) => Ty::simple(TypeCtor::Bool),
476 Literal::String(..) => {
477 Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str))
478 }
479 Literal::ByteString(..) => {
480 let byte_type = Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::u8())));
481 let slice_type = Ty::apply_one(TypeCtor::Slice, byte_type);
482 Ty::apply_one(TypeCtor::Ref(Mutability::Shared), slice_type)
483 }
484 Literal::Char(..) => Ty::simple(TypeCtor::Char),
485 Literal::Int(_v, ty) => Ty::simple(TypeCtor::Int((*ty).into())),
486 Literal::Float(_v, ty) => Ty::simple(TypeCtor::Float((*ty).into())),
487 },
488 };
489 // use a new type variable if we got Ty::Unknown here
490 let ty = self.insert_type_vars_shallow(ty);
491 let ty = self.resolve_ty_as_possible(&mut vec![], ty);
492 self.write_expr_ty(tgt_expr, ty.clone());
493 ty
494 }
495
496 fn infer_block(
497 &mut self,
498 statements: &[Statement],
499 tail: Option<ExprId>,
500 expected: &Expectation,
501 ) -> Ty {
502 let mut diverges = false;
503 for stmt in statements {
504 match stmt {
505 Statement::Let { pat, type_ref, initializer } => {
506 let decl_ty =
507 type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown);
508
509 // Always use the declared type when specified
510 let mut ty = decl_ty.clone();
511
512 if let Some(expr) = initializer {
513 let actual_ty =
514 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
515 if decl_ty == Ty::Unknown {
516 ty = actual_ty;
517 }
518 }
519
520 let ty = self.resolve_ty_as_possible(&mut vec![], ty);
521 self.infer_pat(*pat, &ty, BindingMode::default());
522 }
523 Statement::Expr(expr) => {
524 if let ty_app!(TypeCtor::Never) = self.infer_expr(*expr, &Expectation::none()) {
525 diverges = true;
526 }
527 }
528 }
529 }
530
531 let ty = if let Some(expr) = tail {
532 self.infer_expr_coerce(expr, expected)
533 } else {
534 self.coerce(&Ty::unit(), &expected.ty);
535 Ty::unit()
536 };
537 if diverges {
538 Ty::simple(TypeCtor::Never)
539 } else {
540 ty
541 }
542 }
543
544 fn infer_method_call(
545 &mut self,
546 tgt_expr: ExprId,
547 receiver: ExprId,
548 args: &[ExprId],
549 method_name: &Name,
550 generic_args: Option<&GenericArgs>,
551 ) -> Ty {
552 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
553 let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone());
554 let resolved = method_resolution::lookup_method(
555 &canonicalized_receiver.value,
556 self.db,
557 method_name,
558 &self.resolver,
559 );
560 let (derefed_receiver_ty, method_ty, def_generics) = match resolved {
561 Some((ty, func)) => {
562 let ty = canonicalized_receiver.decanonicalize_ty(ty);
563 self.write_method_resolution(tgt_expr, func);
564 (ty, self.db.value_ty(func.into()), Some(self.db.generic_params(func.into())))
565 }
566 None => (receiver_ty, Ty::Unknown, None),
567 };
568 let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty);
569 let method_ty = method_ty.apply_substs(substs);
570 let method_ty = self.insert_type_vars(method_ty);
571 self.register_obligations_for_call(&method_ty);
572 let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
573 Some(sig) => {
574 if !sig.params().is_empty() {
575 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
576 } else {
577 (Ty::Unknown, Vec::new(), sig.ret().clone())
578 }
579 }
580 None => (Ty::Unknown, Vec::new(), Ty::Unknown),
581 };
582 // Apply autoref so the below unification works correctly
583 // FIXME: return correct autorefs from lookup_method
584 let actual_receiver_ty = match expected_receiver_ty.as_reference() {
585 Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty),
586 _ => derefed_receiver_ty,
587 };
588 self.unify(&expected_receiver_ty, &actual_receiver_ty);
589
590 self.check_call_arguments(args, &param_tys);
591 let ret_ty = self.normalize_associated_types_in(ret_ty);
592 ret_ty
593 }
594
595 fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) {
596 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
597 // We do this in a pretty awful way: first we type-check any arguments
598 // that are not closures, then we type-check the closures. This is so
599 // that we have more information about the types of arguments when we
600 // type-check the functions. This isn't really the right way to do this.
601 for &check_closures in &[false, true] {
602 let param_iter = param_tys.iter().cloned().chain(repeat(Ty::Unknown));
603 for (&arg, param_ty) in args.iter().zip(param_iter) {
604 let is_closure = match &self.body[arg] {
605 Expr::Lambda { .. } => true,
606 _ => false,
607 };
608
609 if is_closure != check_closures {
610 continue;
611 }
612
613 let param_ty = self.normalize_associated_types_in(param_ty);
614 self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone()));
615 }
616 }
617 }
618
619 fn substs_for_method_call(
620 &mut self,
621 def_generics: Option<Arc<GenericParams>>,
622 generic_args: Option<&GenericArgs>,
623 receiver_ty: &Ty,
624 ) -> Substs {
625 let (parent_param_count, param_count) =
626 def_generics.as_ref().map_or((0, 0), |g| (g.count_parent_params(), g.params.len()));
627 let mut substs = Vec::with_capacity(parent_param_count + param_count);
628 // Parent arguments are unknown, except for the receiver type
629 if let Some(parent_generics) = def_generics.and_then(|p| p.parent_params.clone()) {
630 for param in &parent_generics.params {
631 if param.name == name::SELF_TYPE {
632 substs.push(receiver_ty.clone());
633 } else {
634 substs.push(Ty::Unknown);
635 }
636 }
637 }
638 // handle provided type arguments
639 if let Some(generic_args) = generic_args {
640 // if args are provided, it should be all of them, but we can't rely on that
641 for arg in generic_args.args.iter().take(param_count) {
642 match arg {
643 GenericArg::Type(type_ref) => {
644 let ty = self.make_ty(type_ref);
645 substs.push(ty);
646 }
647 }
648 }
649 };
650 let supplied_params = substs.len();
651 for _ in supplied_params..parent_param_count + param_count {
652 substs.push(Ty::Unknown);
653 }
654 assert_eq!(substs.len(), parent_param_count + param_count);
655 Substs(substs.into())
656 }
657
658 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
659 if let Ty::Apply(a_ty) = callable_ty {
660 if let TypeCtor::FnDef(def) = a_ty.ctor {
661 let generic_predicates = self.db.generic_predicates(def.into());
662 for predicate in generic_predicates.iter() {
663 let predicate = predicate.clone().subst(&a_ty.parameters);
664 if let Some(obligation) = Obligation::from_predicate(predicate) {
665 self.obligations.push(obligation);
666 }
667 }
668 // add obligation for trait implementation, if this is a trait method
669 match def {
670 CallableDef::FunctionId(f) => {
671 if let ContainerId::TraitId(trait_) = f.lookup(self.db).container {
672 // construct a TraitDef
673 let substs = a_ty.parameters.prefix(
674 self.db
675 .generic_params(trait_.into())
676 .count_params_including_parent(),
677 );
678 self.obligations.push(Obligation::Trait(TraitRef {
679 trait_: trait_.into(),
680 substs,
681 }));
682 }
683 }
684 CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => {}
685 }
686 }
687 }
688 }
689}
diff --git a/crates/ra_hir/src/ty/infer/pat.rs b/crates/ra_hir/src/ty/infer/pat.rs
deleted file mode 100644
index a14774607..000000000
--- a/crates/ra_hir/src/ty/infer/pat.rs
+++ /dev/null
@@ -1,189 +0,0 @@
1//! Type inference for patterns.
2
3use std::iter::repeat;
4use std::sync::Arc;
5
6use hir_def::{
7 expr::{BindingAnnotation, Pat, PatId, RecordFieldPat},
8 path::Path,
9 type_ref::Mutability,
10};
11use hir_expand::name::Name;
12use test_utils::tested_by;
13
14use super::{BindingMode, InferenceContext};
15use crate::{
16 db::HirDatabase,
17 ty::{utils::variant_data, Substs, Ty, TypeCtor, TypeWalk},
18};
19
20impl<'a, D: HirDatabase> InferenceContext<'a, D> {
21 fn infer_tuple_struct_pat(
22 &mut self,
23 path: Option<&Path>,
24 subpats: &[PatId],
25 expected: &Ty,
26 default_bm: BindingMode,
27 ) -> Ty {
28 let (ty, def) = self.resolve_variant(path);
29 let var_data = def.map(|it| variant_data(self.db, it));
30 self.unify(&ty, expected);
31
32 let substs = ty.substs().unwrap_or_else(Substs::empty);
33
34 let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default();
35
36 for (i, &subpat) in subpats.iter().enumerate() {
37 let expected_ty = var_data
38 .as_ref()
39 .and_then(|d| d.field(&Name::new_tuple_field(i)))
40 .map_or(Ty::Unknown, |field| field_tys[field].clone())
41 .subst(&substs);
42 let expected_ty = self.normalize_associated_types_in(expected_ty);
43 self.infer_pat(subpat, &expected_ty, default_bm);
44 }
45
46 ty
47 }
48
49 fn infer_record_pat(
50 &mut self,
51 path: Option<&Path>,
52 subpats: &[RecordFieldPat],
53 expected: &Ty,
54 default_bm: BindingMode,
55 id: PatId,
56 ) -> Ty {
57 let (ty, def) = self.resolve_variant(path);
58 let var_data = def.map(|it| variant_data(self.db, it));
59 if let Some(variant) = def {
60 self.write_variant_resolution(id.into(), variant);
61 }
62
63 self.unify(&ty, expected);
64
65 let substs = ty.substs().unwrap_or_else(Substs::empty);
66
67 let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default();
68 for subpat in subpats {
69 let matching_field = var_data.as_ref().and_then(|it| it.field(&subpat.name));
70 let expected_ty =
71 matching_field.map_or(Ty::Unknown, |field| field_tys[field].clone()).subst(&substs);
72 let expected_ty = self.normalize_associated_types_in(expected_ty);
73 self.infer_pat(subpat.pat, &expected_ty, default_bm);
74 }
75
76 ty
77 }
78
79 pub(super) fn infer_pat(
80 &mut self,
81 pat: PatId,
82 mut expected: &Ty,
83 mut default_bm: BindingMode,
84 ) -> Ty {
85 let body = Arc::clone(&self.body); // avoid borrow checker problem
86
87 let is_non_ref_pat = match &body[pat] {
88 Pat::Tuple(..)
89 | Pat::TupleStruct { .. }
90 | Pat::Record { .. }
91 | Pat::Range { .. }
92 | Pat::Slice { .. } => true,
93 // FIXME: Path/Lit might actually evaluate to ref, but inference is unimplemented.
94 Pat::Path(..) | Pat::Lit(..) => true,
95 Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false,
96 };
97 if is_non_ref_pat {
98 while let Some((inner, mutability)) = expected.as_reference() {
99 expected = inner;
100 default_bm = match default_bm {
101 BindingMode::Move => BindingMode::Ref(mutability),
102 BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared),
103 BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability),
104 }
105 }
106 } else if let Pat::Ref { .. } = &body[pat] {
107 tested_by!(match_ergonomics_ref);
108 // When you encounter a `&pat` pattern, reset to Move.
109 // This is so that `w` is by value: `let (_, &w) = &(1, &2);`
110 default_bm = BindingMode::Move;
111 }
112
113 // Lose mutability.
114 let default_bm = default_bm;
115 let expected = expected;
116
117 let ty = match &body[pat] {
118 Pat::Tuple(ref args) => {
119 let expectations = match expected.as_tuple() {
120 Some(parameters) => &*parameters.0,
121 _ => &[],
122 };
123 let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown));
124
125 let inner_tys = args
126 .iter()
127 .zip(expectations_iter)
128 .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm))
129 .collect();
130
131 Ty::apply(TypeCtor::Tuple { cardinality: args.len() as u16 }, Substs(inner_tys))
132 }
133 Pat::Ref { pat, mutability } => {
134 let expectation = match expected.as_reference() {
135 Some((inner_ty, exp_mut)) => {
136 if *mutability != exp_mut {
137 // FIXME: emit type error?
138 }
139 inner_ty
140 }
141 _ => &Ty::Unknown,
142 };
143 let subty = self.infer_pat(*pat, expectation, default_bm);
144 Ty::apply_one(TypeCtor::Ref(*mutability), subty)
145 }
146 Pat::TupleStruct { path: p, args: subpats } => {
147 self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm)
148 }
149 Pat::Record { path: p, args: fields } => {
150 self.infer_record_pat(p.as_ref(), fields, expected, default_bm, pat)
151 }
152 Pat::Path(path) => {
153 // FIXME use correct resolver for the surrounding expression
154 let resolver = self.resolver.clone();
155 self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown)
156 }
157 Pat::Bind { mode, name: _, subpat } => {
158 let mode = if mode == &BindingAnnotation::Unannotated {
159 default_bm
160 } else {
161 BindingMode::convert(*mode)
162 };
163 let inner_ty = if let Some(subpat) = subpat {
164 self.infer_pat(*subpat, expected, default_bm)
165 } else {
166 expected.clone()
167 };
168 let inner_ty = self.insert_type_vars_shallow(inner_ty);
169
170 let bound_ty = match mode {
171 BindingMode::Ref(mutability) => {
172 Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone())
173 }
174 BindingMode::Move => inner_ty.clone(),
175 };
176 let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty);
177 self.write_pat_ty(pat, bound_ty);
178 return inner_ty;
179 }
180 _ => Ty::Unknown,
181 };
182 // use a new type variable if we got Ty::Unknown here
183 let ty = self.insert_type_vars_shallow(ty);
184 self.unify(&ty, expected);
185 let ty = self.resolve_ty_as_possible(&mut vec![], ty);
186 self.write_pat_ty(pat, ty.clone());
187 ty
188 }
189}
diff --git a/crates/ra_hir/src/ty/infer/path.rs b/crates/ra_hir/src/ty/infer/path.rs
deleted file mode 100644
index 09ff79728..000000000
--- a/crates/ra_hir/src/ty/infer/path.rs
+++ /dev/null
@@ -1,273 +0,0 @@
1//! Path expression resolution.
2
3use hir_def::{
4 path::{Path, PathSegment},
5 resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs},
6 AssocItemId, ContainerId, Lookup,
7};
8use hir_expand::name::Name;
9
10use crate::{
11 db::HirDatabase,
12 ty::{method_resolution, Substs, Ty, TypeWalk, ValueTyDefId},
13};
14
15use super::{ExprOrPatId, InferenceContext, TraitRef};
16
17impl<'a, D: HirDatabase> InferenceContext<'a, D> {
18 pub(super) fn infer_path(
19 &mut self,
20 resolver: &Resolver,
21 path: &Path,
22 id: ExprOrPatId,
23 ) -> Option<Ty> {
24 let ty = self.resolve_value_path(resolver, path, id)?;
25 let ty = self.insert_type_vars(ty);
26 let ty = self.normalize_associated_types_in(ty);
27 Some(ty)
28 }
29
30 fn resolve_value_path(
31 &mut self,
32 resolver: &Resolver,
33 path: &Path,
34 id: ExprOrPatId,
35 ) -> Option<Ty> {
36 let (value, self_subst) = if let crate::PathKind::Type(type_ref) = &path.kind {
37 if path.segments.is_empty() {
38 // This can't actually happen syntax-wise
39 return None;
40 }
41 let ty = self.make_ty(type_ref);
42 let remaining_segments_for_ty = &path.segments[..path.segments.len() - 1];
43 let ty = Ty::from_type_relative_path(self.db, resolver, ty, remaining_segments_for_ty);
44 self.resolve_ty_assoc_item(
45 ty,
46 &path.segments.last().expect("path had at least one segment").name,
47 id,
48 )?
49 } else {
50 let value_or_partial = resolver.resolve_path_in_value_ns(self.db, &path)?;
51
52 match value_or_partial {
53 ResolveValueResult::ValueNs(it) => (it, None),
54 ResolveValueResult::Partial(def, remaining_index) => {
55 self.resolve_assoc_item(def, path, remaining_index, id)?
56 }
57 }
58 };
59
60 let typable: ValueTyDefId = match value {
61 ValueNs::LocalBinding(pat) => {
62 let ty = self.result.type_of_pat.get(pat)?.clone();
63 let ty = self.resolve_ty_as_possible(&mut vec![], ty);
64 return Some(ty);
65 }
66 ValueNs::FunctionId(it) => it.into(),
67 ValueNs::ConstId(it) => it.into(),
68 ValueNs::StaticId(it) => it.into(),
69 ValueNs::StructId(it) => it.into(),
70 ValueNs::EnumVariantId(it) => it.into(),
71 };
72
73 let mut ty = self.db.value_ty(typable);
74 if let Some(self_subst) = self_subst {
75 ty = ty.subst(&self_subst);
76 }
77 let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable);
78 let ty = ty.subst(&substs);
79 Some(ty)
80 }
81
82 fn resolve_assoc_item(
83 &mut self,
84 def: TypeNs,
85 path: &Path,
86 remaining_index: usize,
87 id: ExprOrPatId,
88 ) -> Option<(ValueNs, Option<Substs>)> {
89 assert!(remaining_index < path.segments.len());
90 // there may be more intermediate segments between the resolved one and
91 // the end. Only the last segment needs to be resolved to a value; from
92 // the segments before that, we need to get either a type or a trait ref.
93
94 let resolved_segment = &path.segments[remaining_index - 1];
95 let remaining_segments = &path.segments[remaining_index..];
96 let is_before_last = remaining_segments.len() == 1;
97
98 match (def, is_before_last) {
99 (TypeNs::TraitId(trait_), true) => {
100 let segment =
101 remaining_segments.last().expect("there should be at least one segment here");
102 let trait_ref = TraitRef::from_resolved_path(
103 self.db,
104 &self.resolver,
105 trait_.into(),
106 resolved_segment,
107 None,
108 );
109 self.resolve_trait_assoc_item(trait_ref, segment, id)
110 }
111 (def, _) => {
112 // Either we already have a type (e.g. `Vec::new`), or we have a
113 // trait but it's not the last segment, so the next segment
114 // should resolve to an associated type of that trait (e.g. `<T
115 // as Iterator>::Item::default`)
116 let remaining_segments_for_ty = &remaining_segments[..remaining_segments.len() - 1];
117 let ty = Ty::from_partly_resolved_hir_path(
118 self.db,
119 &self.resolver,
120 def,
121 resolved_segment,
122 remaining_segments_for_ty,
123 );
124 if let Ty::Unknown = ty {
125 return None;
126 }
127
128 let ty = self.insert_type_vars(ty);
129 let ty = self.normalize_associated_types_in(ty);
130
131 let segment =
132 remaining_segments.last().expect("there should be at least one segment here");
133
134 self.resolve_ty_assoc_item(ty, &segment.name, id)
135 }
136 }
137 }
138
139 fn resolve_trait_assoc_item(
140 &mut self,
141 trait_ref: TraitRef,
142 segment: &PathSegment,
143 id: ExprOrPatId,
144 ) -> Option<(ValueNs, Option<Substs>)> {
145 let trait_ = trait_ref.trait_;
146 let item = self
147 .db
148 .trait_data(trait_)
149 .items
150 .iter()
151 .map(|(_name, id)| (*id).into())
152 .find_map(|item| match item {
153 AssocItemId::FunctionId(func) => {
154 if segment.name == self.db.function_data(func).name {
155 Some(AssocItemId::FunctionId(func))
156 } else {
157 None
158 }
159 }
160
161 AssocItemId::ConstId(konst) => {
162 if self.db.const_data(konst).name.as_ref().map_or(false, |n| n == &segment.name)
163 {
164 Some(AssocItemId::ConstId(konst))
165 } else {
166 None
167 }
168 }
169 AssocItemId::TypeAliasId(_) => None,
170 })?;
171 let def = match item {
172 AssocItemId::FunctionId(f) => ValueNs::FunctionId(f),
173 AssocItemId::ConstId(c) => ValueNs::ConstId(c),
174 AssocItemId::TypeAliasId(_) => unreachable!(),
175 };
176 let substs = Substs::build_for_def(self.db, item)
177 .use_parent_substs(&trait_ref.substs)
178 .fill_with_params()
179 .build();
180
181 self.write_assoc_resolution(id, item);
182 Some((def, Some(substs)))
183 }
184
185 fn resolve_ty_assoc_item(
186 &mut self,
187 ty: Ty,
188 name: &Name,
189 id: ExprOrPatId,
190 ) -> Option<(ValueNs, Option<Substs>)> {
191 if let Ty::Unknown = ty {
192 return None;
193 }
194
195 let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone());
196
197 method_resolution::iterate_method_candidates(
198 &canonical_ty.value,
199 self.db,
200 &self.resolver.clone(),
201 Some(name),
202 method_resolution::LookupMode::Path,
203 move |_ty, item| {
204 let (def, container) = match item {
205 AssocItemId::FunctionId(f) => {
206 (ValueNs::FunctionId(f), f.lookup(self.db).container)
207 }
208 AssocItemId::ConstId(c) => (ValueNs::ConstId(c), c.lookup(self.db).container),
209 AssocItemId::TypeAliasId(_) => unreachable!(),
210 };
211 let substs = match container {
212 ContainerId::ImplId(_) => self.find_self_types(&def, ty.clone()),
213 ContainerId::TraitId(trait_) => {
214 // we're picking this method
215 let trait_substs = Substs::build_for_def(self.db, trait_)
216 .push(ty.clone())
217 .fill(std::iter::repeat_with(|| self.new_type_var()))
218 .build();
219 let substs = Substs::build_for_def(self.db, item)
220 .use_parent_substs(&trait_substs)
221 .fill_with_params()
222 .build();
223 self.obligations.push(super::Obligation::Trait(TraitRef {
224 trait_,
225 substs: trait_substs,
226 }));
227 Some(substs)
228 }
229 ContainerId::ModuleId(_) => None,
230 };
231
232 self.write_assoc_resolution(id, item.into());
233 Some((def, substs))
234 },
235 )
236 }
237
238 fn find_self_types(&self, def: &ValueNs, actual_def_ty: Ty) -> Option<Substs> {
239 if let ValueNs::FunctionId(func) = *def {
240 // We only do the infer if parent has generic params
241 let gen = self.db.generic_params(func.into());
242 if gen.count_parent_params() == 0 {
243 return None;
244 }
245
246 let impl_id = match func.lookup(self.db).container {
247 ContainerId::ImplId(it) => it,
248 _ => return None,
249 };
250 let resolver = impl_id.resolver(self.db);
251 let impl_data = self.db.impl_data(impl_id);
252 let impl_block = Ty::from_hir(self.db, &resolver, &impl_data.target_type);
253 let impl_block_substs = impl_block.substs()?;
254 let actual_substs = actual_def_ty.substs()?;
255
256 let mut new_substs = vec![Ty::Unknown; gen.count_parent_params()];
257
258 // The following code *link up* the function actual parma type
259 // and impl_block type param index
260 impl_block_substs.iter().zip(actual_substs.iter()).for_each(|(param, pty)| {
261 if let Ty::Param { idx, .. } = param {
262 if let Some(s) = new_substs.get_mut(*idx as usize) {
263 *s = pty.clone();
264 }
265 }
266 });
267
268 Some(Substs(new_substs.into()))
269 } else {
270 None
271 }
272 }
273}
diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs
deleted file mode 100644
index e27bb2f82..000000000
--- a/crates/ra_hir/src/ty/infer/unify.rs
+++ /dev/null
@@ -1,166 +0,0 @@
1//! Unification and canonicalization logic.
2
3use super::{InferenceContext, Obligation};
4use crate::{
5 db::HirDatabase,
6 ty::{
7 Canonical, InEnvironment, InferTy, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty,
8 TypeWalk,
9 },
10 util::make_mut_slice,
11};
12
13impl<'a, D: HirDatabase> InferenceContext<'a, D> {
14 pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D>
15 where
16 'a: 'b,
17 {
18 Canonicalizer { ctx: self, free_vars: Vec::new(), var_stack: Vec::new() }
19 }
20}
21
22pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase>
23where
24 'a: 'b,
25{
26 ctx: &'b mut InferenceContext<'a, D>,
27 free_vars: Vec<InferTy>,
28 /// A stack of type variables that is used to detect recursive types (which
29 /// are an error, but we need to protect against them to avoid stack
30 /// overflows).
31 var_stack: Vec<super::TypeVarId>,
32}
33
34pub(super) struct Canonicalized<T> {
35 pub value: Canonical<T>,
36 free_vars: Vec<InferTy>,
37}
38
39impl<'a, 'b, D: HirDatabase> Canonicalizer<'a, 'b, D>
40where
41 'a: 'b,
42{
43 fn add(&mut self, free_var: InferTy) -> usize {
44 self.free_vars.iter().position(|&v| v == free_var).unwrap_or_else(|| {
45 let next_index = self.free_vars.len();
46 self.free_vars.push(free_var);
47 next_index
48 })
49 }
50
51 fn do_canonicalize_ty(&mut self, ty: Ty) -> Ty {
52 ty.fold(&mut |ty| match ty {
53 Ty::Infer(tv) => {
54 let inner = tv.to_inner();
55 if self.var_stack.contains(&inner) {
56 // recursive type
57 return tv.fallback_value();
58 }
59 if let Some(known_ty) =
60 self.ctx.var_unification_table.inlined_probe_value(inner).known()
61 {
62 self.var_stack.push(inner);
63 let result = self.do_canonicalize_ty(known_ty.clone());
64 self.var_stack.pop();
65 result
66 } else {
67 let root = self.ctx.var_unification_table.find(inner);
68 let free_var = match tv {
69 InferTy::TypeVar(_) => InferTy::TypeVar(root),
70 InferTy::IntVar(_) => InferTy::IntVar(root),
71 InferTy::FloatVar(_) => InferTy::FloatVar(root),
72 InferTy::MaybeNeverTypeVar(_) => InferTy::MaybeNeverTypeVar(root),
73 };
74 let position = self.add(free_var);
75 Ty::Bound(position as u32)
76 }
77 }
78 _ => ty,
79 })
80 }
81
82 fn do_canonicalize_trait_ref(&mut self, mut trait_ref: TraitRef) -> TraitRef {
83 for ty in make_mut_slice(&mut trait_ref.substs.0) {
84 *ty = self.do_canonicalize_ty(ty.clone());
85 }
86 trait_ref
87 }
88
89 fn into_canonicalized<T>(self, result: T) -> Canonicalized<T> {
90 Canonicalized {
91 value: Canonical { value: result, num_vars: self.free_vars.len() },
92 free_vars: self.free_vars,
93 }
94 }
95
96 fn do_canonicalize_projection_ty(&mut self, mut projection_ty: ProjectionTy) -> ProjectionTy {
97 for ty in make_mut_slice(&mut projection_ty.parameters.0) {
98 *ty = self.do_canonicalize_ty(ty.clone());
99 }
100 projection_ty
101 }
102
103 fn do_canonicalize_projection_predicate(
104 &mut self,
105 projection: ProjectionPredicate,
106 ) -> ProjectionPredicate {
107 let ty = self.do_canonicalize_ty(projection.ty);
108 let projection_ty = self.do_canonicalize_projection_ty(projection.projection_ty);
109
110 ProjectionPredicate { ty, projection_ty }
111 }
112
113 // FIXME: add some point, we need to introduce a `Fold` trait that abstracts
114 // over all the things that can be canonicalized (like Chalk and rustc have)
115
116 pub(crate) fn canonicalize_ty(mut self, ty: Ty) -> Canonicalized<Ty> {
117 let result = self.do_canonicalize_ty(ty);
118 self.into_canonicalized(result)
119 }
120
121 pub(crate) fn canonicalize_obligation(
122 mut self,
123 obligation: InEnvironment<Obligation>,
124 ) -> Canonicalized<InEnvironment<Obligation>> {
125 let result = match obligation.value {
126 Obligation::Trait(tr) => Obligation::Trait(self.do_canonicalize_trait_ref(tr)),
127 Obligation::Projection(pr) => {
128 Obligation::Projection(self.do_canonicalize_projection_predicate(pr))
129 }
130 };
131 self.into_canonicalized(InEnvironment {
132 value: result,
133 environment: obligation.environment,
134 })
135 }
136}
137
138impl<T> Canonicalized<T> {
139 pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty {
140 ty.walk_mut_binders(
141 &mut |ty, binders| match ty {
142 &mut Ty::Bound(idx) => {
143 if idx as usize >= binders && (idx as usize - binders) < self.free_vars.len() {
144 *ty = Ty::Infer(self.free_vars[idx as usize - binders]);
145 }
146 }
147 _ => {}
148 },
149 0,
150 );
151 ty
152 }
153
154 pub fn apply_solution(
155 &self,
156 ctx: &mut InferenceContext<'_, impl HirDatabase>,
157 solution: Canonical<Vec<Ty>>,
158 ) {
159 // the solution may contain new variables, which we need to convert to new inference vars
160 let new_vars = Substs((0..solution.num_vars).map(|_| ctx.new_type_var()).collect());
161 for (i, ty) in solution.value.into_iter().enumerate() {
162 let var = self.free_vars[i];
163 ctx.unify(&Ty::Infer(var), &ty.subst_bound_vars(&new_vars));
164 }
165 }
166}