1 //! Type inference for expressions.
3 use std::iter::{repeat, repeat_with};
4 use std::{mem, sync::Arc};
6 use chalk_ir::{cast::Cast, fold::Shift, Mutability, TyVariableKind};
8 expr::{Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp},
9 path::{GenericArg, GenericArgs},
10 resolver::resolver_for_expr,
11 AssocContainerId, FieldId, Lookup,
13 use hir_expand::name::{name, Name};
15 use syntax::ast::RangeOp;
19 lower::lower_to_chalk_mutability,
21 method_resolution, op,
22 primitive::{self, UintTy},
23 static_lifetime, to_chalk_trait_id,
25 utils::{generics, Generics},
26 AdtId, Binders, CallableDefId, FnPointer, FnSig, FnSubst, InEnvironment, Interner,
27 ProjectionTyExt, Rawness, Scalar, Substitution, TraitRef, Ty, TyBuilder, TyExt, TyKind,
31 find_breakable, BindingMode, BreakableContext, Diverges, Expectation, InferenceContext,
32 InferenceDiagnostic, TypeMismatch,
35 impl<'a> InferenceContext<'a> {
36 pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
37 let ty = self.infer_expr_inner(tgt_expr, expected);
38 if self.resolve_ty_shallow(&ty).is_never() {
39 // Any expression that produces a value of type `!` must have diverged
40 self.diverges = Diverges::Always;
42 if let Some(expected_ty) = expected.only_has_type(&mut self.table) {
43 let could_unify = self.unify(&ty, &expected_ty);
45 self.result.type_mismatches.insert(
47 TypeMismatch { expected: expected_ty, actual: ty.clone() },
54 /// Infer type of expression with possibly implicit coerce to the expected type.
55 /// Return the type after possible coercion.
56 pub(super) fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty {
57 let ty = self.infer_expr_inner(expr, expected);
58 let ty = if let Some(target) = expected.only_has_type(&mut self.table) {
59 if !self.coerce(&ty, &target) {
62 .insert(expr.into(), TypeMismatch { expected: target, actual: ty.clone() });
63 // Return actual type when type mismatch.
64 // This is needed for diagnostic when return type mismatch.
76 fn callable_sig_from_fn_trait(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
77 let krate = self.resolver.krate()?;
78 let fn_once_trait = FnTrait::FnOnce.get_id(self.db, krate)?;
79 let output_assoc_type =
80 self.db.trait_data(fn_once_trait).associated_type_by_name(&name![Output])?;
82 let mut arg_tys = vec![];
83 let arg_ty = TyBuilder::tuple(num_args)
84 .fill(repeat_with(|| {
85 let arg = self.table.new_type_var();
86 arg_tys.push(arg.clone());
92 let b = TyBuilder::assoc_type_projection(self.db, output_assoc_type);
93 if b.remaining() != 2 {
96 b.push(ty.clone()).push(arg_ty).build()
99 let trait_env = self.trait_env.env.clone();
100 let obligation = InEnvironment {
101 goal: projection.trait_ref(self.db).cast(&Interner),
102 environment: trait_env,
104 let canonical = self.canonicalize(obligation.clone());
105 if self.db.trait_solve(krate, canonical.value.cast(&Interner)).is_some() {
106 self.push_obligation(obligation.goal);
107 let return_ty = self.table.normalize_projection_ty(projection);
108 Some((arg_tys, return_ty))
114 pub(crate) fn callable_sig(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
115 match ty.callable_sig(self.db) {
116 Some(sig) => Some((sig.params().to_vec(), sig.ret().clone())),
117 None => self.callable_sig_from_fn_trait(ty, num_args),
121 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
122 self.db.unwind_if_cancelled();
124 let body = Arc::clone(&self.body); // avoid borrow checker problem
125 let ty = match &body[tgt_expr] {
126 Expr::Missing => self.err_ty(),
127 Expr::If { condition, then_branch, else_branch } => {
128 // if let is desugared to match, so this is always simple if
131 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
134 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
135 let mut both_arms_diverge = Diverges::Always;
137 let mut result_ty = self.table.new_type_var();
138 let then_ty = self.infer_expr_inner(*then_branch, expected);
139 both_arms_diverge &= mem::replace(&mut self.diverges, Diverges::Maybe);
140 result_ty = self.coerce_merge_branch(Some(*then_branch), &result_ty, &then_ty);
141 let else_ty = match else_branch {
142 Some(else_branch) => self.infer_expr_inner(*else_branch, expected),
143 None => TyBuilder::unit(),
145 both_arms_diverge &= self.diverges;
146 // FIXME: create a synthetic `else {}` so we have something to refer to here instead of None?
147 result_ty = self.coerce_merge_branch(*else_branch, &result_ty, &else_ty);
149 self.diverges = condition_diverges | both_arms_diverge;
153 Expr::Block { statements, tail, label, id: _ } => {
154 let old_resolver = mem::replace(
156 resolver_for_expr(self.db.upcast(), self.owner, tgt_expr),
158 let ty = match label {
160 let break_ty = self.table.new_type_var();
161 self.breakables.push(BreakableContext {
163 break_ty: break_ty.clone(),
164 label: label.map(|label| self.body[label].name.clone()),
167 self.infer_block(statements, *tail, &Expectation::has_type(break_ty));
168 let ctxt = self.breakables.pop().expect("breakable stack broken");
175 None => self.infer_block(statements, *tail, expected),
177 self.resolver = old_resolver;
180 Expr::Unsafe { body } | Expr::Const { body } => self.infer_expr(*body, expected),
181 Expr::TryBlock { body } => {
182 let _inner = self.infer_expr(*body, expected);
183 // FIXME should be std::result::Result<{inner}, _>
186 Expr::Async { body } => {
187 // Use the first type parameter as the output type of future.
188 // existenail type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
189 let inner_ty = self.infer_expr(*body, &Expectation::none());
190 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
191 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
192 TyKind::OpaqueType(opaque_ty_id, Substitution::from1(&Interner, inner_ty))
195 Expr::Loop { body, label } => {
196 self.breakables.push(BreakableContext {
198 break_ty: self.table.new_type_var(),
199 label: label.map(|label| self.body[label].name.clone()),
201 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
203 let ctxt = self.breakables.pop().expect("breakable stack broken");
205 self.diverges = Diverges::Maybe;
211 TyKind::Never.intern(&Interner)
214 Expr::While { condition, body, label } => {
215 self.breakables.push(BreakableContext {
217 break_ty: self.err_ty(),
218 label: label.map(|label| self.body[label].name.clone()),
220 // while let is desugared to a match loop, so this is always simple while
223 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
225 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
226 let _ctxt = self.breakables.pop().expect("breakable stack broken");
227 // the body may not run, so it diverging doesn't mean we diverge
228 self.diverges = Diverges::Maybe;
231 Expr::For { iterable, body, pat, label } => {
232 let iterable_ty = self.infer_expr(*iterable, &Expectation::none());
234 self.breakables.push(BreakableContext {
236 break_ty: self.err_ty(),
237 label: label.map(|label| self.body[label].name.clone()),
240 self.resolve_associated_type(iterable_ty, self.resolve_into_iter_item());
242 self.infer_pat(*pat, &pat_ty, BindingMode::default());
244 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
245 let _ctxt = self.breakables.pop().expect("breakable stack broken");
246 // the body may not run, so it diverging doesn't mean we diverge
247 self.diverges = Diverges::Maybe;
250 Expr::Lambda { body, args, ret_type, arg_types } => {
251 assert_eq!(args.len(), arg_types.len());
253 let mut sig_tys = Vec::new();
255 // collect explicitly written argument types
256 for arg_type in arg_types.iter() {
257 let arg_ty = if let Some(type_ref) = arg_type {
258 self.make_ty(type_ref)
260 self.table.new_type_var()
262 sig_tys.push(arg_ty);
266 let ret_ty = match ret_type {
267 Some(type_ref) => self.make_ty(type_ref),
268 None => self.table.new_type_var(),
270 sig_tys.push(ret_ty.clone());
271 let sig_ty = TyKind::Function(FnPointer {
273 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
274 substitution: FnSubst(
275 Substitution::from_iter(&Interner, sig_tys.clone()).shifted_in(&Interner),
279 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
281 TyKind::Closure(closure_id, Substitution::from1(&Interner, sig_ty))
284 // Eagerly try to relate the closure type with the expected
285 // type, otherwise we often won't have enough information to
287 if let Some(t) = expected.only_has_type(&mut self.table) {
288 self.coerce(&closure_ty, &t);
291 // Now go through the argument patterns
292 for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
293 self.infer_pat(*arg_pat, &arg_ty, BindingMode::default());
296 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
297 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
299 self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
301 self.diverges = prev_diverges;
302 self.return_ty = prev_ret_ty;
306 Expr::Call { callee, args } => {
307 let callee_ty = self.infer_expr(*callee, &Expectation::none());
308 let canonicalized = self.canonicalize(callee_ty.clone());
309 let mut derefs = autoderef(
311 self.resolver.krate(),
313 goal: canonicalized.value.clone(),
314 environment: self.table.trait_env.env.clone(),
317 let (param_tys, ret_ty): (Vec<Ty>, Ty) = derefs
318 .find_map(|callee_deref_ty| {
320 &canonicalized.decanonicalize_ty(callee_deref_ty.value),
324 .unwrap_or((Vec::new(), self.err_ty()));
325 self.register_obligations_for_call(&callee_ty);
326 self.check_call_arguments(args, ¶m_tys);
327 self.normalize_associated_types_in(ret_ty)
329 Expr::MethodCall { receiver, args, method_name, generic_args } => self
335 generic_args.as_deref(),
337 Expr::Match { expr, arms } => {
338 let input_ty = self.infer_expr(*expr, &Expectation::none());
340 let expected = expected.adjust_for_branches(&mut self.table);
342 let mut result_ty = if arms.is_empty() {
343 TyKind::Never.intern(&Interner)
346 Expectation::HasType(ty) => ty.clone(),
347 _ => self.table.new_type_var(),
351 let matchee_diverges = self.diverges;
352 let mut all_arms_diverge = Diverges::Always;
355 self.diverges = Diverges::Maybe;
356 let _pat_ty = self.infer_pat(arm.pat, &input_ty, BindingMode::default());
357 if let Some(guard_expr) = arm.guard {
360 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
364 let arm_ty = self.infer_expr_inner(arm.expr, &expected);
365 all_arms_diverge &= self.diverges;
366 result_ty = self.coerce_merge_branch(Some(arm.expr), &result_ty, &arm_ty);
369 self.diverges = matchee_diverges | all_arms_diverge;
374 // FIXME this could be more efficient...
375 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
376 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(self.err_ty())
378 Expr::Continue { .. } => TyKind::Never.intern(&Interner),
379 Expr::Break { expr, label } => {
381 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
382 ctxt.break_ty.clone()
387 let val_ty = if let Some(expr) = expr {
388 self.infer_expr(*expr, &Expectation::none())
393 // FIXME: create a synthetic `()` during lowering so we have something to refer to here?
394 let merged_type = self.coerce_merge_branch(*expr, &last_ty, &val_ty);
396 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
397 ctxt.break_ty = merged_type;
398 ctxt.may_break = true;
400 self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop {
404 TyKind::Never.intern(&Interner)
406 Expr::Return { expr } => {
407 if let Some(expr) = expr {
408 self.infer_expr_coerce(*expr, &Expectation::has_type(self.return_ty.clone()));
410 let unit = TyBuilder::unit();
411 self.coerce(&unit, &self.return_ty.clone());
413 TyKind::Never.intern(&Interner)
415 Expr::Yield { expr } => {
416 // FIXME: track yield type for coercion
417 if let Some(expr) = expr {
418 self.infer_expr(*expr, &Expectation::none());
420 TyKind::Never.intern(&Interner)
422 Expr::RecordLit { path, fields, spread } => {
423 let (ty, def_id) = self.resolve_variant(path.as_deref());
424 if let Some(variant) = def_id {
425 self.write_variant_resolution(tgt_expr.into(), variant);
428 if let Some(t) = expected.only_has_type(&mut self.table) {
434 .map(|(_, s)| s.clone())
435 .unwrap_or_else(|| Substitution::empty(&Interner));
436 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
437 let variant_data = def_id.map(|it| it.variant_data(self.db.upcast()));
438 for field in fields.iter() {
440 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
441 Some(local_id) => Some(FieldId { parent: def_id.unwrap(), local_id }),
443 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
449 let field_ty = field_def.map_or(self.err_ty(), |it| {
450 field_types[it.local_id].clone().substitute(&Interner, &substs)
452 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
454 if let Some(expr) = spread {
455 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
459 Expr::Field { expr, name } => {
460 let receiver_ty = self.infer_expr_inner(*expr, &Expectation::none());
461 let canonicalized = self.canonicalize(receiver_ty);
462 let ty = autoderef::autoderef(
464 self.resolver.krate(),
466 goal: canonicalized.value.clone(),
467 environment: self.trait_env.env.clone(),
470 .find_map(|derefed_ty| {
471 let def_db = self.db.upcast();
472 let module = self.resolver.module();
473 let is_visible = |field_id: &FieldId| {
476 self.db.field_visibilities(field_id.parent)[field_id.local_id]
477 .is_visible_from(def_db, mod_id)
481 match canonicalized.decanonicalize_ty(derefed_ty.value).kind(&Interner) {
482 TyKind::Tuple(_, substs) => name.as_tuple_index().and_then(|idx| {
486 .map(|a| a.assert_ty_ref(&Interner))
489 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
490 let local_id = self.db.struct_data(*s).variant_data.field(name)?;
491 let field = FieldId { parent: (*s).into(), local_id };
492 if is_visible(&field) {
493 self.write_field_resolution(tgt_expr, field);
495 self.db.field_types((*s).into())[field.local_id]
497 .substitute(&Interner, ¶meters),
503 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
504 let local_id = self.db.union_data(*u).variant_data.field(name)?;
505 let field = FieldId { parent: (*u).into(), local_id };
506 if is_visible(&field) {
507 self.write_field_resolution(tgt_expr, field);
509 self.db.field_types((*u).into())[field.local_id]
511 .substitute(&Interner, ¶meters),
520 .unwrap_or(self.err_ty());
521 let ty = self.insert_type_vars(ty);
522 self.normalize_associated_types_in(ty)
524 Expr::Await { expr } => {
525 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
526 self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
528 Expr::Try { expr } => {
529 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
530 self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
532 Expr::Cast { expr, type_ref } => {
533 // FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
534 let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
535 let cast_ty = self.make_ty(type_ref);
536 // FIXME check the cast...
539 Expr::Ref { expr, rawness, mutability } => {
540 let mutability = lower_to_chalk_mutability(*mutability);
541 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = expected
542 .only_has_type(&mut self.table)
544 .and_then(|t| t.as_reference_or_ptr())
546 if exp_mutability == Mutability::Mut && mutability == Mutability::Not {
547 // FIXME: record type error - expected mut reference but found shared ref,
548 // which cannot be coerced
550 if exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
551 // FIXME: record type error - expected reference but found ptr,
552 // which cannot be coerced
554 Expectation::rvalue_hint(Ty::clone(exp_inner))
558 let inner_ty = self.infer_expr_inner(*expr, &expectation);
560 Rawness::RawPtr => TyKind::Raw(mutability, inner_ty),
561 Rawness::Ref => TyKind::Ref(mutability, static_lifetime(), inner_ty),
565 Expr::Box { expr } => {
566 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
567 if let Some(box_) = self.resolve_boxed_box() {
568 TyBuilder::adt(self.db, box_)
570 .fill_with_defaults(self.db, || self.table.new_type_var())
576 Expr::UnaryOp { expr, op } => {
577 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
578 let inner_ty = self.resolve_ty_shallow(&inner_ty);
580 UnaryOp::Deref => match self.resolver.krate() {
582 let canonicalized = self.canonicalize(inner_ty);
583 match autoderef::deref(
587 goal: &canonicalized.value,
588 environment: self.trait_env.env.clone(),
591 Some(derefed_ty) => {
592 canonicalized.decanonicalize_ty(derefed_ty.value)
594 None => self.err_ty(),
597 None => self.err_ty(),
600 match inner_ty.kind(&Interner) {
601 // Fast path for builtins
602 TyKind::Scalar(Scalar::Int(_))
603 | TyKind::Scalar(Scalar::Uint(_))
604 | TyKind::Scalar(Scalar::Float(_))
605 | TyKind::InferenceVar(_, TyVariableKind::Integer)
606 | TyKind::InferenceVar(_, TyVariableKind::Float) => inner_ty,
607 // Otherwise we resolve via the std::ops::Neg trait
609 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
613 match inner_ty.kind(&Interner) {
614 // Fast path for builtins
615 TyKind::Scalar(Scalar::Bool)
616 | TyKind::Scalar(Scalar::Int(_))
617 | TyKind::Scalar(Scalar::Uint(_))
618 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
619 // Otherwise we resolve via the std::ops::Not trait
621 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
626 Expr::BinaryOp { lhs, rhs, op } => match op {
628 let lhs_expectation = match op {
629 BinaryOp::LogicOp(..) => {
630 Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner))
632 _ => Expectation::none(),
634 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
635 let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
636 let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty.clone());
637 let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation));
638 let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
640 let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone());
642 if ret.is_unknown() {
643 cov_mark::hit!(infer_expr_inner_binary_operator_overload);
645 self.resolve_associated_type_with_params(
647 self.resolve_binary_op_output(op),
656 Expr::Range { lhs, rhs, range_type } => {
657 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
658 let rhs_expect = lhs_ty
660 .map_or_else(Expectation::none, |ty| Expectation::has_type(ty.clone()));
661 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
662 match (range_type, lhs_ty, rhs_ty) {
663 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
664 Some(adt) => TyBuilder::adt(self.db, adt).build(),
665 None => self.err_ty(),
667 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
668 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
669 None => self.err_ty(),
671 (RangeOp::Inclusive, None, Some(ty)) => {
672 match self.resolve_range_to_inclusive() {
673 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
674 None => self.err_ty(),
677 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
678 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
679 None => self.err_ty(),
681 (RangeOp::Inclusive, Some(_), Some(ty)) => {
682 match self.resolve_range_inclusive() {
683 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
684 None => self.err_ty(),
687 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
688 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
689 None => self.err_ty(),
691 (RangeOp::Inclusive, _, None) => self.err_ty(),
694 Expr::Index { base, index } => {
695 let base_ty = self.infer_expr_inner(*base, &Expectation::none());
696 let index_ty = self.infer_expr(*index, &Expectation::none());
698 if let (Some(index_trait), Some(krate)) =
699 (self.resolve_ops_index(), self.resolver.krate())
701 let canonicalized = self.canonicalize(base_ty);
702 let self_ty = method_resolution::resolve_indexing_op(
704 &canonicalized.value,
705 self.trait_env.clone(),
710 self_ty.map_or(self.err_ty(), |t| canonicalized.decanonicalize_ty(t.value));
711 self.resolve_associated_type_with_params(
713 self.resolve_ops_index_output(),
720 Expr::Tuple { exprs } => {
721 let mut tys = match expected
722 .only_has_type(&mut self.table)
724 .map(|t| t.kind(&Interner))
726 Some(TyKind::Tuple(_, substs)) => substs
728 .map(|a| a.assert_ty_ref(&Interner).clone())
729 .chain(repeat_with(|| self.table.new_type_var()))
731 .collect::<Vec<_>>(),
732 _ => (0..exprs.len()).map(|_| self.table.new_type_var()).collect(),
735 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
736 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
739 TyKind::Tuple(tys.len(), Substitution::from_iter(&Interner, tys)).intern(&Interner)
741 Expr::Array(array) => {
743 match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(&Interner)) {
744 Some(TyKind::Array(st, _)) | Some(TyKind::Slice(st)) => st.clone(),
745 _ => self.table.new_type_var(),
748 let len = match array {
749 Array::ElementList(items) => {
750 for expr in items.iter() {
751 // FIXME: use CoerceMany (coerce_merge_branch)
752 self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone()));
754 Some(items.len() as u64)
756 Array::Repeat { initializer, repeat } => {
757 self.infer_expr_coerce(
759 &Expectation::has_type(elem_ty.clone()),
763 &Expectation::has_type(
764 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner),
768 let repeat_expr = &self.body.exprs[*repeat];
769 consteval::eval_usize(repeat_expr)
773 TyKind::Array(elem_ty, consteval::usize_const(len)).intern(&Interner)
775 Expr::Literal(lit) => match lit {
776 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(&Interner),
777 Literal::String(..) => {
778 TyKind::Ref(Mutability::Not, static_lifetime(), TyKind::Str.intern(&Interner))
781 Literal::ByteString(bs) => {
782 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(&Interner);
784 let len = consteval::usize_const(Some(bs.len() as u64));
786 let array_type = TyKind::Array(byte_type, len).intern(&Interner);
787 TyKind::Ref(Mutability::Not, static_lifetime(), array_type).intern(&Interner)
789 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(&Interner),
790 Literal::Int(_v, ty) => match ty {
792 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
795 None => self.table.new_integer_var(),
797 Literal::Uint(_v, ty) => match ty {
799 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
802 None => self.table.new_integer_var(),
804 Literal::Float(_v, ty) => match ty {
806 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
809 None => self.table.new_float_var(),
812 Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
814 // use a new type variable if we got unknown here
815 let ty = self.insert_type_vars_shallow(ty);
816 self.write_expr_ty(tgt_expr, ty.clone());
822 statements: &[Statement],
823 tail: Option<ExprId>,
824 expected: &Expectation,
826 for stmt in statements {
828 Statement::Let { pat, type_ref, initializer } => {
830 type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(self.err_ty());
832 // Always use the declared type when specified
833 let mut ty = decl_ty.clone();
835 if let Some(expr) = initializer {
837 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
838 if decl_ty.is_unknown() {
843 self.infer_pat(*pat, &ty, BindingMode::default());
845 Statement::Expr { expr, .. } => {
846 self.infer_expr(*expr, &Expectation::none());
851 let ty = if let Some(expr) = tail {
852 self.infer_expr_coerce(expr, expected)
854 // Citing rustc: if there is no explicit tail expression,
855 // that is typically equivalent to a tail expression
856 // of `()` -- except if the block diverges. In that
857 // case, there is no value supplied from the tail
858 // expression (assuming there are no other breaks,
859 // this implies that the type of the block will be
861 if self.diverges.is_always() {
862 // we don't even make an attempt at coercion
863 self.table.new_maybe_never_var()
865 if let Some(t) = expected.only_has_type(&mut self.table) {
866 self.coerce(&TyBuilder::unit(), &t);
874 fn infer_method_call(
880 generic_args: Option<&GenericArgs>,
882 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
883 let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
885 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
887 let resolved = self.resolver.krate().and_then(|krate| {
888 method_resolution::lookup_method(
889 &canonicalized_receiver.value,
891 self.trait_env.clone(),
894 self.resolver.module(),
898 let (receiver_ty, method_ty, substs) = match resolved {
899 Some((ty, func)) => {
900 let ty = canonicalized_receiver.decanonicalize_ty(ty);
901 let generics = generics(self.db.upcast(), func.into());
902 let substs = self.substs_for_method_call(generics, generic_args, &ty);
903 self.write_method_resolution(tgt_expr, func, substs.clone());
904 (ty, self.db.value_ty(func.into()), substs)
908 Binders::empty(&Interner, self.err_ty()),
909 Substitution::empty(&Interner),
912 let method_ty = method_ty.substitute(&Interner, &substs);
913 self.register_obligations_for_call(&method_ty);
914 let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
916 if !sig.params().is_empty() {
917 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
919 (self.err_ty(), Vec::new(), sig.ret().clone())
922 None => (self.err_ty(), Vec::new(), self.err_ty()),
924 self.unify(&expected_receiver_ty, &receiver_ty);
926 self.check_call_arguments(args, ¶m_tys);
927 self.normalize_associated_types_in(ret_ty)
930 fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) {
931 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
932 // We do this in a pretty awful way: first we type-check any arguments
933 // that are not closures, then we type-check the closures. This is so
934 // that we have more information about the types of arguments when we
935 // type-check the functions. This isn't really the right way to do this.
936 for &check_closures in &[false, true] {
937 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
938 for (&arg, param_ty) in args.iter().zip(param_iter) {
939 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
940 if is_closure != check_closures {
944 let param_ty = self.normalize_associated_types_in(param_ty);
945 self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone()));
950 fn substs_for_method_call(
952 def_generics: Generics,
953 generic_args: Option<&GenericArgs>,
956 let (parent_params, self_params, type_params, impl_trait_params) =
957 def_generics.provenance_split();
958 assert_eq!(self_params, 0); // method shouldn't have another Self param
959 let total_len = parent_params + type_params + impl_trait_params;
960 let mut substs = Vec::with_capacity(total_len);
961 // Parent arguments are unknown, except for the receiver type
962 for (_id, param) in def_generics.iter_parent() {
963 if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
964 substs.push(receiver_ty.clone());
966 substs.push(self.table.new_type_var());
969 // handle provided type arguments
970 if let Some(generic_args) = generic_args {
971 // if args are provided, it should be all of them, but we can't rely on that
972 for arg in generic_args
975 .filter(|arg| matches!(arg, GenericArg::Type(_)))
979 GenericArg::Type(type_ref) => {
980 let ty = self.make_ty(type_ref);
983 GenericArg::Lifetime(_) => {}
987 let supplied_params = substs.len();
988 for _ in supplied_params..total_len {
989 substs.push(self.table.new_type_var());
991 assert_eq!(substs.len(), total_len);
992 Substitution::from_iter(&Interner, substs)
995 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
996 let callable_ty = self.resolve_ty_shallow(callable_ty);
997 if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(&Interner) {
998 let def: CallableDefId = from_chalk(self.db, *fn_def);
999 let generic_predicates = self.db.generic_predicates(def.into());
1000 for predicate in generic_predicates.iter() {
1001 let (predicate, binders) = predicate
1003 .substitute(&Interner, parameters)
1004 .into_value_and_skipped_binders();
1005 always!(binders.len(&Interner) == 0); // quantified where clauses not yet handled
1006 self.push_obligation(predicate.cast(&Interner));
1008 // add obligation for trait implementation, if this is a trait method
1010 CallableDefId::FunctionId(f) => {
1011 if let AssocContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container
1013 // construct a TraitRef
1014 let substs = crate::subst_prefix(
1016 generics(self.db.upcast(), trait_.into()).len(),
1018 self.push_obligation(
1019 TraitRef { trait_id: to_chalk_trait_id(trait_), substitution: substs }
1024 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}