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