1 //! Type inference for expressions.
4 iter::{repeat, repeat_with},
9 use chalk_ir::{cast::Cast, fold::Shift, Mutability, TyVariableKind};
11 expr::{ArithOp, Array, BinaryOp, CmpOp, Expr, ExprId, Literal, Ordering, Statement, UnaryOp},
12 path::{GenericArg, GenericArgs},
13 resolver::resolver_for_expr,
14 FieldId, FunctionId, ItemContainerId, Lookup,
16 use hir_expand::name::{name, Name};
18 use syntax::ast::RangeOp;
21 autoderef::{self, Autoderef},
23 infer::coerce::CoerceMany,
24 lower::lower_to_chalk_mutability,
27 primitive::{self, UintTy},
28 static_lifetime, to_chalk_trait_id,
30 utils::{generics, Generics},
31 AdtId, Binders, CallableDefId, FnPointer, FnSig, FnSubst, InEnvironment, Interner,
32 ProjectionTyExt, Rawness, Scalar, Substitution, TraitRef, Ty, TyBuilder, TyExt, TyKind,
36 find_breakable, BindingMode, BreakableContext, Diverges, Expectation, InferenceContext,
37 InferenceDiagnostic, TypeMismatch,
40 impl<'a> InferenceContext<'a> {
41 pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
42 let ty = self.infer_expr_inner(tgt_expr, expected);
43 if self.resolve_ty_shallow(&ty).is_never() {
44 // Any expression that produces a value of type `!` must have diverged
45 self.diverges = Diverges::Always;
47 if let Some(expected_ty) = expected.only_has_type(&mut self.table) {
48 let could_unify = self.unify(&ty, &expected_ty);
50 self.result.type_mismatches.insert(
52 TypeMismatch { expected: expected_ty, actual: ty.clone() },
59 /// Infer type of expression with possibly implicit coerce to the expected type.
60 /// Return the type after possible coercion.
61 pub(super) fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty {
62 let ty = self.infer_expr_inner(expr, expected);
63 if let Some(target) = expected.only_has_type(&mut self.table) {
64 match self.coerce(Some(expr), &ty, &target) {
69 .insert(expr.into(), TypeMismatch { expected: target, actual: ty.clone() });
70 // Return actual type when type mismatch.
71 // This is needed for diagnostic when return type mismatch.
80 fn callable_sig_from_fn_trait(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
81 let krate = self.resolver.krate()?;
82 let fn_once_trait = FnTrait::FnOnce.get_id(self.db, krate)?;
83 let output_assoc_type =
84 self.db.trait_data(fn_once_trait).associated_type_by_name(&name![Output])?;
86 let mut arg_tys = vec![];
87 let arg_ty = TyBuilder::tuple(num_args)
88 .fill(repeat_with(|| {
89 let arg = self.table.new_type_var();
90 arg_tys.push(arg.clone());
96 let b = TyBuilder::assoc_type_projection(self.db, output_assoc_type);
97 if b.remaining() != 2 {
100 b.push(ty.clone()).push(arg_ty).build()
103 let trait_env = self.trait_env.env.clone();
104 let obligation = InEnvironment {
105 goal: projection.trait_ref(self.db).cast(Interner),
106 environment: trait_env,
108 let canonical = self.canonicalize(obligation.clone());
109 if self.db.trait_solve(krate, canonical.value.cast(Interner)).is_some() {
110 self.push_obligation(obligation.goal);
111 let return_ty = self.table.normalize_projection_ty(projection);
112 Some((arg_tys, return_ty))
118 pub(crate) fn callable_sig(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
119 match ty.callable_sig(self.db) {
120 Some(sig) => Some((sig.params().to_vec(), sig.ret().clone())),
121 None => self.callable_sig_from_fn_trait(ty, num_args),
125 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
126 self.db.unwind_if_cancelled();
128 let body = Arc::clone(&self.body); // avoid borrow checker problem
129 let ty = match &body[tgt_expr] {
130 Expr::Missing => self.err_ty(),
131 &Expr::If { condition, then_branch, else_branch } => {
132 // if let is desugared to match, so this is always simple if
135 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
138 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
139 let mut both_arms_diverge = Diverges::Always;
141 let result_ty = self.table.new_type_var();
142 let then_ty = self.infer_expr_inner(then_branch, expected);
143 both_arms_diverge &= mem::replace(&mut self.diverges, Diverges::Maybe);
144 let mut coerce = CoerceMany::new(result_ty);
145 coerce.coerce(self, Some(then_branch), &then_ty);
146 let else_ty = match else_branch {
147 Some(else_branch) => self.infer_expr_inner(else_branch, expected),
148 None => TyBuilder::unit(),
150 both_arms_diverge &= self.diverges;
151 // FIXME: create a synthetic `else {}` so we have something to refer to here instead of None?
152 coerce.coerce(self, else_branch, &else_ty);
154 self.diverges = condition_diverges | both_arms_diverge;
158 &Expr::Let { pat, expr } => {
159 let input_ty = self.infer_expr(expr, &Expectation::none());
160 self.infer_pat(pat, &input_ty, BindingMode::default());
161 TyKind::Scalar(Scalar::Bool).intern(Interner)
163 Expr::Block { statements, tail, label, id: _ } => {
164 let old_resolver = mem::replace(
166 resolver_for_expr(self.db.upcast(), self.owner, tgt_expr),
168 let ty = match label {
170 let break_ty = self.table.new_type_var();
171 self.breakables.push(BreakableContext {
173 coerce: CoerceMany::new(break_ty.clone()),
174 label: label.map(|label| self.body[label].name.clone()),
176 let ty = self.infer_block(
180 &Expectation::has_type(break_ty),
182 let ctxt = self.breakables.pop().expect("breakable stack broken");
184 ctxt.coerce.complete()
189 None => self.infer_block(tgt_expr, statements, *tail, expected),
191 self.resolver = old_resolver;
194 Expr::Unsafe { body } | Expr::Const { body } => self.infer_expr(*body, expected),
195 Expr::TryBlock { body } => {
196 let _inner = self.infer_expr(*body, expected);
197 // FIXME should be std::result::Result<{inner}, _>
200 Expr::Async { body } => {
201 // Use the first type parameter as the output type of future.
202 // existential type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
203 let inner_ty = self.infer_expr(*body, &Expectation::none());
204 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
205 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
206 TyKind::OpaqueType(opaque_ty_id, Substitution::from1(Interner, inner_ty))
209 Expr::Loop { body, label } => {
210 self.breakables.push(BreakableContext {
212 coerce: CoerceMany::new(self.table.new_type_var()),
213 label: label.map(|label| self.body[label].name.clone()),
215 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
217 let ctxt = self.breakables.pop().expect("breakable stack broken");
220 self.diverges = Diverges::Maybe;
221 ctxt.coerce.complete()
223 TyKind::Never.intern(Interner)
226 Expr::While { condition, body, label } => {
227 self.breakables.push(BreakableContext {
229 coerce: CoerceMany::new(self.err_ty()),
230 label: label.map(|label| self.body[label].name.clone()),
232 // while let is desugared to a match loop, so this is always simple while
235 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
237 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
238 let _ctxt = self.breakables.pop().expect("breakable stack broken");
239 // the body may not run, so it diverging doesn't mean we diverge
240 self.diverges = Diverges::Maybe;
243 Expr::For { iterable, body, pat, label } => {
244 let iterable_ty = self.infer_expr(*iterable, &Expectation::none());
246 self.breakables.push(BreakableContext {
248 coerce: CoerceMany::new(self.err_ty()),
249 label: label.map(|label| self.body[label].name.clone()),
252 self.resolve_associated_type(iterable_ty, self.resolve_into_iter_item());
254 self.infer_pat(*pat, &pat_ty, BindingMode::default());
256 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
257 let _ctxt = self.breakables.pop().expect("breakable stack broken");
258 // the body may not run, so it diverging doesn't mean we diverge
259 self.diverges = Diverges::Maybe;
262 Expr::Lambda { body, args, ret_type, arg_types } => {
263 assert_eq!(args.len(), arg_types.len());
265 let mut sig_tys = Vec::new();
267 // collect explicitly written argument types
268 for arg_type in arg_types.iter() {
269 let arg_ty = match arg_type {
270 Some(type_ref) => self.make_ty(type_ref),
271 None => self.table.new_type_var(),
273 sig_tys.push(arg_ty);
277 let ret_ty = match ret_type {
278 Some(type_ref) => self.make_ty(type_ref),
279 None => self.table.new_type_var(),
281 sig_tys.push(ret_ty.clone());
282 let sig_ty = TyKind::Function(FnPointer {
284 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
285 substitution: FnSubst(
286 Substitution::from_iter(Interner, sig_tys.clone()).shifted_in(Interner),
290 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
292 TyKind::Closure(closure_id, Substitution::from1(Interner, sig_ty.clone()))
295 // Eagerly try to relate the closure type with the expected
296 // type, otherwise we often won't have enough information to
298 self.deduce_closure_type_from_expectations(
305 // Now go through the argument patterns
306 for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
307 self.infer_pat(*arg_pat, &arg_ty, BindingMode::default());
310 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
311 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
313 self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
315 self.diverges = prev_diverges;
316 self.return_ty = prev_ret_ty;
320 Expr::Call { callee, args } => {
321 let callee_ty = self.infer_expr(*callee, &Expectation::none());
322 let canonicalized = self.canonicalize(callee_ty.clone());
323 let mut derefs = Autoderef::new(
325 self.resolver.krate(),
327 goal: canonicalized.value.clone(),
328 environment: self.table.trait_env.env.clone(),
331 let res = derefs.by_ref().find_map(|(callee_deref_ty, _)| {
332 let ty = &canonicalized.decanonicalize_ty(&mut self.table, callee_deref_ty);
333 self.callable_sig(ty, args.len())
335 let (param_tys, ret_ty): (Vec<Ty>, Ty) = match res {
337 self.write_expr_adj(*callee, self.auto_deref_adjust_steps(&derefs));
340 None => (Vec::new(), self.err_ty()),
342 self.register_obligations_for_call(&callee_ty);
344 let expected_inputs = self.expected_inputs_for_expected_output(
350 self.check_call_arguments(args, &expected_inputs, ¶m_tys);
351 self.normalize_associated_types_in(ret_ty)
353 Expr::MethodCall { receiver, args, method_name, generic_args } => self
359 generic_args.as_deref(),
362 Expr::Match { expr, arms } => {
363 let input_ty = self.infer_expr(*expr, &Expectation::none());
365 let expected = expected.adjust_for_branches(&mut self.table);
367 let result_ty = if arms.is_empty() {
368 TyKind::Never.intern(Interner)
371 Expectation::HasType(ty) => ty.clone(),
372 _ => self.table.new_type_var(),
375 let mut coerce = CoerceMany::new(result_ty);
377 let matchee_diverges = self.diverges;
378 let mut all_arms_diverge = Diverges::Always;
380 for arm in arms.iter() {
381 self.diverges = Diverges::Maybe;
382 let _pat_ty = self.infer_pat(arm.pat, &input_ty, BindingMode::default());
383 if let Some(guard_expr) = arm.guard {
386 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
390 let arm_ty = self.infer_expr_inner(arm.expr, &expected);
391 all_arms_diverge &= self.diverges;
392 coerce.coerce(self, Some(arm.expr), &arm_ty);
395 self.diverges = matchee_diverges | all_arms_diverge;
400 // FIXME this could be more efficient...
401 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
402 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or_else(|| self.err_ty())
404 Expr::Continue { .. } => TyKind::Never.intern(Interner),
405 Expr::Break { expr, label } => {
406 let mut coerce = match find_breakable(&mut self.breakables, label.as_ref()) {
408 // avoiding the borrowck
411 CoerceMany::new(self.result.standard_types.unknown.clone()),
414 None => CoerceMany::new(self.result.standard_types.unknown.clone()),
417 let val_ty = if let Some(expr) = *expr {
418 self.infer_expr(expr, &Expectation::none())
423 // FIXME: create a synthetic `()` during lowering so we have something to refer to here?
424 coerce.coerce(self, *expr, &val_ty);
426 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
427 ctxt.coerce = coerce;
428 ctxt.may_break = true;
430 self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop {
435 TyKind::Never.intern(Interner)
437 Expr::Return { expr } => {
438 if let Some(expr) = expr {
439 self.infer_expr_coerce(*expr, &Expectation::has_type(self.return_ty.clone()));
441 let unit = TyBuilder::unit();
442 let _ = self.coerce(Some(tgt_expr), &unit, &self.return_ty.clone());
444 TyKind::Never.intern(Interner)
446 Expr::Yield { expr } => {
447 // FIXME: track yield type for coercion
448 if let Some(expr) = expr {
449 self.infer_expr(*expr, &Expectation::none());
451 TyKind::Never.intern(Interner)
453 Expr::RecordLit { path, fields, spread } => {
454 let (ty, def_id) = self.resolve_variant(path.as_deref(), false);
455 if let Some(variant) = def_id {
456 self.write_variant_resolution(tgt_expr.into(), variant);
459 if let Some(t) = expected.only_has_type(&mut self.table) {
465 .map(|(_, s)| s.clone())
466 .unwrap_or_else(|| Substitution::empty(Interner));
467 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
468 let variant_data = def_id.map(|it| it.variant_data(self.db.upcast()));
469 for field in fields.iter() {
471 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
472 Some(local_id) => Some(FieldId { parent: def_id.unwrap(), local_id }),
474 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
480 let field_ty = field_def.map_or(self.err_ty(), |it| {
481 field_types[it.local_id].clone().substitute(Interner, &substs)
483 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
485 if let Some(expr) = spread {
486 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
490 Expr::Field { expr, name } => {
491 let receiver_ty = self.infer_expr_inner(*expr, &Expectation::none());
492 let canonicalized = self.canonicalize(receiver_ty);
494 let mut autoderef = Autoderef::new(
496 self.resolver.krate(),
498 goal: canonicalized.value.clone(),
499 environment: self.trait_env.env.clone(),
502 let ty = autoderef.by_ref().find_map(|(derefed_ty, _)| {
503 let module = self.resolver.module();
505 let is_visible = |field_id: &FieldId| {
508 db.field_visibilities(field_id.parent)[field_id.local_id]
509 .is_visible_from(db.upcast(), mod_id)
514 .decanonicalize_ty(&mut self.table, derefed_ty)
517 TyKind::Tuple(_, substs) => name.as_tuple_index().and_then(|idx| {
521 .map(|a| a.assert_ty_ref(Interner))
524 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
525 let local_id = self.db.struct_data(*s).variant_data.field(name)?;
526 let field = FieldId { parent: (*s).into(), local_id };
527 if is_visible(&field) {
528 self.write_field_resolution(tgt_expr, field);
530 self.db.field_types((*s).into())[field.local_id]
532 .substitute(Interner, ¶meters),
535 // Write down the first field resolution even if it is not visible
536 // This aids IDE features for private fields like goto def and in
537 // case of autoderef finding an applicable field, this will be
538 // overwritten in a following cycle
539 self.write_field_resolution_if_empty(tgt_expr, field);
543 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
544 let local_id = self.db.union_data(*u).variant_data.field(name)?;
545 let field = FieldId { parent: (*u).into(), local_id };
546 if is_visible(&field) {
547 self.write_field_resolution(tgt_expr, field);
549 self.db.field_types((*u).into())[field.local_id]
551 .substitute(Interner, ¶meters),
554 // Write down the first field resolution even if it is not visible
555 // This aids IDE features for private fields like goto def and in
556 // case of autoderef finding an applicable field, this will be
557 // overwritten in a following cycle
558 self.write_field_resolution_if_empty(tgt_expr, field);
567 self.write_expr_adj(*expr, self.auto_deref_adjust_steps(&autoderef));
570 None => self.err_ty(),
572 let ty = self.insert_type_vars(ty);
573 self.normalize_associated_types_in(ty)
575 Expr::Await { expr } => {
576 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
577 self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
579 Expr::Try { expr } => {
580 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
581 self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
583 Expr::Cast { expr, type_ref } => {
584 // FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
585 let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
586 let cast_ty = self.make_ty(type_ref);
587 // FIXME check the cast...
590 Expr::Ref { expr, rawness, mutability } => {
591 let mutability = lower_to_chalk_mutability(*mutability);
592 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = expected
593 .only_has_type(&mut self.table)
595 .and_then(|t| t.as_reference_or_ptr())
597 if exp_mutability == Mutability::Mut && mutability == Mutability::Not {
598 // FIXME: record type error - expected mut reference but found shared ref,
599 // which cannot be coerced
601 if exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
602 // FIXME: record type error - expected reference but found ptr,
603 // which cannot be coerced
605 Expectation::rvalue_hint(&mut self.table, Ty::clone(exp_inner))
609 let inner_ty = self.infer_expr_inner(*expr, &expectation);
611 Rawness::RawPtr => TyKind::Raw(mutability, inner_ty),
612 Rawness::Ref => TyKind::Ref(mutability, static_lifetime(), inner_ty),
616 Expr::Box { expr } => {
617 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
618 if let Some(box_) = self.resolve_boxed_box() {
619 TyBuilder::adt(self.db, box_)
621 .fill_with_defaults(self.db, || self.table.new_type_var())
627 Expr::UnaryOp { expr, op } => {
628 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
629 let inner_ty = self.resolve_ty_shallow(&inner_ty);
631 UnaryOp::Deref => match self.resolver.krate() {
633 let canonicalized = self.canonicalize(inner_ty);
634 match autoderef::deref(
638 goal: &canonicalized.value,
639 environment: self.trait_env.env.clone(),
642 Some(derefed_ty) => {
643 canonicalized.decanonicalize_ty(&mut self.table, derefed_ty)
645 None => self.err_ty(),
648 None => self.err_ty(),
651 match inner_ty.kind(Interner) {
652 // Fast path for builtins
653 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_))
654 | TyKind::InferenceVar(
656 TyVariableKind::Integer | TyVariableKind::Float,
658 // Otherwise we resolve via the std::ops::Neg trait
660 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
664 match inner_ty.kind(Interner) {
665 // Fast path for builtins
666 TyKind::Scalar(Scalar::Bool | Scalar::Int(_) | Scalar::Uint(_))
667 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
668 // Otherwise we resolve via the std::ops::Not trait
670 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
675 Expr::BinaryOp { lhs, rhs, op } => match op {
676 Some(BinaryOp::Assignment { op: None }) => {
677 let lhs_ty = self.infer_expr(*lhs, &Expectation::none());
678 self.infer_expr_coerce(*rhs, &Expectation::has_type(lhs_ty));
679 self.result.standard_types.unit.clone()
681 Some(BinaryOp::LogicOp(_)) => {
682 let bool_ty = self.result.standard_types.bool_.clone();
683 self.infer_expr_coerce(*lhs, &Expectation::HasType(bool_ty.clone()));
684 let lhs_diverges = self.diverges;
685 self.infer_expr_coerce(*rhs, &Expectation::HasType(bool_ty.clone()));
686 // Depending on the LHS' value, the RHS can never execute.
687 self.diverges = lhs_diverges;
690 Some(op) => self.infer_overloadable_binop(*lhs, *op, *rhs, tgt_expr),
693 Expr::Range { lhs, rhs, range_type } => {
694 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
695 let rhs_expect = lhs_ty
697 .map_or_else(Expectation::none, |ty| Expectation::has_type(ty.clone()));
698 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
699 match (range_type, lhs_ty, rhs_ty) {
700 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
701 Some(adt) => TyBuilder::adt(self.db, adt).build(),
702 None => self.err_ty(),
704 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
705 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
706 None => self.err_ty(),
708 (RangeOp::Inclusive, None, Some(ty)) => {
709 match self.resolve_range_to_inclusive() {
710 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
711 None => self.err_ty(),
714 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
715 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
716 None => self.err_ty(),
718 (RangeOp::Inclusive, Some(_), Some(ty)) => {
719 match self.resolve_range_inclusive() {
720 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
721 None => self.err_ty(),
724 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
725 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
726 None => self.err_ty(),
728 (RangeOp::Inclusive, _, None) => self.err_ty(),
731 Expr::Index { base, index } => {
732 let base_ty = self.infer_expr_inner(*base, &Expectation::none());
733 let index_ty = self.infer_expr(*index, &Expectation::none());
735 if let (Some(index_trait), Some(krate)) =
736 (self.resolve_ops_index(), self.resolver.krate())
738 let canonicalized = self.canonicalize(base_ty);
739 let self_ty = method_resolution::resolve_indexing_op(
741 &canonicalized.value,
742 self.trait_env.clone(),
746 let self_ty = self_ty.map_or(self.err_ty(), |t| {
747 canonicalized.decanonicalize_ty(&mut self.table, t)
749 self.resolve_associated_type_with_params(
751 self.resolve_ops_index_output(),
758 Expr::Tuple { exprs } => {
759 let mut tys = match expected
760 .only_has_type(&mut self.table)
762 .map(|t| t.kind(Interner))
764 Some(TyKind::Tuple(_, substs)) => substs
766 .map(|a| a.assert_ty_ref(Interner).clone())
767 .chain(repeat_with(|| self.table.new_type_var()))
769 .collect::<Vec<_>>(),
770 _ => (0..exprs.len()).map(|_| self.table.new_type_var()).collect(),
773 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
774 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
777 TyKind::Tuple(tys.len(), Substitution::from_iter(Interner, tys)).intern(Interner)
779 Expr::Array(array) => {
781 match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(Interner)) {
782 Some(TyKind::Array(st, _) | TyKind::Slice(st)) => st.clone(),
783 _ => self.table.new_type_var(),
785 let mut coerce = CoerceMany::new(elem_ty.clone());
787 let expected = Expectation::has_type(elem_ty.clone());
788 let len = match array {
789 Array::ElementList(items) => {
790 for &expr in items.iter() {
791 let cur_elem_ty = self.infer_expr_inner(expr, &expected);
792 coerce.coerce(self, Some(expr), &cur_elem_ty);
794 Some(items.len() as u64)
796 &Array::Repeat { initializer, repeat } => {
797 self.infer_expr_coerce(initializer, &Expectation::has_type(elem_ty));
800 &Expectation::has_type(
801 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(Interner),
805 consteval::eval_usize(
807 consteval::ConstEvalCtx {
810 local_data: Default::default(),
811 infer: &mut |x| self.infer_expr(x, &expected),
817 TyKind::Array(coerce.complete(), consteval::usize_const(len)).intern(Interner)
819 Expr::Literal(lit) => match lit {
820 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
821 Literal::String(..) => {
822 TyKind::Ref(Mutability::Not, static_lifetime(), TyKind::Str.intern(Interner))
825 Literal::ByteString(bs) => {
826 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner);
828 let len = consteval::usize_const(Some(bs.len() as u64));
830 let array_type = TyKind::Array(byte_type, len).intern(Interner);
831 TyKind::Ref(Mutability::Not, static_lifetime(), array_type).intern(Interner)
833 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(Interner),
834 Literal::Int(_v, ty) => match ty {
836 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
839 None => self.table.new_integer_var(),
841 Literal::Uint(_v, ty) => match ty {
843 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
846 None => self.table.new_integer_var(),
848 Literal::Float(_v, ty) => match ty {
850 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
853 None => self.table.new_float_var(),
856 Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
858 // use a new type variable if we got unknown here
859 let ty = self.insert_type_vars_shallow(ty);
860 self.write_expr_ty(tgt_expr, ty.clone());
864 fn infer_overloadable_binop(
871 let lhs_expectation = Expectation::none();
872 let lhs_ty = self.infer_expr(lhs, &lhs_expectation);
873 let rhs_ty = self.table.new_type_var();
875 let func = self.resolve_binop_method(op);
876 let func = match func {
879 let rhs_ty = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone());
880 let rhs_ty = self.infer_expr_coerce(rhs, &Expectation::from_option(rhs_ty));
882 .builtin_binary_op_return_ty(op, lhs_ty, rhs_ty)
883 .unwrap_or_else(|| self.err_ty());
887 let subst = TyBuilder::subst_for_def(self.db, func)
888 .push(lhs_ty.clone())
889 .push(rhs_ty.clone())
891 self.write_method_resolution(tgt_expr, func, subst.clone());
893 let method_ty = self.db.value_ty(func.into()).substitute(Interner, &subst);
894 self.register_obligations_for_call(&method_ty);
896 self.infer_expr_coerce(rhs, &Expectation::has_type(rhs_ty.clone()));
898 let ret_ty = match method_ty.callable_sig(self.db) {
899 Some(sig) => sig.ret().clone(),
900 None => self.err_ty(),
903 let ret_ty = self.normalize_associated_types_in(ret_ty);
905 // FIXME: record autoref adjustments
907 // use knowledge of built-in binary ops, which can sometimes help inference
908 if let Some(builtin_rhs) = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone()) {
909 self.unify(&builtin_rhs, &rhs_ty);
911 if let Some(builtin_ret) = self.builtin_binary_op_return_ty(op, lhs_ty, rhs_ty) {
912 self.unify(&builtin_ret, &ret_ty);
921 statements: &[Statement],
922 tail: Option<ExprId>,
923 expected: &Expectation,
925 for stmt in statements {
927 Statement::Let { pat, type_ref, initializer, else_branch } => {
928 let decl_ty = type_ref
930 .map(|tr| self.make_ty(tr))
931 .unwrap_or_else(|| self.err_ty());
933 // Always use the declared type when specified
934 let mut ty = decl_ty.clone();
936 if let Some(expr) = initializer {
938 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
939 if decl_ty.is_unknown() {
944 if let Some(expr) = else_branch {
945 self.infer_expr_coerce(
947 &Expectation::has_type(Ty::new(Interner, TyKind::Never)),
951 self.infer_pat(*pat, &ty, BindingMode::default());
953 Statement::Expr { expr, .. } => {
954 self.infer_expr(*expr, &Expectation::none());
959 if let Some(expr) = tail {
960 self.infer_expr_coerce(expr, expected)
962 // Citing rustc: if there is no explicit tail expression,
963 // that is typically equivalent to a tail expression
964 // of `()` -- except if the block diverges. In that
965 // case, there is no value supplied from the tail
966 // expression (assuming there are no other breaks,
967 // this implies that the type of the block will be
969 if self.diverges.is_always() {
970 // we don't even make an attempt at coercion
971 self.table.new_maybe_never_var()
973 if let Some(t) = expected.only_has_type(&mut self.table) {
974 let _ = self.coerce(Some(expr), &TyBuilder::unit(), &t);
981 fn infer_method_call(
987 generic_args: Option<&GenericArgs>,
988 expected: &Expectation,
990 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
991 let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
993 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
995 let resolved = self.resolver.krate().and_then(|krate| {
996 method_resolution::lookup_method(
997 &canonicalized_receiver.value,
999 self.trait_env.clone(),
1002 self.resolver.module().into(),
1006 let (receiver_ty, method_ty, substs) = match resolved {
1007 Some((ty, func)) => {
1008 let ty = canonicalized_receiver.decanonicalize_ty(&mut self.table, ty);
1009 let generics = generics(self.db.upcast(), func.into());
1010 let substs = self.substs_for_method_call(generics, generic_args, &ty);
1011 self.write_method_resolution(tgt_expr, func, substs.clone());
1012 (ty, self.db.value_ty(func.into()), substs)
1016 Binders::empty(Interner, self.err_ty()),
1017 Substitution::empty(Interner),
1020 let method_ty = method_ty.substitute(Interner, &substs);
1021 self.register_obligations_for_call(&method_ty);
1022 let (formal_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
1024 if !sig.params().is_empty() {
1025 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
1027 (self.err_ty(), Vec::new(), sig.ret().clone())
1030 None => (self.err_ty(), Vec::new(), self.err_ty()),
1032 self.unify(&formal_receiver_ty, &receiver_ty);
1034 let expected_inputs =
1035 self.expected_inputs_for_expected_output(expected, ret_ty.clone(), param_tys.clone());
1037 self.check_call_arguments(args, &expected_inputs, ¶m_tys);
1038 self.normalize_associated_types_in(ret_ty)
1041 fn expected_inputs_for_expected_output(
1043 expected_output: &Expectation,
1047 if let Some(expected_ty) = expected_output.to_option(&mut self.table) {
1048 self.table.fudge_inference(|table| {
1049 if table.try_unify(&expected_ty, &output).is_ok() {
1050 table.resolve_with_fallback(inputs, &|var, kind, _, _| match kind {
1051 chalk_ir::VariableKind::Ty(tk) => var.to_ty(Interner, tk).cast(Interner),
1052 chalk_ir::VariableKind::Lifetime => {
1053 var.to_lifetime(Interner).cast(Interner)
1055 chalk_ir::VariableKind::Const(ty) => {
1056 var.to_const(Interner, ty).cast(Interner)
1068 fn check_call_arguments(&mut self, args: &[ExprId], expected_inputs: &[Ty], param_tys: &[Ty]) {
1069 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
1070 // We do this in a pretty awful way: first we type-check any arguments
1071 // that are not closures, then we type-check the closures. This is so
1072 // that we have more information about the types of arguments when we
1073 // type-check the functions. This isn't really the right way to do this.
1074 for &check_closures in &[false, true] {
1075 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
1076 let expected_iter = expected_inputs
1079 .chain(param_iter.clone().skip(expected_inputs.len()));
1080 for ((&arg, param_ty), expected_ty) in args.iter().zip(param_iter).zip(expected_iter) {
1081 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
1082 if is_closure != check_closures {
1086 // the difference between param_ty and expected here is that
1087 // expected is the parameter when the expected *return* type is
1088 // taken into account. So in `let _: &[i32] = identity(&[1, 2])`
1089 // the expected type is already `&[i32]`, whereas param_ty is
1090 // still an unbound type variable. We don't always want to force
1091 // the parameter to coerce to the expected type (for example in
1092 // `coerce_unsize_expected_type_4`).
1093 let param_ty = self.normalize_associated_types_in(param_ty);
1094 let expected = Expectation::rvalue_hint(&mut self.table, expected_ty);
1095 // infer with the expected type we have...
1096 let ty = self.infer_expr_inner(arg, &expected);
1098 // then coerce to either the expected type or just the formal parameter type
1099 let coercion_target = if let Some(ty) = expected.only_has_type(&mut self.table) {
1100 // if we are coercing to the expectation, unify with the
1101 // formal parameter type to connect everything
1102 self.unify(&ty, ¶m_ty);
1107 if !coercion_target.is_unknown() {
1108 if self.coerce(Some(arg), &ty, &coercion_target).is_err() {
1109 self.result.type_mismatches.insert(
1111 TypeMismatch { expected: coercion_target, actual: ty.clone() },
1119 fn substs_for_method_call(
1121 def_generics: Generics,
1122 generic_args: Option<&GenericArgs>,
1125 let (parent_params, self_params, type_params, impl_trait_params) =
1126 def_generics.provenance_split();
1127 assert_eq!(self_params, 0); // method shouldn't have another Self param
1128 let total_len = parent_params + type_params + impl_trait_params;
1129 let mut substs = Vec::with_capacity(total_len);
1130 // Parent arguments are unknown, except for the receiver type
1131 for (_id, param) in def_generics.iter_parent() {
1132 if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
1133 substs.push(receiver_ty.clone());
1135 substs.push(self.table.new_type_var());
1138 // handle provided type arguments
1139 if let Some(generic_args) = generic_args {
1140 // if args are provided, it should be all of them, but we can't rely on that
1141 for arg in generic_args
1144 .filter(|arg| matches!(arg, GenericArg::Type(_)))
1148 GenericArg::Type(type_ref) => {
1149 let ty = self.make_ty(type_ref);
1152 GenericArg::Lifetime(_) => {}
1156 let supplied_params = substs.len();
1157 for _ in supplied_params..total_len {
1158 substs.push(self.table.new_type_var());
1160 assert_eq!(substs.len(), total_len);
1161 Substitution::from_iter(Interner, substs)
1164 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
1165 let callable_ty = self.resolve_ty_shallow(callable_ty);
1166 if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(Interner) {
1167 let def: CallableDefId = from_chalk(self.db, *fn_def);
1168 let generic_predicates = self.db.generic_predicates(def.into());
1169 for predicate in generic_predicates.iter() {
1170 let (predicate, binders) = predicate
1172 .substitute(Interner, parameters)
1173 .into_value_and_skipped_binders();
1174 always!(binders.len(Interner) == 0); // quantified where clauses not yet handled
1175 self.push_obligation(predicate.cast(Interner));
1177 // add obligation for trait implementation, if this is a trait method
1179 CallableDefId::FunctionId(f) => {
1180 if let ItemContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container {
1181 // construct a TraitRef
1182 let substs = crate::subst_prefix(
1184 generics(self.db.upcast(), trait_.into()).len(),
1186 self.push_obligation(
1187 TraitRef { trait_id: to_chalk_trait_id(trait_), substitution: substs }
1192 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}
1197 fn builtin_binary_op_return_ty(&mut self, op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Option<Ty> {
1198 let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
1199 let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
1201 BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => {
1202 Some(TyKind::Scalar(Scalar::Bool).intern(Interner))
1204 BinaryOp::Assignment { .. } => Some(TyBuilder::unit()),
1205 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => {
1206 // all integer combinations are valid here
1208 lhs_ty.kind(Interner),
1209 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1210 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1212 rhs_ty.kind(Interner),
1213 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1214 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1221 BinaryOp::ArithOp(_) => match (lhs_ty.kind(Interner), rhs_ty.kind(Interner)) {
1222 // (int, int) | (uint, uint) | (float, float)
1223 (TyKind::Scalar(Scalar::Int(_)), TyKind::Scalar(Scalar::Int(_)))
1224 | (TyKind::Scalar(Scalar::Uint(_)), TyKind::Scalar(Scalar::Uint(_)))
1225 | (TyKind::Scalar(Scalar::Float(_)), TyKind::Scalar(Scalar::Float(_))) => {
1228 // ({int}, int) | ({int}, uint)
1230 TyKind::InferenceVar(_, TyVariableKind::Integer),
1231 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1233 // (int, {int}) | (uint, {int})
1235 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1236 TyKind::InferenceVar(_, TyVariableKind::Integer),
1238 // ({float} | float)
1240 TyKind::InferenceVar(_, TyVariableKind::Float),
1241 TyKind::Scalar(Scalar::Float(_)),
1245 TyKind::Scalar(Scalar::Float(_)),
1246 TyKind::InferenceVar(_, TyVariableKind::Float),
1248 // ({int}, {int}) | ({float}, {float})
1250 TyKind::InferenceVar(_, TyVariableKind::Integer),
1251 TyKind::InferenceVar(_, TyVariableKind::Integer),
1254 TyKind::InferenceVar(_, TyVariableKind::Float),
1255 TyKind::InferenceVar(_, TyVariableKind::Float),
1262 fn builtin_binary_op_rhs_expectation(&mut self, op: BinaryOp, lhs_ty: Ty) -> Option<Ty> {
1264 BinaryOp::LogicOp(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
1265 BinaryOp::Assignment { op: None } => lhs_ty,
1266 BinaryOp::CmpOp(CmpOp::Eq { .. }) => match self
1267 .resolve_ty_shallow(&lhs_ty)
1270 TyKind::Scalar(_) | TyKind::Str => lhs_ty,
1271 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1274 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => return None,
1275 BinaryOp::CmpOp(CmpOp::Ord { .. })
1276 | BinaryOp::Assignment { op: Some(_) }
1277 | BinaryOp::ArithOp(_) => match self.resolve_ty_shallow(&lhs_ty).kind(Interner) {
1278 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_)) => lhs_ty,
1279 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1285 fn resolve_binop_method(&self, op: BinaryOp) -> Option<FunctionId> {
1286 let (name, lang_item) = match op {
1287 BinaryOp::LogicOp(_) => return None,
1288 BinaryOp::ArithOp(aop) => match aop {
1289 ArithOp::Add => (name!(add), name!(add)),
1290 ArithOp::Mul => (name!(mul), name!(mul)),
1291 ArithOp::Sub => (name!(sub), name!(sub)),
1292 ArithOp::Div => (name!(div), name!(div)),
1293 ArithOp::Rem => (name!(rem), name!(rem)),
1294 ArithOp::Shl => (name!(shl), name!(shl)),
1295 ArithOp::Shr => (name!(shr), name!(shr)),
1296 ArithOp::BitXor => (name!(bitxor), name!(bitxor)),
1297 ArithOp::BitOr => (name!(bitor), name!(bitor)),
1298 ArithOp::BitAnd => (name!(bitand), name!(bitand)),
1300 BinaryOp::Assignment { op: Some(aop) } => match aop {
1301 ArithOp::Add => (name!(add_assign), name!(add_assign)),
1302 ArithOp::Mul => (name!(mul_assign), name!(mul_assign)),
1303 ArithOp::Sub => (name!(sub_assign), name!(sub_assign)),
1304 ArithOp::Div => (name!(div_assign), name!(div_assign)),
1305 ArithOp::Rem => (name!(rem_assign), name!(rem_assign)),
1306 ArithOp::Shl => (name!(shl_assign), name!(shl_assign)),
1307 ArithOp::Shr => (name!(shr_assign), name!(shr_assign)),
1308 ArithOp::BitXor => (name!(bitxor_assign), name!(bitxor_assign)),
1309 ArithOp::BitOr => (name!(bitor_assign), name!(bitor_assign)),
1310 ArithOp::BitAnd => (name!(bitand_assign), name!(bitand_assign)),
1312 BinaryOp::CmpOp(cop) => match cop {
1313 CmpOp::Eq { negated: false } => (name!(eq), name!(eq)),
1314 CmpOp::Eq { negated: true } => (name!(ne), name!(eq)),
1315 CmpOp::Ord { ordering: Ordering::Less, strict: false } => {
1316 (name!(le), name!(partial_ord))
1318 CmpOp::Ord { ordering: Ordering::Less, strict: true } => {
1319 (name!(lt), name!(partial_ord))
1321 CmpOp::Ord { ordering: Ordering::Greater, strict: false } => {
1322 (name!(ge), name!(partial_ord))
1324 CmpOp::Ord { ordering: Ordering::Greater, strict: true } => {
1325 (name!(gt), name!(partial_ord))
1328 BinaryOp::Assignment { op: None } => return None,
1331 let trait_ = self.resolve_lang_item(lang_item)?.as_trait()?;
1333 self.db.trait_data(trait_).method_by_name(&name)