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.clone()))
284 // Eagerly try to relate the closure type with the expected
285 // type, otherwise we often won't have enough information to
287 self.deduce_closure_type_from_expectations(&closure_ty, &sig_ty, expected);
289 // Now go through the argument patterns
290 for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
291 self.infer_pat(*arg_pat, &arg_ty, BindingMode::default());
294 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
295 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
297 self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
299 self.diverges = prev_diverges;
300 self.return_ty = prev_ret_ty;
304 Expr::Call { callee, args } => {
305 let callee_ty = self.infer_expr(*callee, &Expectation::none());
306 let canonicalized = self.canonicalize(callee_ty.clone());
307 let mut derefs = autoderef(
309 self.resolver.krate(),
311 goal: canonicalized.value.clone(),
312 environment: self.table.trait_env.env.clone(),
315 let (param_tys, ret_ty): (Vec<Ty>, Ty) = derefs
316 .find_map(|callee_deref_ty| {
318 &canonicalized.decanonicalize_ty(callee_deref_ty.value),
322 .unwrap_or((Vec::new(), self.err_ty()));
323 self.register_obligations_for_call(&callee_ty);
324 self.check_call_arguments(args, ¶m_tys);
325 self.normalize_associated_types_in(ret_ty)
327 Expr::MethodCall { receiver, args, method_name, generic_args } => self
328 .infer_method_call(tgt_expr, *receiver, args, method_name, generic_args.as_deref()),
329 Expr::Match { expr, arms } => {
330 let input_ty = self.infer_expr(*expr, &Expectation::none());
332 let expected = expected.adjust_for_branches(&mut self.table);
334 let mut result_ty = if arms.is_empty() {
335 TyKind::Never.intern(&Interner)
338 Expectation::HasType(ty) => ty.clone(),
339 _ => self.table.new_type_var(),
343 let matchee_diverges = self.diverges;
344 let mut all_arms_diverge = Diverges::Always;
347 self.diverges = Diverges::Maybe;
348 let _pat_ty = self.infer_pat(arm.pat, &input_ty, BindingMode::default());
349 if let Some(guard_expr) = arm.guard {
352 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
356 let arm_ty = self.infer_expr_inner(arm.expr, &expected);
357 all_arms_diverge &= self.diverges;
358 result_ty = self.coerce_merge_branch(Some(arm.expr), &result_ty, &arm_ty);
361 self.diverges = matchee_diverges | all_arms_diverge;
366 // FIXME this could be more efficient...
367 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
368 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or_else(|| self.err_ty())
370 Expr::Continue { .. } => TyKind::Never.intern(&Interner),
371 Expr::Break { expr, label } => {
373 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
374 ctxt.break_ty.clone()
379 let val_ty = if let Some(expr) = expr {
380 self.infer_expr(*expr, &Expectation::none())
385 // FIXME: create a synthetic `()` during lowering so we have something to refer to here?
386 let merged_type = self.coerce_merge_branch(*expr, &last_ty, &val_ty);
388 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
389 ctxt.break_ty = merged_type;
390 ctxt.may_break = true;
392 self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop {
396 TyKind::Never.intern(&Interner)
398 Expr::Return { expr } => {
399 if let Some(expr) = expr {
400 self.infer_expr_coerce(*expr, &Expectation::has_type(self.return_ty.clone()));
402 let unit = TyBuilder::unit();
403 self.coerce(&unit, &self.return_ty.clone());
405 TyKind::Never.intern(&Interner)
407 Expr::Yield { expr } => {
408 // FIXME: track yield type for coercion
409 if let Some(expr) = expr {
410 self.infer_expr(*expr, &Expectation::none());
412 TyKind::Never.intern(&Interner)
414 Expr::RecordLit { path, fields, spread } => {
415 let (ty, def_id) = self.resolve_variant(path.as_deref());
416 if let Some(variant) = def_id {
417 self.write_variant_resolution(tgt_expr.into(), variant);
420 if let Some(t) = expected.only_has_type(&mut self.table) {
426 .map(|(_, s)| s.clone())
427 .unwrap_or_else(|| Substitution::empty(&Interner));
428 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
429 let variant_data = def_id.map(|it| it.variant_data(self.db.upcast()));
430 for field in fields.iter() {
432 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
433 Some(local_id) => Some(FieldId { parent: def_id.unwrap(), local_id }),
435 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
441 let field_ty = field_def.map_or(self.err_ty(), |it| {
442 field_types[it.local_id].clone().substitute(&Interner, &substs)
444 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
446 if let Some(expr) = spread {
447 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
451 Expr::Field { expr, name } => {
452 let receiver_ty = self.infer_expr_inner(*expr, &Expectation::none());
453 let canonicalized = self.canonicalize(receiver_ty);
454 let ty = autoderef::autoderef(
456 self.resolver.krate(),
458 goal: canonicalized.value.clone(),
459 environment: self.trait_env.env.clone(),
462 .find_map(|derefed_ty| {
463 let def_db = self.db.upcast();
464 let module = self.resolver.module();
465 let is_visible = |field_id: &FieldId| {
468 self.db.field_visibilities(field_id.parent)[field_id.local_id]
469 .is_visible_from(def_db, mod_id)
473 match canonicalized.decanonicalize_ty(derefed_ty.value).kind(&Interner) {
474 TyKind::Tuple(_, substs) => name.as_tuple_index().and_then(|idx| {
478 .map(|a| a.assert_ty_ref(&Interner))
481 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
482 let local_id = self.db.struct_data(*s).variant_data.field(name)?;
483 let field = FieldId { parent: (*s).into(), local_id };
484 if is_visible(&field) {
485 self.write_field_resolution(tgt_expr, field);
487 self.db.field_types((*s).into())[field.local_id]
489 .substitute(&Interner, ¶meters),
495 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
496 let local_id = self.db.union_data(*u).variant_data.field(name)?;
497 let field = FieldId { parent: (*u).into(), local_id };
498 if is_visible(&field) {
499 self.write_field_resolution(tgt_expr, field);
501 self.db.field_types((*u).into())[field.local_id]
503 .substitute(&Interner, ¶meters),
512 .unwrap_or_else(|| self.err_ty());
513 let ty = self.insert_type_vars(ty);
514 self.normalize_associated_types_in(ty)
516 Expr::Await { expr } => {
517 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
518 self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
520 Expr::Try { expr } => {
521 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
522 self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
524 Expr::Cast { expr, type_ref } => {
525 // FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
526 let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
527 let cast_ty = self.make_ty(type_ref);
528 // FIXME check the cast...
531 Expr::Ref { expr, rawness, mutability } => {
532 let mutability = lower_to_chalk_mutability(*mutability);
533 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = expected
534 .only_has_type(&mut self.table)
536 .and_then(|t| t.as_reference_or_ptr())
538 if exp_mutability == Mutability::Mut && mutability == Mutability::Not {
539 // FIXME: record type error - expected mut reference but found shared ref,
540 // which cannot be coerced
542 if exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
543 // FIXME: record type error - expected reference but found ptr,
544 // which cannot be coerced
546 Expectation::rvalue_hint(Ty::clone(exp_inner))
550 let inner_ty = self.infer_expr_inner(*expr, &expectation);
552 Rawness::RawPtr => TyKind::Raw(mutability, inner_ty),
553 Rawness::Ref => TyKind::Ref(mutability, static_lifetime(), inner_ty),
557 Expr::Box { expr } => {
558 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
559 if let Some(box_) = self.resolve_boxed_box() {
560 TyBuilder::adt(self.db, box_)
562 .fill_with_defaults(self.db, || self.table.new_type_var())
568 Expr::UnaryOp { expr, op } => {
569 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
570 let inner_ty = self.resolve_ty_shallow(&inner_ty);
572 UnaryOp::Deref => match self.resolver.krate() {
574 let canonicalized = self.canonicalize(inner_ty);
575 match autoderef::deref(
579 goal: &canonicalized.value,
580 environment: self.trait_env.env.clone(),
583 Some(derefed_ty) => {
584 canonicalized.decanonicalize_ty(derefed_ty.value)
586 None => self.err_ty(),
589 None => self.err_ty(),
592 match inner_ty.kind(&Interner) {
593 // Fast path for builtins
594 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_))
595 | TyKind::InferenceVar(
597 TyVariableKind::Integer | TyVariableKind::Float,
599 // Otherwise we resolve via the std::ops::Neg trait
601 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
605 match inner_ty.kind(&Interner) {
606 // Fast path for builtins
607 TyKind::Scalar(Scalar::Bool | Scalar::Int(_) | Scalar::Uint(_))
608 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
609 // Otherwise we resolve via the std::ops::Not trait
611 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
616 Expr::BinaryOp { lhs, rhs, op } => match op {
618 let lhs_expectation = match op {
619 BinaryOp::LogicOp(..) => {
620 Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner))
622 _ => Expectation::none(),
624 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
625 let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
626 let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty.clone());
627 let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation));
628 let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
630 let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone());
632 if ret.is_unknown() {
633 cov_mark::hit!(infer_expr_inner_binary_operator_overload);
635 self.resolve_associated_type_with_params(
637 self.resolve_binary_op_output(op),
646 Expr::Range { lhs, rhs, range_type } => {
647 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
648 let rhs_expect = lhs_ty
650 .map_or_else(Expectation::none, |ty| Expectation::has_type(ty.clone()));
651 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
652 match (range_type, lhs_ty, rhs_ty) {
653 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
654 Some(adt) => TyBuilder::adt(self.db, adt).build(),
655 None => self.err_ty(),
657 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
658 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
659 None => self.err_ty(),
661 (RangeOp::Inclusive, None, Some(ty)) => {
662 match self.resolve_range_to_inclusive() {
663 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
664 None => self.err_ty(),
667 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
668 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
669 None => self.err_ty(),
671 (RangeOp::Inclusive, Some(_), Some(ty)) => {
672 match self.resolve_range_inclusive() {
673 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
674 None => self.err_ty(),
677 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
678 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
679 None => self.err_ty(),
681 (RangeOp::Inclusive, _, None) => self.err_ty(),
684 Expr::Index { base, index } => {
685 let base_ty = self.infer_expr_inner(*base, &Expectation::none());
686 let index_ty = self.infer_expr(*index, &Expectation::none());
688 if let (Some(index_trait), Some(krate)) =
689 (self.resolve_ops_index(), self.resolver.krate())
691 let canonicalized = self.canonicalize(base_ty);
692 let self_ty = method_resolution::resolve_indexing_op(
694 &canonicalized.value,
695 self.trait_env.clone(),
700 self_ty.map_or(self.err_ty(), |t| canonicalized.decanonicalize_ty(t.value));
701 self.resolve_associated_type_with_params(
703 self.resolve_ops_index_output(),
710 Expr::Tuple { exprs } => {
711 let mut tys = match expected
712 .only_has_type(&mut self.table)
714 .map(|t| t.kind(&Interner))
716 Some(TyKind::Tuple(_, substs)) => substs
718 .map(|a| a.assert_ty_ref(&Interner).clone())
719 .chain(repeat_with(|| self.table.new_type_var()))
721 .collect::<Vec<_>>(),
722 _ => (0..exprs.len()).map(|_| self.table.new_type_var()).collect(),
725 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
726 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
729 TyKind::Tuple(tys.len(), Substitution::from_iter(&Interner, tys)).intern(&Interner)
731 Expr::Array(array) => {
733 match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(&Interner)) {
734 Some(TyKind::Array(st, _) | TyKind::Slice(st)) => st.clone(),
735 _ => self.table.new_type_var(),
738 let expected = Expectation::has_type(elem_ty.clone());
739 let len = match array {
740 Array::ElementList(items) => {
741 for expr in items.iter() {
742 let cur_elem_ty = self.infer_expr_inner(*expr, &expected);
743 elem_ty = self.coerce_merge_branch(Some(*expr), &elem_ty, &cur_elem_ty);
745 Some(items.len() as u64)
747 Array::Repeat { initializer, repeat } => {
748 self.infer_expr_coerce(
750 &Expectation::has_type(elem_ty.clone()),
754 &Expectation::has_type(
755 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner),
759 let repeat_expr = &self.body.exprs[*repeat];
760 consteval::eval_usize(repeat_expr)
764 TyKind::Array(elem_ty, consteval::usize_const(len)).intern(&Interner)
766 Expr::Literal(lit) => match lit {
767 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(&Interner),
768 Literal::String(..) => {
769 TyKind::Ref(Mutability::Not, static_lifetime(), TyKind::Str.intern(&Interner))
772 Literal::ByteString(bs) => {
773 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(&Interner);
775 let len = consteval::usize_const(Some(bs.len() as u64));
777 let array_type = TyKind::Array(byte_type, len).intern(&Interner);
778 TyKind::Ref(Mutability::Not, static_lifetime(), array_type).intern(&Interner)
780 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(&Interner),
781 Literal::Int(_v, ty) => match ty {
783 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
786 None => self.table.new_integer_var(),
788 Literal::Uint(_v, ty) => match ty {
790 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
793 None => self.table.new_integer_var(),
795 Literal::Float(_v, ty) => match ty {
797 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
800 None => self.table.new_float_var(),
803 Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
805 // use a new type variable if we got unknown here
806 let ty = self.insert_type_vars_shallow(ty);
807 self.write_expr_ty(tgt_expr, ty.clone());
813 statements: &[Statement],
814 tail: Option<ExprId>,
815 expected: &Expectation,
817 for stmt in statements {
819 Statement::Let { pat, type_ref, initializer } => {
820 let decl_ty = type_ref
822 .map(|tr| self.make_ty(tr))
823 .unwrap_or_else(|| self.err_ty());
825 // Always use the declared type when specified
826 let mut ty = decl_ty.clone();
828 if let Some(expr) = initializer {
830 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
831 if decl_ty.is_unknown() {
836 self.infer_pat(*pat, &ty, BindingMode::default());
838 Statement::Expr { expr, .. } => {
839 self.infer_expr(*expr, &Expectation::none());
844 let ty = if let Some(expr) = tail {
845 self.infer_expr_coerce(expr, expected)
847 // Citing rustc: if there is no explicit tail expression,
848 // that is typically equivalent to a tail expression
849 // of `()` -- except if the block diverges. In that
850 // case, there is no value supplied from the tail
851 // expression (assuming there are no other breaks,
852 // this implies that the type of the block will be
854 if self.diverges.is_always() {
855 // we don't even make an attempt at coercion
856 self.table.new_maybe_never_var()
858 if let Some(t) = expected.only_has_type(&mut self.table) {
859 self.coerce(&TyBuilder::unit(), &t);
867 fn infer_method_call(
873 generic_args: Option<&GenericArgs>,
875 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
876 let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
878 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
880 let resolved = self.resolver.krate().and_then(|krate| {
881 method_resolution::lookup_method(
882 &canonicalized_receiver.value,
884 self.trait_env.clone(),
887 self.resolver.module(),
891 let (receiver_ty, method_ty, substs) = match resolved {
892 Some((ty, func)) => {
893 let ty = canonicalized_receiver.decanonicalize_ty(ty);
894 let generics = generics(self.db.upcast(), func.into());
895 let substs = self.substs_for_method_call(generics, generic_args, &ty);
896 self.write_method_resolution(tgt_expr, func, substs.clone());
897 (ty, self.db.value_ty(func.into()), substs)
901 Binders::empty(&Interner, self.err_ty()),
902 Substitution::empty(&Interner),
905 let method_ty = method_ty.substitute(&Interner, &substs);
906 self.register_obligations_for_call(&method_ty);
907 let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
909 if !sig.params().is_empty() {
910 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
912 (self.err_ty(), Vec::new(), sig.ret().clone())
915 None => (self.err_ty(), Vec::new(), self.err_ty()),
917 self.unify(&expected_receiver_ty, &receiver_ty);
919 self.check_call_arguments(args, ¶m_tys);
920 self.normalize_associated_types_in(ret_ty)
923 fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) {
924 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
925 // We do this in a pretty awful way: first we type-check any arguments
926 // that are not closures, then we type-check the closures. This is so
927 // that we have more information about the types of arguments when we
928 // type-check the functions. This isn't really the right way to do this.
929 for &check_closures in &[false, true] {
930 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
931 for (&arg, param_ty) in args.iter().zip(param_iter) {
932 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
933 if is_closure != check_closures {
937 let param_ty = self.normalize_associated_types_in(param_ty);
938 self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone()));
943 fn substs_for_method_call(
945 def_generics: Generics,
946 generic_args: Option<&GenericArgs>,
949 let (parent_params, self_params, type_params, impl_trait_params) =
950 def_generics.provenance_split();
951 assert_eq!(self_params, 0); // method shouldn't have another Self param
952 let total_len = parent_params + type_params + impl_trait_params;
953 let mut substs = Vec::with_capacity(total_len);
954 // Parent arguments are unknown, except for the receiver type
955 for (_id, param) in def_generics.iter_parent() {
956 if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
957 substs.push(receiver_ty.clone());
959 substs.push(self.table.new_type_var());
962 // handle provided type arguments
963 if let Some(generic_args) = generic_args {
964 // if args are provided, it should be all of them, but we can't rely on that
965 for arg in generic_args
968 .filter(|arg| matches!(arg, GenericArg::Type(_)))
972 GenericArg::Type(type_ref) => {
973 let ty = self.make_ty(type_ref);
976 GenericArg::Lifetime(_) => {}
980 let supplied_params = substs.len();
981 for _ in supplied_params..total_len {
982 substs.push(self.table.new_type_var());
984 assert_eq!(substs.len(), total_len);
985 Substitution::from_iter(&Interner, substs)
988 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
989 let callable_ty = self.resolve_ty_shallow(callable_ty);
990 if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(&Interner) {
991 let def: CallableDefId = from_chalk(self.db, *fn_def);
992 let generic_predicates = self.db.generic_predicates(def.into());
993 for predicate in generic_predicates.iter() {
994 let (predicate, binders) = predicate
996 .substitute(&Interner, parameters)
997 .into_value_and_skipped_binders();
998 always!(binders.len(&Interner) == 0); // quantified where clauses not yet handled
999 self.push_obligation(predicate.cast(&Interner));
1001 // add obligation for trait implementation, if this is a trait method
1003 CallableDefId::FunctionId(f) => {
1004 if let AssocContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container
1006 // construct a TraitRef
1007 let substs = crate::subst_prefix(
1009 generics(self.db.upcast(), trait_.into()).len(),
1011 self.push_obligation(
1012 TraitRef { trait_id: to_chalk_trait_id(trait_), substitution: substs }
1017 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}