diff options
Diffstat (limited to 'crates/ra_hir/src/ty/infer/expr.rs')
-rw-r--r-- | crates/ra_hir/src/ty/infer/expr.rs | 667 |
1 files changed, 0 insertions, 667 deletions
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 | |||
3 | use std::iter::{repeat, repeat_with}; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use hir_def::{ | ||
7 | builtin_type::Signedness, | ||
8 | generics::GenericParams, | ||
9 | path::{GenericArg, GenericArgs}, | ||
10 | resolver::resolver_for_expr, | ||
11 | }; | ||
12 | use hir_expand::name; | ||
13 | |||
14 | use 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 | |||
25 | use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; | ||
26 | |||
27 | impl<'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, ¶m_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, ¶m_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 | } | ||