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