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 infer::coerce::CoerceMany,
20 lower::lower_to_chalk_mutability,
22 method_resolution, op,
23 primitive::{self, UintTy},
24 static_lifetime, to_chalk_trait_id,
26 utils::{generics, Generics},
27 AdtId, Binders, CallableDefId, FnPointer, FnSig, FnSubst, InEnvironment, Interner,
28 ProjectionTyExt, Rawness, Scalar, Substitution, TraitRef, Ty, TyBuilder, TyExt, TyKind,
32 find_breakable, BindingMode, BreakableContext, Diverges, Expectation, InferenceContext,
33 InferenceDiagnostic, TypeMismatch,
36 impl<'a> InferenceContext<'a> {
37 pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
38 let ty = self.infer_expr_inner(tgt_expr, expected);
39 if self.resolve_ty_shallow(&ty).is_never() {
40 // Any expression that produces a value of type `!` must have diverged
41 self.diverges = Diverges::Always;
43 if let Some(expected_ty) = expected.only_has_type(&mut self.table) {
44 let could_unify = self.unify(&ty, &expected_ty);
46 self.result.type_mismatches.insert(
48 TypeMismatch { expected: expected_ty, actual: ty.clone() },
55 /// Infer type of expression with possibly implicit coerce to the expected type.
56 /// Return the type after possible coercion.
57 pub(super) fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty {
58 let ty = self.infer_expr_inner(expr, expected);
59 let ty = if let Some(target) = expected.only_has_type(&mut self.table) {
60 match self.coerce(Some(expr), &ty, &target) {
65 .insert(expr.into(), TypeMismatch { expected: target, actual: ty.clone() });
66 // Return actual type when type mismatch.
67 // This is needed for diagnostic when return type mismatch.
78 fn callable_sig_from_fn_trait(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
79 let krate = self.resolver.krate()?;
80 let fn_once_trait = FnTrait::FnOnce.get_id(self.db, krate)?;
81 let output_assoc_type =
82 self.db.trait_data(fn_once_trait).associated_type_by_name(&name![Output])?;
84 let mut arg_tys = vec![];
85 let arg_ty = TyBuilder::tuple(num_args)
86 .fill(repeat_with(|| {
87 let arg = self.table.new_type_var();
88 arg_tys.push(arg.clone());
94 let b = TyBuilder::assoc_type_projection(self.db, output_assoc_type);
95 if b.remaining() != 2 {
98 b.push(ty.clone()).push(arg_ty).build()
101 let trait_env = self.trait_env.env.clone();
102 let obligation = InEnvironment {
103 goal: projection.trait_ref(self.db).cast(&Interner),
104 environment: trait_env,
106 let canonical = self.canonicalize(obligation.clone());
107 if self.db.trait_solve(krate, canonical.value.cast(&Interner)).is_some() {
108 self.push_obligation(obligation.goal);
109 let return_ty = self.table.normalize_projection_ty(projection);
110 Some((arg_tys, return_ty))
116 pub(crate) fn callable_sig(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
117 match ty.callable_sig(self.db) {
118 Some(sig) => Some((sig.params().to_vec(), sig.ret().clone())),
119 None => self.callable_sig_from_fn_trait(ty, num_args),
123 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
124 self.db.unwind_if_cancelled();
126 let body = Arc::clone(&self.body); // avoid borrow checker problem
127 let ty = match &body[tgt_expr] {
128 Expr::Missing => self.err_ty(),
129 &Expr::If { condition, then_branch, else_branch } => {
130 // if let is desugared to match, so this is always simple if
133 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
136 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
137 let mut both_arms_diverge = Diverges::Always;
139 let result_ty = self.table.new_type_var();
140 let then_ty = self.infer_expr_inner(then_branch, expected);
141 both_arms_diverge &= mem::replace(&mut self.diverges, Diverges::Maybe);
142 let mut coerce = CoerceMany::new(result_ty);
143 coerce.coerce(self, Some(then_branch), &then_ty);
144 let else_ty = match else_branch {
145 Some(else_branch) => self.infer_expr_inner(else_branch, expected),
146 None => TyBuilder::unit(),
148 both_arms_diverge &= self.diverges;
149 // FIXME: create a synthetic `else {}` so we have something to refer to here instead of None?
150 coerce.coerce(self, else_branch, &else_ty);
152 self.diverges = condition_diverges | both_arms_diverge;
156 Expr::Block { statements, tail, label, id: _ } => {
157 let old_resolver = mem::replace(
159 resolver_for_expr(self.db.upcast(), self.owner, tgt_expr),
161 let ty = match label {
163 let break_ty = self.table.new_type_var();
164 self.breakables.push(BreakableContext {
166 coerce: CoerceMany::new(break_ty.clone()),
167 label: label.map(|label| self.body[label].name.clone()),
169 let ty = self.infer_block(
173 &Expectation::has_type(break_ty),
175 let ctxt = self.breakables.pop().expect("breakable stack broken");
177 ctxt.coerce.complete()
182 None => self.infer_block(tgt_expr, statements, *tail, expected),
184 self.resolver = old_resolver;
187 Expr::Unsafe { body } | Expr::Const { body } => self.infer_expr(*body, expected),
188 Expr::TryBlock { body } => {
189 let _inner = self.infer_expr(*body, expected);
190 // FIXME should be std::result::Result<{inner}, _>
193 Expr::Async { body } => {
194 // Use the first type parameter as the output type of future.
195 // existential type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
196 let inner_ty = self.infer_expr(*body, &Expectation::none());
197 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
198 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
199 TyKind::OpaqueType(opaque_ty_id, Substitution::from1(&Interner, inner_ty))
202 Expr::Loop { body, label } => {
203 self.breakables.push(BreakableContext {
205 coerce: CoerceMany::new(self.table.new_type_var()),
206 label: label.map(|label| self.body[label].name.clone()),
208 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
210 let ctxt = self.breakables.pop().expect("breakable stack broken");
213 self.diverges = Diverges::Maybe;
214 ctxt.coerce.complete()
216 TyKind::Never.intern(&Interner)
219 Expr::While { condition, body, label } => {
220 self.breakables.push(BreakableContext {
222 coerce: CoerceMany::new(self.err_ty()),
223 label: label.map(|label| self.body[label].name.clone()),
225 // while let is desugared to a match loop, so this is always simple while
228 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
230 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
231 let _ctxt = self.breakables.pop().expect("breakable stack broken");
232 // the body may not run, so it diverging doesn't mean we diverge
233 self.diverges = Diverges::Maybe;
236 Expr::For { iterable, body, pat, label } => {
237 let iterable_ty = self.infer_expr(*iterable, &Expectation::none());
239 self.breakables.push(BreakableContext {
241 coerce: CoerceMany::new(self.err_ty()),
242 label: label.map(|label| self.body[label].name.clone()),
245 self.resolve_associated_type(iterable_ty, self.resolve_into_iter_item());
247 self.infer_pat(*pat, &pat_ty, BindingMode::default());
249 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
250 let _ctxt = self.breakables.pop().expect("breakable stack broken");
251 // the body may not run, so it diverging doesn't mean we diverge
252 self.diverges = Diverges::Maybe;
255 Expr::Lambda { body, args, ret_type, arg_types } => {
256 assert_eq!(args.len(), arg_types.len());
258 let mut sig_tys = Vec::new();
260 // collect explicitly written argument types
261 for arg_type in arg_types.iter() {
262 let arg_ty = if let Some(type_ref) = arg_type {
263 self.make_ty(type_ref)
265 self.table.new_type_var()
267 sig_tys.push(arg_ty);
271 let ret_ty = match ret_type {
272 Some(type_ref) => self.make_ty(type_ref),
273 None => self.table.new_type_var(),
275 sig_tys.push(ret_ty.clone());
276 let sig_ty = TyKind::Function(FnPointer {
278 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
279 substitution: FnSubst(
280 Substitution::from_iter(&Interner, sig_tys.clone()).shifted_in(&Interner),
284 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
286 TyKind::Closure(closure_id, Substitution::from1(&Interner, sig_ty.clone()))
289 // Eagerly try to relate the closure type with the expected
290 // type, otherwise we often won't have enough information to
292 self.deduce_closure_type_from_expectations(
299 // Now go through the argument patterns
300 for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
301 self.infer_pat(*arg_pat, &arg_ty, BindingMode::default());
304 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
305 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
307 self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
309 self.diverges = prev_diverges;
310 self.return_ty = prev_ret_ty;
314 Expr::Call { callee, args } => {
315 let callee_ty = self.infer_expr(*callee, &Expectation::none());
316 let canonicalized = self.canonicalize(callee_ty.clone());
317 let mut derefs = autoderef(
319 self.resolver.krate(),
321 goal: canonicalized.value.clone(),
322 environment: self.table.trait_env.env.clone(),
325 let (param_tys, ret_ty): (Vec<Ty>, Ty) = derefs
326 .find_map(|callee_deref_ty| {
328 &canonicalized.decanonicalize_ty(callee_deref_ty.value),
332 .unwrap_or((Vec::new(), self.err_ty()));
333 self.register_obligations_for_call(&callee_ty);
334 self.check_call_arguments(args, ¶m_tys);
335 self.normalize_associated_types_in(ret_ty)
337 Expr::MethodCall { receiver, args, method_name, generic_args } => self
338 .infer_method_call(tgt_expr, *receiver, args, method_name, generic_args.as_deref()),
339 Expr::Match { expr, arms } => {
340 let input_ty = self.infer_expr(*expr, &Expectation::none());
342 let expected = expected.adjust_for_branches(&mut self.table);
344 let result_ty = if arms.is_empty() {
345 TyKind::Never.intern(&Interner)
348 Expectation::HasType(ty) => ty.clone(),
349 _ => self.table.new_type_var(),
352 let mut coerce = CoerceMany::new(result_ty);
354 let matchee_diverges = self.diverges;
355 let mut all_arms_diverge = Diverges::Always;
358 self.diverges = Diverges::Maybe;
359 let _pat_ty = self.infer_pat(arm.pat, &input_ty, BindingMode::default());
360 if let Some(guard_expr) = arm.guard {
363 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
367 let arm_ty = self.infer_expr_inner(arm.expr, &expected);
368 all_arms_diverge &= self.diverges;
369 coerce.coerce(self, Some(arm.expr), &arm_ty);
372 self.diverges = matchee_diverges | all_arms_diverge;
377 // FIXME this could be more efficient...
378 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
379 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or_else(|| self.err_ty())
381 Expr::Continue { .. } => TyKind::Never.intern(&Interner),
382 Expr::Break { expr, label } => {
383 let mut coerce = match find_breakable(&mut self.breakables, label.as_ref()) {
385 // avoiding the borrowck
388 CoerceMany::new(self.result.standard_types.unknown.clone()),
391 None => CoerceMany::new(self.result.standard_types.unknown.clone()),
394 let val_ty = if let Some(expr) = *expr {
395 self.infer_expr(expr, &Expectation::none())
400 // FIXME: create a synthetic `()` during lowering so we have something to refer to here?
401 coerce.coerce(self, *expr, &val_ty);
403 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
404 ctxt.coerce = coerce;
405 ctxt.may_break = true;
407 self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop {
412 TyKind::Never.intern(&Interner)
414 Expr::Return { expr } => {
415 if let Some(expr) = expr {
416 self.infer_expr_coerce(*expr, &Expectation::has_type(self.return_ty.clone()));
418 let unit = TyBuilder::unit();
419 let _ = self.coerce(Some(tgt_expr), &unit, &self.return_ty.clone());
421 TyKind::Never.intern(&Interner)
423 Expr::Yield { expr } => {
424 // FIXME: track yield type for coercion
425 if let Some(expr) = expr {
426 self.infer_expr(*expr, &Expectation::none());
428 TyKind::Never.intern(&Interner)
430 Expr::RecordLit { path, fields, spread } => {
431 let (ty, def_id) = self.resolve_variant(path.as_deref());
432 if let Some(variant) = def_id {
433 self.write_variant_resolution(tgt_expr.into(), variant);
436 if let Some(t) = expected.only_has_type(&mut self.table) {
442 .map(|(_, s)| s.clone())
443 .unwrap_or_else(|| Substitution::empty(&Interner));
444 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
445 let variant_data = def_id.map(|it| it.variant_data(self.db.upcast()));
446 for field in fields.iter() {
448 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
449 Some(local_id) => Some(FieldId { parent: def_id.unwrap(), local_id }),
451 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
457 let field_ty = field_def.map_or(self.err_ty(), |it| {
458 field_types[it.local_id].clone().substitute(&Interner, &substs)
460 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
462 if let Some(expr) = spread {
463 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
467 Expr::Field { expr, name } => {
468 let receiver_ty = self.infer_expr_inner(*expr, &Expectation::none());
469 let canonicalized = self.canonicalize(receiver_ty);
470 let ty = autoderef::autoderef(
472 self.resolver.krate(),
474 goal: canonicalized.value.clone(),
475 environment: self.trait_env.env.clone(),
478 .find_map(|derefed_ty| {
479 let def_db = self.db.upcast();
480 let module = self.resolver.module();
481 let is_visible = |field_id: &FieldId| {
484 self.db.field_visibilities(field_id.parent)[field_id.local_id]
485 .is_visible_from(def_db, mod_id)
489 match canonicalized.decanonicalize_ty(derefed_ty.value).kind(&Interner) {
490 TyKind::Tuple(_, substs) => name.as_tuple_index().and_then(|idx| {
494 .map(|a| a.assert_ty_ref(&Interner))
497 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
498 let local_id = self.db.struct_data(*s).variant_data.field(name)?;
499 let field = FieldId { parent: (*s).into(), local_id };
500 if is_visible(&field) {
501 self.write_field_resolution(tgt_expr, field);
503 self.db.field_types((*s).into())[field.local_id]
505 .substitute(&Interner, ¶meters),
511 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
512 let local_id = self.db.union_data(*u).variant_data.field(name)?;
513 let field = FieldId { parent: (*u).into(), local_id };
514 if is_visible(&field) {
515 self.write_field_resolution(tgt_expr, field);
517 self.db.field_types((*u).into())[field.local_id]
519 .substitute(&Interner, ¶meters),
528 .unwrap_or_else(|| self.err_ty());
529 let ty = self.insert_type_vars(ty);
530 self.normalize_associated_types_in(ty)
532 Expr::Await { expr } => {
533 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
534 self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
536 Expr::Try { expr } => {
537 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
538 self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
540 Expr::Cast { expr, type_ref } => {
541 // FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
542 let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
543 let cast_ty = self.make_ty(type_ref);
544 // FIXME check the cast...
547 Expr::Ref { expr, rawness, mutability } => {
548 let mutability = lower_to_chalk_mutability(*mutability);
549 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = expected
550 .only_has_type(&mut self.table)
552 .and_then(|t| t.as_reference_or_ptr())
554 if exp_mutability == Mutability::Mut && mutability == Mutability::Not {
555 // FIXME: record type error - expected mut reference but found shared ref,
556 // which cannot be coerced
558 if exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
559 // FIXME: record type error - expected reference but found ptr,
560 // which cannot be coerced
562 Expectation::rvalue_hint(Ty::clone(exp_inner))
566 let inner_ty = self.infer_expr_inner(*expr, &expectation);
568 Rawness::RawPtr => TyKind::Raw(mutability, inner_ty),
569 Rawness::Ref => TyKind::Ref(mutability, static_lifetime(), inner_ty),
573 Expr::Box { expr } => {
574 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
575 if let Some(box_) = self.resolve_boxed_box() {
576 TyBuilder::adt(self.db, box_)
578 .fill_with_defaults(self.db, || self.table.new_type_var())
584 Expr::UnaryOp { expr, op } => {
585 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
586 let inner_ty = self.resolve_ty_shallow(&inner_ty);
588 UnaryOp::Deref => match self.resolver.krate() {
590 let canonicalized = self.canonicalize(inner_ty);
591 match autoderef::deref(
595 goal: &canonicalized.value,
596 environment: self.trait_env.env.clone(),
599 Some(derefed_ty) => {
600 canonicalized.decanonicalize_ty(derefed_ty.value)
602 None => self.err_ty(),
605 None => self.err_ty(),
608 match inner_ty.kind(&Interner) {
609 // Fast path for builtins
610 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_))
611 | TyKind::InferenceVar(
613 TyVariableKind::Integer | TyVariableKind::Float,
615 // Otherwise we resolve via the std::ops::Neg trait
617 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
621 match inner_ty.kind(&Interner) {
622 // Fast path for builtins
623 TyKind::Scalar(Scalar::Bool | Scalar::Int(_) | Scalar::Uint(_))
624 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
625 // Otherwise we resolve via the std::ops::Not trait
627 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
632 Expr::BinaryOp { lhs, rhs, op } => match op {
634 let lhs_expectation = match op {
635 BinaryOp::LogicOp(..) => {
636 Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner))
638 _ => Expectation::none(),
640 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
641 let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
642 let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty.clone());
643 let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation));
644 let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
646 let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone());
648 if ret.is_unknown() {
649 cov_mark::hit!(infer_expr_inner_binary_operator_overload);
651 self.resolve_associated_type_with_params(
653 self.resolve_binary_op_output(op),
662 Expr::Range { lhs, rhs, range_type } => {
663 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
664 let rhs_expect = lhs_ty
666 .map_or_else(Expectation::none, |ty| Expectation::has_type(ty.clone()));
667 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
668 match (range_type, lhs_ty, rhs_ty) {
669 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
670 Some(adt) => TyBuilder::adt(self.db, adt).build(),
671 None => self.err_ty(),
673 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
674 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
675 None => self.err_ty(),
677 (RangeOp::Inclusive, None, Some(ty)) => {
678 match self.resolve_range_to_inclusive() {
679 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
680 None => self.err_ty(),
683 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
684 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
685 None => self.err_ty(),
687 (RangeOp::Inclusive, Some(_), Some(ty)) => {
688 match self.resolve_range_inclusive() {
689 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
690 None => self.err_ty(),
693 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
694 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
695 None => self.err_ty(),
697 (RangeOp::Inclusive, _, None) => self.err_ty(),
700 Expr::Index { base, index } => {
701 let base_ty = self.infer_expr_inner(*base, &Expectation::none());
702 let index_ty = self.infer_expr(*index, &Expectation::none());
704 if let (Some(index_trait), Some(krate)) =
705 (self.resolve_ops_index(), self.resolver.krate())
707 let canonicalized = self.canonicalize(base_ty);
708 let self_ty = method_resolution::resolve_indexing_op(
710 &canonicalized.value,
711 self.trait_env.clone(),
716 self_ty.map_or(self.err_ty(), |t| canonicalized.decanonicalize_ty(t.value));
717 self.resolve_associated_type_with_params(
719 self.resolve_ops_index_output(),
726 Expr::Tuple { exprs } => {
727 let mut tys = match expected
728 .only_has_type(&mut self.table)
730 .map(|t| t.kind(&Interner))
732 Some(TyKind::Tuple(_, substs)) => substs
734 .map(|a| a.assert_ty_ref(&Interner).clone())
735 .chain(repeat_with(|| self.table.new_type_var()))
737 .collect::<Vec<_>>(),
738 _ => (0..exprs.len()).map(|_| self.table.new_type_var()).collect(),
741 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
742 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
745 TyKind::Tuple(tys.len(), Substitution::from_iter(&Interner, tys)).intern(&Interner)
747 Expr::Array(array) => {
749 match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(&Interner)) {
750 Some(TyKind::Array(st, _) | TyKind::Slice(st)) => st.clone(),
751 _ => self.table.new_type_var(),
753 let mut coerce = CoerceMany::new(elem_ty.clone());
755 let expected = Expectation::has_type(elem_ty.clone());
756 let len = match array {
757 Array::ElementList(items) => {
758 for &expr in items.iter() {
759 let cur_elem_ty = self.infer_expr_inner(expr, &expected);
760 coerce.coerce(self, Some(expr), &cur_elem_ty);
762 Some(items.len() as u64)
764 &Array::Repeat { initializer, repeat } => {
765 self.infer_expr_coerce(initializer, &Expectation::has_type(elem_ty));
768 &Expectation::has_type(
769 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner),
773 let repeat_expr = &self.body.exprs[repeat];
774 consteval::eval_usize(repeat_expr)
778 TyKind::Array(coerce.complete(), consteval::usize_const(len)).intern(&Interner)
780 Expr::Literal(lit) => match lit {
781 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(&Interner),
782 Literal::String(..) => {
783 TyKind::Ref(Mutability::Not, static_lifetime(), TyKind::Str.intern(&Interner))
786 Literal::ByteString(bs) => {
787 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(&Interner);
789 let len = consteval::usize_const(Some(bs.len() as u64));
791 let array_type = TyKind::Array(byte_type, len).intern(&Interner);
792 TyKind::Ref(Mutability::Not, static_lifetime(), array_type).intern(&Interner)
794 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(&Interner),
795 Literal::Int(_v, ty) => match ty {
797 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
800 None => self.table.new_integer_var(),
802 Literal::Uint(_v, ty) => match ty {
804 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
807 None => self.table.new_integer_var(),
809 Literal::Float(_v, ty) => match ty {
811 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
814 None => self.table.new_float_var(),
817 Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
819 // use a new type variable if we got unknown here
820 let ty = self.insert_type_vars_shallow(ty);
821 self.write_expr_ty(tgt_expr, ty.clone());
828 statements: &[Statement],
829 tail: Option<ExprId>,
830 expected: &Expectation,
832 for stmt in statements {
834 Statement::Let { pat, type_ref, initializer } => {
835 let decl_ty = type_ref
837 .map(|tr| self.make_ty(tr))
838 .unwrap_or_else(|| self.err_ty());
840 // Always use the declared type when specified
841 let mut ty = decl_ty.clone();
843 if let Some(expr) = initializer {
845 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
846 if decl_ty.is_unknown() {
851 self.infer_pat(*pat, &ty, BindingMode::default());
853 Statement::Expr { expr, .. } => {
854 self.infer_expr(*expr, &Expectation::none());
859 let ty = if let Some(expr) = tail {
860 self.infer_expr_coerce(expr, expected)
862 // Citing rustc: if there is no explicit tail expression,
863 // that is typically equivalent to a tail expression
864 // of `()` -- except if the block diverges. In that
865 // case, there is no value supplied from the tail
866 // expression (assuming there are no other breaks,
867 // this implies that the type of the block will be
869 if self.diverges.is_always() {
870 // we don't even make an attempt at coercion
871 self.table.new_maybe_never_var()
873 if let Some(t) = expected.only_has_type(&mut self.table) {
874 let _ = self.coerce(Some(expr), &TyBuilder::unit(), &t);
882 fn infer_method_call(
888 generic_args: Option<&GenericArgs>,
890 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
891 let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
893 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
895 let resolved = self.resolver.krate().and_then(|krate| {
896 method_resolution::lookup_method(
897 &canonicalized_receiver.value,
899 self.trait_env.clone(),
902 self.resolver.module(),
906 let (receiver_ty, method_ty, substs) = match resolved {
907 Some((ty, func)) => {
908 let ty = canonicalized_receiver.decanonicalize_ty(ty);
909 let generics = generics(self.db.upcast(), func.into());
910 let substs = self.substs_for_method_call(generics, generic_args, &ty);
911 self.write_method_resolution(tgt_expr, func, substs.clone());
912 (ty, self.db.value_ty(func.into()), substs)
916 Binders::empty(&Interner, self.err_ty()),
917 Substitution::empty(&Interner),
920 let method_ty = method_ty.substitute(&Interner, &substs);
921 self.register_obligations_for_call(&method_ty);
922 let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
924 if !sig.params().is_empty() {
925 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
927 (self.err_ty(), Vec::new(), sig.ret().clone())
930 None => (self.err_ty(), Vec::new(), self.err_ty()),
932 self.unify(&expected_receiver_ty, &receiver_ty);
934 self.check_call_arguments(args, ¶m_tys);
935 self.normalize_associated_types_in(ret_ty)
938 fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) {
939 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
940 // We do this in a pretty awful way: first we type-check any arguments
941 // that are not closures, then we type-check the closures. This is so
942 // that we have more information about the types of arguments when we
943 // type-check the functions. This isn't really the right way to do this.
944 for &check_closures in &[false, true] {
945 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
946 for (&arg, param_ty) in args.iter().zip(param_iter) {
947 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
948 if is_closure != check_closures {
952 let param_ty = self.normalize_associated_types_in(param_ty);
953 self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone()));
958 fn substs_for_method_call(
960 def_generics: Generics,
961 generic_args: Option<&GenericArgs>,
964 let (parent_params, self_params, type_params, impl_trait_params) =
965 def_generics.provenance_split();
966 assert_eq!(self_params, 0); // method shouldn't have another Self param
967 let total_len = parent_params + type_params + impl_trait_params;
968 let mut substs = Vec::with_capacity(total_len);
969 // Parent arguments are unknown, except for the receiver type
970 for (_id, param) in def_generics.iter_parent() {
971 if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
972 substs.push(receiver_ty.clone());
974 substs.push(self.table.new_type_var());
977 // handle provided type arguments
978 if let Some(generic_args) = generic_args {
979 // if args are provided, it should be all of them, but we can't rely on that
980 for arg in generic_args
983 .filter(|arg| matches!(arg, GenericArg::Type(_)))
987 GenericArg::Type(type_ref) => {
988 let ty = self.make_ty(type_ref);
991 GenericArg::Lifetime(_) => {}
995 let supplied_params = substs.len();
996 for _ in supplied_params..total_len {
997 substs.push(self.table.new_type_var());
999 assert_eq!(substs.len(), total_len);
1000 Substitution::from_iter(&Interner, substs)
1003 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
1004 let callable_ty = self.resolve_ty_shallow(callable_ty);
1005 if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(&Interner) {
1006 let def: CallableDefId = from_chalk(self.db, *fn_def);
1007 let generic_predicates = self.db.generic_predicates(def.into());
1008 for predicate in generic_predicates.iter() {
1009 let (predicate, binders) = predicate
1011 .substitute(&Interner, parameters)
1012 .into_value_and_skipped_binders();
1013 always!(binders.len(&Interner) == 0); // quantified where clauses not yet handled
1014 self.push_obligation(predicate.cast(&Interner));
1016 // add obligation for trait implementation, if this is a trait method
1018 CallableDefId::FunctionId(f) => {
1019 if let AssocContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container
1021 // construct a TraitRef
1022 let substs = crate::subst_prefix(
1024 generics(self.db.upcast(), trait_.into()).len(),
1026 self.push_obligation(
1027 TraitRef { trait_id: to_chalk_trait_id(trait_), substitution: substs }
1032 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}