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