aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src/ty/infer/expr.rs
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2019-10-12 17:41:47 +0100
committerGitHub <[email protected]>2019-10-12 17:41:47 +0100
commit264a07975d23ad4d7cb41b309ba4a4c0a507a028 (patch)
tree9025efd452e137874b3b0655e4d5ba12ae44b146 /crates/ra_hir/src/ty/infer/expr.rs
parent0896ca04c4e6f88ae268a39472570df4b6d360b0 (diff)
parent2955fbc7e1e49b96565505bf599e950b11d370ac (diff)
Merge #2004
2004: Split up infer.rs further r=flodiebold a=flodiebold - coercion logic goes to `coerce.rs` - expression inference goes to `expr.rs` - pattern inference goes to `pat.rs` Co-authored-by: Florian Diebold <[email protected]>
Diffstat (limited to 'crates/ra_hir/src/ty/infer/expr.rs')
-rw-r--r--crates/ra_hir/src/ty/infer/expr.rs658
1 files changed, 658 insertions, 0 deletions
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}