1 //! Type inference for expressions.
4 collections::hash_map::Entry,
5 iter::{repeat, repeat_with},
11 cast::Cast, fold::Shift, DebruijnIndex, GenericArgData, Mutability, TyVariableKind,
14 expr::{ArithOp, Array, BinaryOp, CmpOp, Expr, ExprId, Literal, Ordering, Statement, UnaryOp},
15 generics::TypeOrConstParamData,
16 path::{GenericArg, GenericArgs},
17 resolver::resolver_for_expr,
18 ConstParamId, FieldId, FunctionId, ItemContainerId, Lookup,
20 use hir_expand::name::{name, Name};
22 use syntax::ast::RangeOp;
25 autoderef::{self, Autoderef},
27 infer::coerce::CoerceMany,
29 const_or_path_to_chalk, generic_arg_to_chalk, lower_to_chalk_mutability, ParamLoweringMode,
31 mapping::{from_chalk, ToChalk},
33 primitive::{self, UintTy},
34 static_lifetime, to_chalk_trait_id,
35 utils::{generics, Generics},
36 AdtId, Binders, CallableDefId, FnPointer, FnSig, FnSubst, Interner, Rawness, Scalar,
37 Substitution, TraitRef, Ty, TyBuilder, TyExt, TyKind,
41 coerce::auto_deref_adjust_steps, find_breakable, BindingMode, BreakableContext, Diverges,
42 Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch,
45 impl<'a> InferenceContext<'a> {
46 pub(crate) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
47 let ty = self.infer_expr_inner(tgt_expr, expected);
48 if self.resolve_ty_shallow(&ty).is_never() {
49 // Any expression that produces a value of type `!` must have diverged
50 self.diverges = Diverges::Always;
52 if let Some(expected_ty) = expected.only_has_type(&mut self.table) {
53 let could_unify = self.unify(&ty, &expected_ty);
55 self.result.type_mismatches.insert(
57 TypeMismatch { expected: expected_ty, actual: ty.clone() },
64 /// Infer type of expression with possibly implicit coerce to the expected type.
65 /// Return the type after possible coercion.
66 pub(super) fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty {
67 let ty = self.infer_expr_inner(expr, expected);
68 if let Some(target) = expected.only_has_type(&mut self.table) {
69 match self.coerce(Some(expr), &ty, &target) {
72 self.result.type_mismatches.insert(
74 TypeMismatch { expected: target.clone(), actual: ty.clone() },
84 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
85 self.db.unwind_if_cancelled();
87 let body = Arc::clone(&self.body); // avoid borrow checker problem
88 let ty = match &body[tgt_expr] {
89 Expr::Missing => self.err_ty(),
90 &Expr::If { condition, then_branch, else_branch } => {
93 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
96 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
97 let mut both_arms_diverge = Diverges::Always;
99 let result_ty = self.table.new_type_var();
100 let then_ty = self.infer_expr_inner(then_branch, expected);
101 both_arms_diverge &= mem::replace(&mut self.diverges, Diverges::Maybe);
102 let mut coerce = CoerceMany::new(result_ty);
103 coerce.coerce(self, Some(then_branch), &then_ty);
104 let else_ty = match else_branch {
105 Some(else_branch) => self.infer_expr_inner(else_branch, expected),
106 None => TyBuilder::unit(),
108 both_arms_diverge &= self.diverges;
109 // FIXME: create a synthetic `else {}` so we have something to refer to here instead of None?
110 coerce.coerce(self, else_branch, &else_ty);
112 self.diverges = condition_diverges | both_arms_diverge;
116 &Expr::Let { pat, expr } => {
117 let input_ty = self.infer_expr(expr, &Expectation::none());
118 self.infer_pat(pat, &input_ty, BindingMode::default());
119 TyKind::Scalar(Scalar::Bool).intern(Interner)
121 Expr::Block { statements, tail, label, id: _ } => {
122 let old_resolver = mem::replace(
124 resolver_for_expr(self.db.upcast(), self.owner, tgt_expr),
126 let ty = match label {
128 let break_ty = self.table.new_type_var();
129 self.breakables.push(BreakableContext {
131 coerce: CoerceMany::new(break_ty.clone()),
132 label: label.map(|label| self.body[label].name.clone()),
134 let ty = self.infer_block(
138 &Expectation::has_type(break_ty),
140 let ctxt = self.breakables.pop().expect("breakable stack broken");
142 ctxt.coerce.complete()
147 None => self.infer_block(tgt_expr, statements, *tail, expected),
149 self.resolver = old_resolver;
152 Expr::Unsafe { body } | Expr::Const { body } => self.infer_expr(*body, expected),
153 Expr::TryBlock { body } => {
154 let _inner = self.infer_expr(*body, expected);
155 // FIXME should be std::result::Result<{inner}, _>
158 Expr::Async { body } => {
159 let ret_ty = self.table.new_type_var();
160 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
161 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
163 let inner_ty = self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
165 self.diverges = prev_diverges;
166 self.return_ty = prev_ret_ty;
168 // Use the first type parameter as the output type of future.
169 // existential type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
170 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
171 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
172 TyKind::OpaqueType(opaque_ty_id, Substitution::from1(Interner, inner_ty))
175 Expr::Loop { body, label } => {
176 self.breakables.push(BreakableContext {
178 coerce: CoerceMany::new(self.table.new_type_var()),
179 label: label.map(|label| self.body[label].name.clone()),
181 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
183 let ctxt = self.breakables.pop().expect("breakable stack broken");
186 self.diverges = Diverges::Maybe;
187 ctxt.coerce.complete()
189 TyKind::Never.intern(Interner)
192 Expr::While { condition, body, label } => {
193 self.breakables.push(BreakableContext {
195 coerce: CoerceMany::new(self.err_ty()),
196 label: label.map(|label| self.body[label].name.clone()),
200 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
202 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
203 let _ctxt = self.breakables.pop().expect("breakable stack broken");
204 // the body may not run, so it diverging doesn't mean we diverge
205 self.diverges = Diverges::Maybe;
208 Expr::For { iterable, body, pat, label } => {
209 let iterable_ty = self.infer_expr(*iterable, &Expectation::none());
211 self.breakables.push(BreakableContext {
213 coerce: CoerceMany::new(self.err_ty()),
214 label: label.map(|label| self.body[label].name.clone()),
217 self.resolve_associated_type(iterable_ty, self.resolve_into_iter_item());
219 self.infer_pat(*pat, &pat_ty, BindingMode::default());
221 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
222 let _ctxt = self.breakables.pop().expect("breakable stack broken");
223 // the body may not run, so it diverging doesn't mean we diverge
224 self.diverges = Diverges::Maybe;
227 Expr::Lambda { body, args, ret_type, arg_types } => {
228 assert_eq!(args.len(), arg_types.len());
230 let mut sig_tys = Vec::new();
232 // collect explicitly written argument types
233 for arg_type in arg_types.iter() {
234 let arg_ty = match arg_type {
235 Some(type_ref) => self.make_ty(type_ref),
236 None => self.table.new_type_var(),
238 sig_tys.push(arg_ty);
242 let ret_ty = match ret_type {
243 Some(type_ref) => self.make_ty(type_ref),
244 None => self.table.new_type_var(),
246 sig_tys.push(ret_ty.clone());
247 let sig_ty = TyKind::Function(FnPointer {
249 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
250 substitution: FnSubst(
251 Substitution::from_iter(Interner, sig_tys.clone()).shifted_in(Interner),
255 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
257 TyKind::Closure(closure_id, Substitution::from1(Interner, sig_ty.clone()))
260 // Eagerly try to relate the closure type with the expected
261 // type, otherwise we often won't have enough information to
263 self.deduce_closure_type_from_expectations(
270 // Now go through the argument patterns
271 for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
272 self.infer_pat(*arg_pat, &arg_ty, BindingMode::default());
275 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
276 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
278 self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
280 self.diverges = prev_diverges;
281 self.return_ty = prev_ret_ty;
285 Expr::Call { callee, args } => {
286 let callee_ty = self.infer_expr(*callee, &Expectation::none());
287 let mut derefs = Autoderef::new(&mut self.table, callee_ty.clone());
289 let mut derefed_callee = callee_ty.clone();
290 // manual loop to be able to access `derefs.table`
291 while let Some((callee_deref_ty, _)) = derefs.next() {
292 res = derefs.table.callable_sig(&callee_deref_ty, args.len());
294 derefed_callee = callee_deref_ty;
298 // if the function is unresolved, we use is_varargs=true to
299 // suppress the arg count diagnostic here
301 derefed_callee.callable_sig(self.db).map_or(false, |sig| sig.is_varargs)
303 let (param_tys, ret_ty) = match res {
305 let adjustments = auto_deref_adjust_steps(&derefs);
306 self.write_expr_adj(*callee, adjustments);
309 None => (Vec::new(), self.err_ty()), // FIXME diagnostic
311 let indices_to_skip = self.check_legacy_const_generics(derefed_callee, args);
312 self.register_obligations_for_call(&callee_ty);
314 let expected_inputs = self.expected_inputs_for_expected_output(
320 self.check_call_arguments(
328 self.normalize_associated_types_in(ret_ty)
330 Expr::MethodCall { receiver, args, method_name, generic_args } => self
336 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;
357 for arm in arms.iter() {
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(), false);
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());
470 let mut autoderef = Autoderef::new(&mut self.table, receiver_ty);
471 let ty = autoderef.by_ref().find_map(|(derefed_ty, _)| {
472 let (field_id, parameters) = match derefed_ty.kind(Interner) {
473 TyKind::Tuple(_, substs) => {
474 return name.as_tuple_index().and_then(|idx| {
478 .map(|a| a.assert_ty_ref(Interner))
482 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
483 let local_id = self.db.struct_data(*s).variant_data.field(name)?;
484 let field = FieldId { parent: (*s).into(), local_id };
485 (field, parameters.clone())
487 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
488 let local_id = self.db.union_data(*u).variant_data.field(name)?;
489 let field = FieldId { parent: (*u).into(), local_id };
490 (field, parameters.clone())
494 let module = self.resolver.module();
495 let is_visible = module
497 self.db.field_visibilities(field_id.parent)[field_id.local_id]
498 .is_visible_from(self.db.upcast(), mod_id)
502 // Write down the first field resolution even if it is not visible
503 // This aids IDE features for private fields like goto def and in
504 // case of autoderef finding an applicable field, this will be
505 // overwritten in a following cycle
506 if let Entry::Vacant(entry) = self.result.field_resolutions.entry(tgt_expr)
508 entry.insert(field_id);
512 // can't have `write_field_resolution` here because `self.table` is borrowed :(
513 self.result.field_resolutions.insert(tgt_expr, field_id);
514 let ty = self.db.field_types(field_id.parent)[field_id.local_id]
516 .substitute(Interner, ¶meters);
521 let adjustments = auto_deref_adjust_steps(&autoderef);
522 self.write_expr_adj(*expr, adjustments);
523 let ty = self.insert_type_vars(ty);
524 let ty = self.normalize_associated_types_in(ty);
531 Expr::Await { expr } => {
532 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
533 self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
535 Expr::Try { expr } => {
536 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
537 self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
539 Expr::Cast { expr, type_ref } => {
540 // FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
541 let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
542 let cast_ty = self.make_ty(type_ref);
543 // FIXME check the cast...
546 Expr::Ref { expr, rawness, mutability } => {
547 let mutability = lower_to_chalk_mutability(*mutability);
548 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = expected
549 .only_has_type(&mut self.table)
551 .and_then(|t| t.as_reference_or_ptr())
553 if exp_mutability == Mutability::Mut && mutability == Mutability::Not {
554 // FIXME: record type error - expected mut reference but found shared ref,
555 // which cannot be coerced
557 if exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
558 // FIXME: record type error - expected reference but found ptr,
559 // which cannot be coerced
561 Expectation::rvalue_hint(&mut self.table, Ty::clone(exp_inner))
565 let inner_ty = self.infer_expr_inner(*expr, &expectation);
567 Rawness::RawPtr => TyKind::Raw(mutability, inner_ty),
568 Rawness::Ref => TyKind::Ref(mutability, static_lifetime(), inner_ty),
572 Expr::Box { expr } => {
573 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
574 if let Some(box_) = self.resolve_boxed_box() {
575 TyBuilder::adt(self.db, box_)
577 .fill_with_defaults(self.db, || self.table.new_type_var())
583 Expr::UnaryOp { expr, op } => {
584 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
585 let inner_ty = self.resolve_ty_shallow(&inner_ty);
588 autoderef::deref(&mut self.table, inner_ty).unwrap_or_else(|| self.err_ty())
591 match inner_ty.kind(Interner) {
592 // Fast path for builtins
593 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_))
594 | TyKind::InferenceVar(
596 TyVariableKind::Integer | TyVariableKind::Float,
598 // Otherwise we resolve via the std::ops::Neg trait
600 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
604 match inner_ty.kind(Interner) {
605 // Fast path for builtins
606 TyKind::Scalar(Scalar::Bool | Scalar::Int(_) | Scalar::Uint(_))
607 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
608 // Otherwise we resolve via the std::ops::Not trait
610 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
615 Expr::BinaryOp { lhs, rhs, op } => match op {
616 Some(BinaryOp::Assignment { op: None }) => {
617 let lhs_ty = self.infer_expr(*lhs, &Expectation::none());
618 self.infer_expr_coerce(*rhs, &Expectation::has_type(lhs_ty));
619 self.result.standard_types.unit.clone()
621 Some(BinaryOp::LogicOp(_)) => {
622 let bool_ty = self.result.standard_types.bool_.clone();
623 self.infer_expr_coerce(*lhs, &Expectation::HasType(bool_ty.clone()));
624 let lhs_diverges = self.diverges;
625 self.infer_expr_coerce(*rhs, &Expectation::HasType(bool_ty.clone()));
626 // Depending on the LHS' value, the RHS can never execute.
627 self.diverges = lhs_diverges;
630 Some(op) => self.infer_overloadable_binop(*lhs, *op, *rhs, tgt_expr),
633 Expr::Range { lhs, rhs, range_type } => {
634 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
635 let rhs_expect = lhs_ty
637 .map_or_else(Expectation::none, |ty| Expectation::has_type(ty.clone()));
638 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
639 match (range_type, lhs_ty, rhs_ty) {
640 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
641 Some(adt) => TyBuilder::adt(self.db, adt).build(),
642 None => self.err_ty(),
644 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
645 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
646 None => self.err_ty(),
648 (RangeOp::Inclusive, None, Some(ty)) => {
649 match self.resolve_range_to_inclusive() {
650 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
651 None => self.err_ty(),
654 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
655 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
656 None => self.err_ty(),
658 (RangeOp::Inclusive, Some(_), Some(ty)) => {
659 match self.resolve_range_inclusive() {
660 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
661 None => self.err_ty(),
664 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
665 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
666 None => self.err_ty(),
668 (RangeOp::Inclusive, _, None) => self.err_ty(),
671 Expr::Index { base, index } => {
672 let base_ty = self.infer_expr_inner(*base, &Expectation::none());
673 let index_ty = self.infer_expr(*index, &Expectation::none());
675 if let Some(index_trait) = self.resolve_ops_index() {
676 let canonicalized = self.canonicalize(base_ty.clone());
677 let receiver_adjustments = method_resolution::resolve_indexing_op(
679 self.trait_env.clone(),
683 let (self_ty, adj) = receiver_adjustments
684 .map_or((self.err_ty(), Vec::new()), |adj| {
685 adj.apply(&mut self.table, base_ty)
687 self.write_expr_adj(*base, adj);
688 self.resolve_associated_type_with_params(
690 self.resolve_ops_index_output(),
691 &[GenericArgData::Ty(index_ty).intern(Interner)],
697 Expr::Tuple { exprs } => {
698 let mut tys = match expected
699 .only_has_type(&mut self.table)
701 .map(|t| t.kind(Interner))
703 Some(TyKind::Tuple(_, substs)) => substs
705 .map(|a| a.assert_ty_ref(Interner).clone())
706 .chain(repeat_with(|| self.table.new_type_var()))
708 .collect::<Vec<_>>(),
709 _ => (0..exprs.len()).map(|_| self.table.new_type_var()).collect(),
712 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
713 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
716 TyKind::Tuple(tys.len(), Substitution::from_iter(Interner, tys)).intern(Interner)
718 Expr::Array(array) => {
720 match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(Interner)) {
721 Some(TyKind::Array(st, _) | TyKind::Slice(st)) => st.clone(),
722 _ => self.table.new_type_var(),
724 let mut coerce = CoerceMany::new(elem_ty.clone());
726 let expected = Expectation::has_type(elem_ty.clone());
727 let len = match array {
728 Array::ElementList(items) => {
729 for &expr in items.iter() {
730 let cur_elem_ty = self.infer_expr_inner(expr, &expected);
731 coerce.coerce(self, Some(expr), &cur_elem_ty);
733 consteval::usize_const(Some(items.len() as u64))
735 &Array::Repeat { initializer, repeat } => {
736 self.infer_expr_coerce(initializer, &Expectation::has_type(elem_ty));
739 &Expectation::has_type(
740 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(Interner),
744 if let Some(g_def) = self.owner.as_generic_def_id() {
745 let generics = generics(self.db.upcast(), g_def);
746 consteval::eval_to_const(
748 ParamLoweringMode::Placeholder,
751 DebruijnIndex::INNERMOST,
754 consteval::usize_const(None)
759 TyKind::Array(coerce.complete(), len).intern(Interner)
761 Expr::Literal(lit) => match lit {
762 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
763 Literal::String(..) => {
764 TyKind::Ref(Mutability::Not, static_lifetime(), TyKind::Str.intern(Interner))
767 Literal::ByteString(bs) => {
768 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner);
770 let len = consteval::usize_const(Some(bs.len() as u64));
772 let array_type = TyKind::Array(byte_type, len).intern(Interner);
773 TyKind::Ref(Mutability::Not, static_lifetime(), array_type).intern(Interner)
775 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(Interner),
776 Literal::Int(_v, ty) => match ty {
778 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
781 None => self.table.new_integer_var(),
783 Literal::Uint(_v, ty) => match ty {
785 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
788 None => self.table.new_integer_var(),
790 Literal::Float(_v, ty) => match ty {
792 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
795 None => self.table.new_float_var(),
798 Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
800 // use a new type variable if we got unknown here
801 let ty = self.insert_type_vars_shallow(ty);
802 self.write_expr_ty(tgt_expr, ty.clone());
806 fn infer_overloadable_binop(
813 let lhs_expectation = Expectation::none();
814 let lhs_ty = self.infer_expr(lhs, &lhs_expectation);
815 let rhs_ty = self.table.new_type_var();
817 let func = self.resolve_binop_method(op);
818 let func = match func {
821 let rhs_ty = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone());
822 let rhs_ty = self.infer_expr_coerce(rhs, &Expectation::from_option(rhs_ty));
824 .builtin_binary_op_return_ty(op, lhs_ty, rhs_ty)
825 .unwrap_or_else(|| self.err_ty());
829 let subst = TyBuilder::subst_for_def(self.db, func)
830 .push(lhs_ty.clone())
831 .push(rhs_ty.clone())
833 self.write_method_resolution(tgt_expr, func, subst.clone());
835 let method_ty = self.db.value_ty(func.into()).substitute(Interner, &subst);
836 self.register_obligations_for_call(&method_ty);
838 self.infer_expr_coerce(rhs, &Expectation::has_type(rhs_ty.clone()));
840 let ret_ty = match method_ty.callable_sig(self.db) {
841 Some(sig) => sig.ret().clone(),
842 None => self.err_ty(),
845 let ret_ty = self.normalize_associated_types_in(ret_ty);
847 // FIXME: record autoref adjustments
849 // use knowledge of built-in binary ops, which can sometimes help inference
850 if let Some(builtin_rhs) = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone()) {
851 self.unify(&builtin_rhs, &rhs_ty);
853 if let Some(builtin_ret) = self.builtin_binary_op_return_ty(op, lhs_ty, rhs_ty) {
854 self.unify(&builtin_ret, &ret_ty);
863 statements: &[Statement],
864 tail: Option<ExprId>,
865 expected: &Expectation,
867 for stmt in statements {
869 Statement::Let { pat, type_ref, initializer, else_branch } => {
870 let decl_ty = type_ref
872 .map(|tr| self.make_ty(tr))
873 .unwrap_or_else(|| self.err_ty());
875 // Always use the declared type when specified
876 let mut ty = decl_ty.clone();
878 if let Some(expr) = initializer {
880 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
881 if decl_ty.is_unknown() {
886 if let Some(expr) = else_branch {
887 self.infer_expr_coerce(
889 &Expectation::has_type(Ty::new(Interner, TyKind::Never)),
893 self.infer_pat(*pat, &ty, BindingMode::default());
895 Statement::Expr { expr, .. } => {
896 self.infer_expr(*expr, &Expectation::none());
901 if let Some(expr) = tail {
902 self.infer_expr_coerce(expr, expected)
904 // Citing rustc: if there is no explicit tail expression,
905 // that is typically equivalent to a tail expression
906 // of `()` -- except if the block diverges. In that
907 // case, there is no value supplied from the tail
908 // expression (assuming there are no other breaks,
909 // this implies that the type of the block will be
911 if self.diverges.is_always() {
912 // we don't even make an attempt at coercion
913 self.table.new_maybe_never_var()
915 if let Some(t) = expected.only_has_type(&mut self.table) {
916 if self.coerce(Some(expr), &TyBuilder::unit(), &t).is_err() {
917 self.result.type_mismatches.insert(
919 TypeMismatch { expected: t.clone(), actual: TyBuilder::unit() },
930 fn infer_method_call(
936 generic_args: Option<&GenericArgs>,
937 expected: &Expectation,
939 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
940 let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
942 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
944 let resolved = method_resolution::lookup_method(
945 &canonicalized_receiver.value,
947 self.trait_env.clone(),
949 self.resolver.module().into(),
952 let (receiver_ty, method_ty, substs) = match resolved {
953 Some((adjust, func)) => {
954 let (ty, adjustments) = adjust.apply(&mut self.table, receiver_ty);
955 let generics = generics(self.db.upcast(), func.into());
956 let substs = self.substs_for_method_call(generics, generic_args);
957 self.write_expr_adj(receiver, adjustments);
958 self.write_method_resolution(tgt_expr, func, substs.clone());
959 (ty, self.db.value_ty(func.into()), substs)
963 Binders::empty(Interner, self.err_ty()),
964 Substitution::empty(Interner),
967 let method_ty = method_ty.substitute(Interner, &substs);
968 self.register_obligations_for_call(&method_ty);
969 let (formal_receiver_ty, param_tys, ret_ty, is_varargs) =
970 match method_ty.callable_sig(self.db) {
972 if !sig.params().is_empty() {
974 sig.params()[0].clone(),
975 sig.params()[1..].to_vec(),
980 (self.err_ty(), Vec::new(), sig.ret().clone(), sig.is_varargs)
983 None => (self.err_ty(), Vec::new(), self.err_ty(), true),
985 self.unify(&formal_receiver_ty, &receiver_ty);
987 let expected_inputs =
988 self.expected_inputs_for_expected_output(expected, ret_ty.clone(), param_tys.clone());
990 self.check_call_arguments(tgt_expr, args, &expected_inputs, ¶m_tys, &[], is_varargs);
991 self.normalize_associated_types_in(ret_ty)
994 fn expected_inputs_for_expected_output(
996 expected_output: &Expectation,
1000 if let Some(expected_ty) = expected_output.to_option(&mut self.table) {
1001 self.table.fudge_inference(|table| {
1002 if table.try_unify(&expected_ty, &output).is_ok() {
1003 table.resolve_with_fallback(inputs, &|var, kind, _, _| match kind {
1004 chalk_ir::VariableKind::Ty(tk) => var.to_ty(Interner, tk).cast(Interner),
1005 chalk_ir::VariableKind::Lifetime => {
1006 var.to_lifetime(Interner).cast(Interner)
1008 chalk_ir::VariableKind::Const(ty) => {
1009 var.to_const(Interner, ty).cast(Interner)
1021 fn check_call_arguments(
1025 expected_inputs: &[Ty],
1027 skip_indices: &[u32],
1030 if args.len() != param_tys.len() + skip_indices.len() && !is_varargs {
1031 self.push_diagnostic(InferenceDiagnostic::MismatchedArgCount {
1033 expected: param_tys.len() + skip_indices.len(),
1038 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
1039 // We do this in a pretty awful way: first we type-check any arguments
1040 // that are not closures, then we type-check the closures. This is so
1041 // that we have more information about the types of arguments when we
1042 // type-check the functions. This isn't really the right way to do this.
1043 for &check_closures in &[false, true] {
1044 let mut skip_indices = skip_indices.into_iter().copied().fuse().peekable();
1045 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
1046 let expected_iter = expected_inputs
1049 .chain(param_iter.clone().skip(expected_inputs.len()));
1050 for (idx, ((&arg, param_ty), expected_ty)) in
1051 args.iter().zip(param_iter).zip(expected_iter).enumerate()
1053 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
1054 if is_closure != check_closures {
1058 while skip_indices.peek().map_or(false, |i| *i < idx as u32) {
1059 skip_indices.next();
1061 if skip_indices.peek().copied() == Some(idx as u32) {
1065 // the difference between param_ty and expected here is that
1066 // expected is the parameter when the expected *return* type is
1067 // taken into account. So in `let _: &[i32] = identity(&[1, 2])`
1068 // the expected type is already `&[i32]`, whereas param_ty is
1069 // still an unbound type variable. We don't always want to force
1070 // the parameter to coerce to the expected type (for example in
1071 // `coerce_unsize_expected_type_4`).
1072 let param_ty = self.normalize_associated_types_in(param_ty);
1073 let expected = Expectation::rvalue_hint(&mut self.table, expected_ty);
1074 // infer with the expected type we have...
1075 let ty = self.infer_expr_inner(arg, &expected);
1077 // then coerce to either the expected type or just the formal parameter type
1078 let coercion_target = if let Some(ty) = expected.only_has_type(&mut self.table) {
1079 // if we are coercing to the expectation, unify with the
1080 // formal parameter type to connect everything
1081 self.unify(&ty, ¶m_ty);
1086 if !coercion_target.is_unknown() {
1087 if self.coerce(Some(arg), &ty, &coercion_target).is_err() {
1088 self.result.type_mismatches.insert(
1090 TypeMismatch { expected: coercion_target, actual: ty.clone() },
1098 fn substs_for_method_call(
1100 def_generics: Generics,
1101 generic_args: Option<&GenericArgs>,
1103 let (parent_params, self_params, type_params, const_params, impl_trait_params) =
1104 def_generics.provenance_split();
1105 assert_eq!(self_params, 0); // method shouldn't have another Self param
1106 let total_len = parent_params + type_params + const_params + impl_trait_params;
1107 let mut substs = Vec::with_capacity(total_len);
1108 // Parent arguments are unknown
1109 for (id, param) in def_generics.iter_parent() {
1111 TypeOrConstParamData::TypeParamData(_) => {
1112 substs.push(GenericArgData::Ty(self.table.new_type_var()).intern(Interner));
1114 TypeOrConstParamData::ConstParamData(_) => {
1115 let ty = self.db.const_param_ty(ConstParamId::from_unchecked(id));
1117 .push(GenericArgData::Const(self.table.new_const_var(ty)).intern(Interner));
1121 // handle provided arguments
1122 if let Some(generic_args) = generic_args {
1123 // if args are provided, it should be all of them, but we can't rely on that
1124 for (arg, kind_id) in generic_args
1127 .filter(|arg| !matches!(arg, GenericArg::Lifetime(_)))
1128 .take(type_params + const_params)
1129 .zip(def_generics.iter_id().skip(parent_params))
1131 if let Some(g) = generic_arg_to_chalk(
1136 |this, type_ref| this.make_ty(type_ref),
1138 const_or_path_to_chalk(
1142 ParamLoweringMode::Placeholder,
1143 || generics(this.db.upcast(), (&this.resolver).generic_def().unwrap()),
1144 DebruijnIndex::INNERMOST,
1152 for (id, data) in def_generics.iter().skip(substs.len()) {
1154 TypeOrConstParamData::TypeParamData(_) => {
1155 substs.push(GenericArgData::Ty(self.table.new_type_var()).intern(Interner))
1157 TypeOrConstParamData::ConstParamData(_) => {
1159 GenericArgData::Const(self.table.new_const_var(
1160 self.db.const_param_ty(ConstParamId::from_unchecked(id)),
1167 assert_eq!(substs.len(), total_len);
1168 Substitution::from_iter(Interner, substs)
1171 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
1172 let callable_ty = self.resolve_ty_shallow(callable_ty);
1173 if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(Interner) {
1174 let def: CallableDefId = from_chalk(self.db, *fn_def);
1175 let generic_predicates = self.db.generic_predicates(def.into());
1176 for predicate in generic_predicates.iter() {
1177 let (predicate, binders) = predicate
1179 .substitute(Interner, parameters)
1180 .into_value_and_skipped_binders();
1181 always!(binders.len(Interner) == 0); // quantified where clauses not yet handled
1182 self.push_obligation(predicate.cast(Interner));
1184 // add obligation for trait implementation, if this is a trait method
1186 CallableDefId::FunctionId(f) => {
1187 if let ItemContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container {
1188 // construct a TraitRef
1189 let substs = crate::subst_prefix(
1191 generics(self.db.upcast(), trait_.into()).len(),
1193 self.push_obligation(
1194 TraitRef { trait_id: to_chalk_trait_id(trait_), substitution: substs }
1199 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}
1204 /// Returns the argument indices to skip.
1205 fn check_legacy_const_generics(&mut self, callee: Ty, args: &[ExprId]) -> Vec<u32> {
1206 let (func, subst) = match callee.kind(Interner) {
1207 TyKind::FnDef(fn_id, subst) => {
1208 let callable = CallableDefId::from_chalk(self.db, *fn_id);
1209 let func = match callable {
1210 CallableDefId::FunctionId(f) => f,
1211 _ => return Vec::new(),
1215 _ => return Vec::new(),
1218 let data = self.db.function_data(func);
1219 if data.legacy_const_generics_indices.is_empty() {
1223 // only use legacy const generics if the param count matches with them
1224 if data.params.len() + data.legacy_const_generics_indices.len() != args.len() {
1225 if args.len() <= data.params.len() {
1228 // there are more parameters than there should be without legacy
1229 // const params; use them
1230 let mut indices = data.legacy_const_generics_indices.clone();
1236 // check legacy const parameters
1237 for (subst_idx, arg_idx) in data.legacy_const_generics_indices.iter().copied().enumerate() {
1238 let arg = match subst.at(Interner, subst_idx).constant(Interner) {
1240 None => continue, // not a const parameter?
1242 if arg_idx >= args.len() as u32 {
1245 let _ty = arg.data(Interner).ty.clone();
1246 let expected = Expectation::none(); // FIXME use actual const ty, when that is lowered correctly
1247 self.infer_expr(args[arg_idx as usize], &expected);
1248 // FIXME: evaluate and unify with the const
1250 let mut indices = data.legacy_const_generics_indices.clone();
1255 fn builtin_binary_op_return_ty(&mut self, op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Option<Ty> {
1256 let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
1257 let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
1259 BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => {
1260 Some(TyKind::Scalar(Scalar::Bool).intern(Interner))
1262 BinaryOp::Assignment { .. } => Some(TyBuilder::unit()),
1263 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => {
1264 // all integer combinations are valid here
1266 lhs_ty.kind(Interner),
1267 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1268 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1270 rhs_ty.kind(Interner),
1271 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1272 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1279 BinaryOp::ArithOp(_) => match (lhs_ty.kind(Interner), rhs_ty.kind(Interner)) {
1280 // (int, int) | (uint, uint) | (float, float)
1281 (TyKind::Scalar(Scalar::Int(_)), TyKind::Scalar(Scalar::Int(_)))
1282 | (TyKind::Scalar(Scalar::Uint(_)), TyKind::Scalar(Scalar::Uint(_)))
1283 | (TyKind::Scalar(Scalar::Float(_)), TyKind::Scalar(Scalar::Float(_))) => {
1286 // ({int}, int) | ({int}, uint)
1288 TyKind::InferenceVar(_, TyVariableKind::Integer),
1289 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1291 // (int, {int}) | (uint, {int})
1293 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1294 TyKind::InferenceVar(_, TyVariableKind::Integer),
1296 // ({float} | float)
1298 TyKind::InferenceVar(_, TyVariableKind::Float),
1299 TyKind::Scalar(Scalar::Float(_)),
1303 TyKind::Scalar(Scalar::Float(_)),
1304 TyKind::InferenceVar(_, TyVariableKind::Float),
1306 // ({int}, {int}) | ({float}, {float})
1308 TyKind::InferenceVar(_, TyVariableKind::Integer),
1309 TyKind::InferenceVar(_, TyVariableKind::Integer),
1312 TyKind::InferenceVar(_, TyVariableKind::Float),
1313 TyKind::InferenceVar(_, TyVariableKind::Float),
1320 fn builtin_binary_op_rhs_expectation(&mut self, op: BinaryOp, lhs_ty: Ty) -> Option<Ty> {
1322 BinaryOp::LogicOp(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
1323 BinaryOp::Assignment { op: None } => lhs_ty,
1324 BinaryOp::CmpOp(CmpOp::Eq { .. }) => match self
1325 .resolve_ty_shallow(&lhs_ty)
1328 TyKind::Scalar(_) | TyKind::Str => lhs_ty,
1329 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1332 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => return None,
1333 BinaryOp::CmpOp(CmpOp::Ord { .. })
1334 | BinaryOp::Assignment { op: Some(_) }
1335 | BinaryOp::ArithOp(_) => match self.resolve_ty_shallow(&lhs_ty).kind(Interner) {
1336 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_)) => lhs_ty,
1337 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1343 fn resolve_binop_method(&self, op: BinaryOp) -> Option<FunctionId> {
1344 let (name, lang_item) = match op {
1345 BinaryOp::LogicOp(_) => return None,
1346 BinaryOp::ArithOp(aop) => match aop {
1347 ArithOp::Add => (name!(add), name!(add)),
1348 ArithOp::Mul => (name!(mul), name!(mul)),
1349 ArithOp::Sub => (name!(sub), name!(sub)),
1350 ArithOp::Div => (name!(div), name!(div)),
1351 ArithOp::Rem => (name!(rem), name!(rem)),
1352 ArithOp::Shl => (name!(shl), name!(shl)),
1353 ArithOp::Shr => (name!(shr), name!(shr)),
1354 ArithOp::BitXor => (name!(bitxor), name!(bitxor)),
1355 ArithOp::BitOr => (name!(bitor), name!(bitor)),
1356 ArithOp::BitAnd => (name!(bitand), name!(bitand)),
1358 BinaryOp::Assignment { op: Some(aop) } => match aop {
1359 ArithOp::Add => (name!(add_assign), name!(add_assign)),
1360 ArithOp::Mul => (name!(mul_assign), name!(mul_assign)),
1361 ArithOp::Sub => (name!(sub_assign), name!(sub_assign)),
1362 ArithOp::Div => (name!(div_assign), name!(div_assign)),
1363 ArithOp::Rem => (name!(rem_assign), name!(rem_assign)),
1364 ArithOp::Shl => (name!(shl_assign), name!(shl_assign)),
1365 ArithOp::Shr => (name!(shr_assign), name!(shr_assign)),
1366 ArithOp::BitXor => (name!(bitxor_assign), name!(bitxor_assign)),
1367 ArithOp::BitOr => (name!(bitor_assign), name!(bitor_assign)),
1368 ArithOp::BitAnd => (name!(bitand_assign), name!(bitand_assign)),
1370 BinaryOp::CmpOp(cop) => match cop {
1371 CmpOp::Eq { negated: false } => (name!(eq), name!(eq)),
1372 CmpOp::Eq { negated: true } => (name!(ne), name!(eq)),
1373 CmpOp::Ord { ordering: Ordering::Less, strict: false } => {
1374 (name!(le), name!(partial_ord))
1376 CmpOp::Ord { ordering: Ordering::Less, strict: true } => {
1377 (name!(lt), name!(partial_ord))
1379 CmpOp::Ord { ordering: Ordering::Greater, strict: false } => {
1380 (name!(ge), name!(partial_ord))
1382 CmpOp::Ord { ordering: Ordering::Greater, strict: true } => {
1383 (name!(gt), name!(partial_ord))
1386 BinaryOp::Assignment { op: None } => return None,
1389 let trait_ = self.resolve_lang_item(lang_item)?.as_trait()?;
1391 self.db.trait_data(trait_).method_by_name(&name)