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 mut result_ty = if arms.is_empty() {
341 TyKind::Never.intern(&Interner)
343 self.table.new_type_var()
346 let matchee_diverges = self.diverges;
347 let mut all_arms_diverge = Diverges::Always;
350 self.diverges = Diverges::Maybe;
351 let _pat_ty = self.infer_pat(arm.pat, &input_ty, BindingMode::default());
352 if let Some(guard_expr) = arm.guard {
355 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
359 let arm_ty = self.infer_expr_inner(arm.expr, &expected);
360 all_arms_diverge &= self.diverges;
361 result_ty = self.coerce_merge_branch(Some(arm.expr), &result_ty, &arm_ty);
364 self.diverges = matchee_diverges | all_arms_diverge;
369 // FIXME this could be more efficient...
370 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
371 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(self.err_ty())
373 Expr::Continue { .. } => TyKind::Never.intern(&Interner),
374 Expr::Break { expr, label } => {
376 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
377 ctxt.break_ty.clone()
382 let val_ty = if let Some(expr) = expr {
383 self.infer_expr(*expr, &Expectation::none())
388 // FIXME: create a synthetic `()` during lowering so we have something to refer to here?
389 let merged_type = self.coerce_merge_branch(*expr, &last_ty, &val_ty);
391 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
392 ctxt.break_ty = merged_type;
393 ctxt.may_break = true;
395 self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop {
399 TyKind::Never.intern(&Interner)
401 Expr::Return { expr } => {
402 if let Some(expr) = expr {
403 self.infer_expr_coerce(*expr, &Expectation::has_type(self.return_ty.clone()));
405 let unit = TyBuilder::unit();
406 self.coerce(&unit, &self.return_ty.clone());
408 TyKind::Never.intern(&Interner)
410 Expr::Yield { expr } => {
411 // FIXME: track yield type for coercion
412 if let Some(expr) = expr {
413 self.infer_expr(*expr, &Expectation::none());
415 TyKind::Never.intern(&Interner)
417 Expr::RecordLit { path, fields, spread } => {
418 let (ty, def_id) = self.resolve_variant(path.as_deref());
419 if let Some(variant) = def_id {
420 self.write_variant_resolution(tgt_expr.into(), variant);
423 if let Some(t) = expected.only_has_type(&mut self.table) {
429 .map(|(_, s)| s.clone())
430 .unwrap_or_else(|| Substitution::empty(&Interner));
431 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
432 let variant_data = def_id.map(|it| it.variant_data(self.db.upcast()));
433 for field in fields.iter() {
435 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
436 Some(local_id) => Some(FieldId { parent: def_id.unwrap(), local_id }),
438 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
444 let field_ty = field_def.map_or(self.err_ty(), |it| {
445 field_types[it.local_id].clone().substitute(&Interner, &substs)
447 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
449 if let Some(expr) = spread {
450 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
454 Expr::Field { expr, name } => {
455 let receiver_ty = self.infer_expr_inner(*expr, &Expectation::none());
456 let canonicalized = self.canonicalize(receiver_ty);
457 let ty = autoderef::autoderef(
459 self.resolver.krate(),
461 goal: canonicalized.value.clone(),
462 environment: self.trait_env.env.clone(),
465 .find_map(|derefed_ty| {
466 let def_db = self.db.upcast();
467 let module = self.resolver.module();
468 let is_visible = |field_id: &FieldId| {
471 self.db.field_visibilities(field_id.parent)[field_id.local_id]
472 .is_visible_from(def_db, mod_id)
476 match canonicalized.decanonicalize_ty(derefed_ty.value).kind(&Interner) {
477 TyKind::Tuple(_, substs) => name.as_tuple_index().and_then(|idx| {
481 .map(|a| a.assert_ty_ref(&Interner))
484 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
485 let local_id = self.db.struct_data(*s).variant_data.field(name)?;
486 let field = FieldId { parent: (*s).into(), local_id };
487 if is_visible(&field) {
488 self.write_field_resolution(tgt_expr, field);
490 self.db.field_types((*s).into())[field.local_id]
492 .substitute(&Interner, ¶meters),
498 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
499 let local_id = self.db.union_data(*u).variant_data.field(name)?;
500 let field = FieldId { parent: (*u).into(), local_id };
501 if is_visible(&field) {
502 self.write_field_resolution(tgt_expr, field);
504 self.db.field_types((*u).into())[field.local_id]
506 .substitute(&Interner, ¶meters),
515 .unwrap_or(self.err_ty());
516 let ty = self.insert_type_vars(ty);
517 self.normalize_associated_types_in(ty)
519 Expr::Await { expr } => {
520 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
521 self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
523 Expr::Try { expr } => {
524 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
525 self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
527 Expr::Cast { expr, type_ref } => {
528 // FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
529 let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
530 let cast_ty = self.make_ty(type_ref);
531 // FIXME check the cast...
534 Expr::Ref { expr, rawness, mutability } => {
535 let mutability = lower_to_chalk_mutability(*mutability);
536 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = expected
537 .only_has_type(&mut self.table)
539 .and_then(|t| t.as_reference_or_ptr())
541 if exp_mutability == Mutability::Mut && mutability == Mutability::Not {
542 // FIXME: record type error - expected mut reference but found shared ref,
543 // which cannot be coerced
545 if exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
546 // FIXME: record type error - expected reference but found ptr,
547 // which cannot be coerced
549 Expectation::rvalue_hint(Ty::clone(exp_inner))
553 let inner_ty = self.infer_expr_inner(*expr, &expectation);
555 Rawness::RawPtr => TyKind::Raw(mutability, inner_ty),
556 Rawness::Ref => TyKind::Ref(mutability, static_lifetime(), inner_ty),
560 Expr::Box { expr } => {
561 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
562 if let Some(box_) = self.resolve_boxed_box() {
563 TyBuilder::adt(self.db, box_)
565 .fill_with_defaults(self.db, || self.table.new_type_var())
571 Expr::UnaryOp { expr, op } => {
572 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
573 let inner_ty = self.resolve_ty_shallow(&inner_ty);
575 UnaryOp::Deref => match self.resolver.krate() {
577 let canonicalized = self.canonicalize(inner_ty);
578 match autoderef::deref(
582 goal: &canonicalized.value,
583 environment: self.trait_env.env.clone(),
586 Some(derefed_ty) => {
587 canonicalized.decanonicalize_ty(derefed_ty.value)
589 None => self.err_ty(),
592 None => self.err_ty(),
595 match inner_ty.kind(&Interner) {
596 // Fast path for builtins
597 TyKind::Scalar(Scalar::Int(_))
598 | TyKind::Scalar(Scalar::Uint(_))
599 | TyKind::Scalar(Scalar::Float(_))
600 | TyKind::InferenceVar(_, TyVariableKind::Integer)
601 | TyKind::InferenceVar(_, TyVariableKind::Float) => inner_ty,
602 // Otherwise we resolve via the std::ops::Neg trait
604 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
608 match inner_ty.kind(&Interner) {
609 // Fast path for builtins
610 TyKind::Scalar(Scalar::Bool)
611 | TyKind::Scalar(Scalar::Int(_))
612 | TyKind::Scalar(Scalar::Uint(_))
613 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
614 // Otherwise we resolve via the std::ops::Not trait
616 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
621 Expr::BinaryOp { lhs, rhs, op } => match op {
623 let lhs_expectation = match op {
624 BinaryOp::LogicOp(..) => {
625 Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner))
627 _ => Expectation::none(),
629 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
630 let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
631 let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty.clone());
632 let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation));
633 let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
635 let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone());
637 if ret.is_unknown() {
638 cov_mark::hit!(infer_expr_inner_binary_operator_overload);
640 self.resolve_associated_type_with_params(
642 self.resolve_binary_op_output(op),
651 Expr::Range { lhs, rhs, range_type } => {
652 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
653 let rhs_expect = lhs_ty
655 .map_or_else(Expectation::none, |ty| Expectation::has_type(ty.clone()));
656 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
657 match (range_type, lhs_ty, rhs_ty) {
658 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
659 Some(adt) => TyBuilder::adt(self.db, adt).build(),
660 None => self.err_ty(),
662 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
663 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
664 None => self.err_ty(),
666 (RangeOp::Inclusive, None, Some(ty)) => {
667 match self.resolve_range_to_inclusive() {
668 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
669 None => self.err_ty(),
672 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
673 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
674 None => self.err_ty(),
676 (RangeOp::Inclusive, Some(_), Some(ty)) => {
677 match self.resolve_range_inclusive() {
678 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
679 None => self.err_ty(),
682 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
683 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
684 None => self.err_ty(),
686 (RangeOp::Inclusive, _, None) => self.err_ty(),
689 Expr::Index { base, index } => {
690 let base_ty = self.infer_expr_inner(*base, &Expectation::none());
691 let index_ty = self.infer_expr(*index, &Expectation::none());
693 if let (Some(index_trait), Some(krate)) =
694 (self.resolve_ops_index(), self.resolver.krate())
696 let canonicalized = self.canonicalize(base_ty);
697 let self_ty = method_resolution::resolve_indexing_op(
699 &canonicalized.value,
700 self.trait_env.clone(),
705 self_ty.map_or(self.err_ty(), |t| canonicalized.decanonicalize_ty(t.value));
706 self.resolve_associated_type_with_params(
708 self.resolve_ops_index_output(),
715 Expr::Tuple { exprs } => {
716 let mut tys = match expected
717 .only_has_type(&mut self.table)
719 .map(|t| t.kind(&Interner))
721 Some(TyKind::Tuple(_, substs)) => substs
723 .map(|a| a.assert_ty_ref(&Interner).clone())
724 .chain(repeat_with(|| self.table.new_type_var()))
726 .collect::<Vec<_>>(),
727 _ => (0..exprs.len()).map(|_| self.table.new_type_var()).collect(),
730 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
731 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
734 TyKind::Tuple(tys.len(), Substitution::from_iter(&Interner, tys)).intern(&Interner)
736 Expr::Array(array) => {
738 match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(&Interner)) {
739 Some(TyKind::Array(st, _)) | Some(TyKind::Slice(st)) => st.clone(),
740 _ => self.table.new_type_var(),
743 let len = match array {
744 Array::ElementList(items) => {
745 for expr in items.iter() {
746 // FIXME: use CoerceMany (coerce_merge_branch)
747 self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone()));
749 Some(items.len() as u64)
751 Array::Repeat { initializer, repeat } => {
752 self.infer_expr_coerce(
754 &Expectation::has_type(elem_ty.clone()),
758 &Expectation::has_type(
759 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner),
763 let repeat_expr = &self.body.exprs[*repeat];
764 consteval::eval_usize(repeat_expr)
768 TyKind::Array(elem_ty, consteval::usize_const(len)).intern(&Interner)
770 Expr::Literal(lit) => match lit {
771 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(&Interner),
772 Literal::String(..) => {
773 TyKind::Ref(Mutability::Not, static_lifetime(), TyKind::Str.intern(&Interner))
776 Literal::ByteString(bs) => {
777 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(&Interner);
779 let len = consteval::usize_const(Some(bs.len() as u64));
781 let array_type = TyKind::Array(byte_type, len).intern(&Interner);
782 TyKind::Ref(Mutability::Not, static_lifetime(), array_type).intern(&Interner)
784 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(&Interner),
785 Literal::Int(_v, ty) => match ty {
787 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
790 None => self.table.new_integer_var(),
792 Literal::Uint(_v, ty) => match ty {
794 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
797 None => self.table.new_integer_var(),
799 Literal::Float(_v, ty) => match ty {
801 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
804 None => self.table.new_float_var(),
807 Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
809 // use a new type variable if we got unknown here
810 let ty = self.insert_type_vars_shallow(ty);
811 self.write_expr_ty(tgt_expr, ty.clone());
817 statements: &[Statement],
818 tail: Option<ExprId>,
819 expected: &Expectation,
821 for stmt in statements {
823 Statement::Let { pat, type_ref, initializer } => {
825 type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(self.err_ty());
827 // Always use the declared type when specified
828 let mut ty = decl_ty.clone();
830 if let Some(expr) = initializer {
832 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
833 if decl_ty.is_unknown() {
838 self.infer_pat(*pat, &ty, BindingMode::default());
840 Statement::Expr { expr, .. } => {
841 self.infer_expr(*expr, &Expectation::none());
846 let ty = if let Some(expr) = tail {
847 self.infer_expr_coerce(expr, expected)
849 // Citing rustc: if there is no explicit tail expression,
850 // that is typically equivalent to a tail expression
851 // of `()` -- except if the block diverges. In that
852 // case, there is no value supplied from the tail
853 // expression (assuming there are no other breaks,
854 // this implies that the type of the block will be
856 if self.diverges.is_always() {
857 // we don't even make an attempt at coercion
858 self.table.new_maybe_never_var()
860 if let Some(t) = expected.only_has_type(&mut self.table) {
861 self.coerce(&TyBuilder::unit(), &t);
869 fn infer_method_call(
875 generic_args: Option<&GenericArgs>,
877 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
878 let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
880 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
882 let resolved = self.resolver.krate().and_then(|krate| {
883 method_resolution::lookup_method(
884 &canonicalized_receiver.value,
886 self.trait_env.clone(),
889 self.resolver.module(),
893 let (receiver_ty, method_ty, substs) = match resolved {
894 Some((ty, func)) => {
895 let ty = canonicalized_receiver.decanonicalize_ty(ty);
896 let generics = generics(self.db.upcast(), func.into());
897 let substs = self.substs_for_method_call(generics, generic_args, &ty);
898 self.write_method_resolution(tgt_expr, func, substs.clone());
899 (ty, self.db.value_ty(func.into()), substs)
903 Binders::empty(&Interner, self.err_ty()),
904 Substitution::empty(&Interner),
907 let method_ty = method_ty.substitute(&Interner, &substs);
908 self.register_obligations_for_call(&method_ty);
909 let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
911 if !sig.params().is_empty() {
912 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
914 (self.err_ty(), Vec::new(), sig.ret().clone())
917 None => (self.err_ty(), Vec::new(), self.err_ty()),
919 self.unify(&expected_receiver_ty, &receiver_ty);
921 self.check_call_arguments(args, ¶m_tys);
922 self.normalize_associated_types_in(ret_ty)
925 fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) {
926 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
927 // We do this in a pretty awful way: first we type-check any arguments
928 // that are not closures, then we type-check the closures. This is so
929 // that we have more information about the types of arguments when we
930 // type-check the functions. This isn't really the right way to do this.
931 for &check_closures in &[false, true] {
932 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
933 for (&arg, param_ty) in args.iter().zip(param_iter) {
934 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
935 if is_closure != check_closures {
939 let param_ty = self.normalize_associated_types_in(param_ty);
940 self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone()));
945 fn substs_for_method_call(
947 def_generics: Generics,
948 generic_args: Option<&GenericArgs>,
951 let (parent_params, self_params, type_params, impl_trait_params) =
952 def_generics.provenance_split();
953 assert_eq!(self_params, 0); // method shouldn't have another Self param
954 let total_len = parent_params + type_params + impl_trait_params;
955 let mut substs = Vec::with_capacity(total_len);
956 // Parent arguments are unknown, except for the receiver type
957 for (_id, param) in def_generics.iter_parent() {
958 if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
959 substs.push(receiver_ty.clone());
961 substs.push(self.table.new_type_var());
964 // handle provided type arguments
965 if let Some(generic_args) = generic_args {
966 // if args are provided, it should be all of them, but we can't rely on that
967 for arg in generic_args
970 .filter(|arg| matches!(arg, GenericArg::Type(_)))
974 GenericArg::Type(type_ref) => {
975 let ty = self.make_ty(type_ref);
978 GenericArg::Lifetime(_) => {}
982 let supplied_params = substs.len();
983 for _ in supplied_params..total_len {
984 substs.push(self.table.new_type_var());
986 assert_eq!(substs.len(), total_len);
987 Substitution::from_iter(&Interner, substs)
990 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
991 let callable_ty = self.resolve_ty_shallow(&callable_ty);
992 if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(&Interner) {
993 let def: CallableDefId = from_chalk(self.db, *fn_def);
994 let generic_predicates = self.db.generic_predicates(def.into());
995 for predicate in generic_predicates.iter() {
996 let (predicate, binders) = predicate
998 .substitute(&Interner, parameters)
999 .into_value_and_skipped_binders();
1000 always!(binders.len(&Interner) == 0); // quantified where clauses not yet handled
1001 self.push_obligation(predicate.cast(&Interner));
1003 // add obligation for trait implementation, if this is a trait method
1005 CallableDefId::FunctionId(f) => {
1006 if let AssocContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container
1008 // construct a TraitRef
1009 let substs = crate::subst_prefix(
1011 generics(self.db.upcast(), trait_.into()).len(),
1013 self.push_obligation(
1014 TraitRef { trait_id: to_chalk_trait_id(trait_), substitution: substs }
1019 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}