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