1 //! Type inference for expressions.
4 collections::hash_map::Entry,
5 iter::{repeat, repeat_with},
10 use chalk_ir::{cast::Cast, fold::Shift, Mutability, TyVariableKind};
12 expr::{ArithOp, Array, BinaryOp, CmpOp, Expr, ExprId, Literal, Ordering, Statement, UnaryOp},
13 path::{GenericArg, GenericArgs},
14 resolver::resolver_for_expr,
15 FieldId, FunctionId, ItemContainerId, Lookup,
17 use hir_expand::name::{name, Name};
19 use syntax::ast::RangeOp;
22 autoderef::{self, Autoderef},
24 infer::coerce::CoerceMany,
25 lower::lower_to_chalk_mutability,
28 primitive::{self, UintTy},
29 static_lifetime, to_chalk_trait_id,
30 utils::{generics, Generics},
31 AdtId, Binders, CallableDefId, FnPointer, FnSig, FnSubst, Interner, Rawness, Scalar,
32 Substitution, TraitRef, Ty, TyBuilder, TyExt, TyKind,
36 coerce::auto_deref_adjust_steps, find_breakable, BindingMode, BreakableContext, Diverges,
37 Expectation, InferenceContext, 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 infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
81 self.db.unwind_if_cancelled();
83 let body = Arc::clone(&self.body); // avoid borrow checker problem
84 let ty = match &body[tgt_expr] {
85 Expr::Missing => self.err_ty(),
86 &Expr::If { condition, then_branch, else_branch } => {
87 // if let is desugared to match, so this is always simple if
90 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
93 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
94 let mut both_arms_diverge = Diverges::Always;
96 let result_ty = self.table.new_type_var();
97 let then_ty = self.infer_expr_inner(then_branch, expected);
98 both_arms_diverge &= mem::replace(&mut self.diverges, Diverges::Maybe);
99 let mut coerce = CoerceMany::new(result_ty);
100 coerce.coerce(self, Some(then_branch), &then_ty);
101 let else_ty = match else_branch {
102 Some(else_branch) => self.infer_expr_inner(else_branch, expected),
103 None => TyBuilder::unit(),
105 both_arms_diverge &= self.diverges;
106 // FIXME: create a synthetic `else {}` so we have something to refer to here instead of None?
107 coerce.coerce(self, else_branch, &else_ty);
109 self.diverges = condition_diverges | both_arms_diverge;
113 &Expr::Let { pat, expr } => {
114 let input_ty = self.infer_expr(expr, &Expectation::none());
115 self.infer_pat(pat, &input_ty, BindingMode::default());
116 TyKind::Scalar(Scalar::Bool).intern(Interner)
118 Expr::Block { statements, tail, label, id: _ } => {
119 let old_resolver = mem::replace(
121 resolver_for_expr(self.db.upcast(), self.owner, tgt_expr),
123 let ty = match label {
125 let break_ty = self.table.new_type_var();
126 self.breakables.push(BreakableContext {
128 coerce: CoerceMany::new(break_ty.clone()),
129 label: label.map(|label| self.body[label].name.clone()),
131 let ty = self.infer_block(
135 &Expectation::has_type(break_ty),
137 let ctxt = self.breakables.pop().expect("breakable stack broken");
139 ctxt.coerce.complete()
144 None => self.infer_block(tgt_expr, statements, *tail, expected),
146 self.resolver = old_resolver;
149 Expr::Unsafe { body } | Expr::Const { body } => self.infer_expr(*body, expected),
150 Expr::TryBlock { body } => {
151 let _inner = self.infer_expr(*body, expected);
152 // FIXME should be std::result::Result<{inner}, _>
155 Expr::Async { body } => {
156 // Use the first type parameter as the output type of future.
157 // existential type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
158 let inner_ty = self.infer_expr(*body, &Expectation::none());
159 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
160 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
161 TyKind::OpaqueType(opaque_ty_id, Substitution::from1(Interner, inner_ty))
164 Expr::Loop { body, label } => {
165 self.breakables.push(BreakableContext {
167 coerce: CoerceMany::new(self.table.new_type_var()),
168 label: label.map(|label| self.body[label].name.clone()),
170 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
172 let ctxt = self.breakables.pop().expect("breakable stack broken");
175 self.diverges = Diverges::Maybe;
176 ctxt.coerce.complete()
178 TyKind::Never.intern(Interner)
181 Expr::While { condition, body, label } => {
182 self.breakables.push(BreakableContext {
184 coerce: CoerceMany::new(self.err_ty()),
185 label: label.map(|label| self.body[label].name.clone()),
187 // while let is desugared to a match loop, so this is always simple while
190 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
192 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
193 let _ctxt = self.breakables.pop().expect("breakable stack broken");
194 // the body may not run, so it diverging doesn't mean we diverge
195 self.diverges = Diverges::Maybe;
198 Expr::For { iterable, body, pat, label } => {
199 let iterable_ty = self.infer_expr(*iterable, &Expectation::none());
201 self.breakables.push(BreakableContext {
203 coerce: CoerceMany::new(self.err_ty()),
204 label: label.map(|label| self.body[label].name.clone()),
207 self.resolve_associated_type(iterable_ty, self.resolve_into_iter_item());
209 self.infer_pat(*pat, &pat_ty, BindingMode::default());
211 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
212 let _ctxt = self.breakables.pop().expect("breakable stack broken");
213 // the body may not run, so it diverging doesn't mean we diverge
214 self.diverges = Diverges::Maybe;
217 Expr::Lambda { body, args, ret_type, arg_types } => {
218 assert_eq!(args.len(), arg_types.len());
220 let mut sig_tys = Vec::new();
222 // collect explicitly written argument types
223 for arg_type in arg_types.iter() {
224 let arg_ty = match arg_type {
225 Some(type_ref) => self.make_ty(type_ref),
226 None => self.table.new_type_var(),
228 sig_tys.push(arg_ty);
232 let ret_ty = match ret_type {
233 Some(type_ref) => self.make_ty(type_ref),
234 None => self.table.new_type_var(),
236 sig_tys.push(ret_ty.clone());
237 let sig_ty = TyKind::Function(FnPointer {
239 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
240 substitution: FnSubst(
241 Substitution::from_iter(Interner, sig_tys.clone()).shifted_in(Interner),
245 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
247 TyKind::Closure(closure_id, Substitution::from1(Interner, sig_ty.clone()))
250 // Eagerly try to relate the closure type with the expected
251 // type, otherwise we often won't have enough information to
253 self.deduce_closure_type_from_expectations(
260 // Now go through the argument patterns
261 for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
262 self.infer_pat(*arg_pat, &arg_ty, BindingMode::default());
265 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
266 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
268 self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
270 self.diverges = prev_diverges;
271 self.return_ty = prev_ret_ty;
275 Expr::Call { callee, args } => {
276 let callee_ty = self.infer_expr(*callee, &Expectation::none());
277 let mut derefs = Autoderef::new(&mut self.table, callee_ty.clone());
279 // manual loop to be able to access `derefs.table`
280 while let Some((callee_deref_ty, _)) = derefs.next() {
281 res = derefs.table.callable_sig(&callee_deref_ty, args.len());
286 let (param_tys, ret_ty): (Vec<Ty>, Ty) = match res {
288 let adjustments = auto_deref_adjust_steps(&derefs);
289 self.write_expr_adj(*callee, adjustments);
292 None => (Vec::new(), self.err_ty()),
294 self.register_obligations_for_call(&callee_ty);
296 let expected_inputs = self.expected_inputs_for_expected_output(
302 self.check_call_arguments(args, &expected_inputs, ¶m_tys);
303 self.normalize_associated_types_in(ret_ty)
305 Expr::MethodCall { receiver, args, method_name, generic_args } => self
311 generic_args.as_deref(),
314 Expr::Match { expr, arms } => {
315 let input_ty = self.infer_expr(*expr, &Expectation::none());
317 let expected = expected.adjust_for_branches(&mut self.table);
319 let result_ty = if arms.is_empty() {
320 TyKind::Never.intern(Interner)
323 Expectation::HasType(ty) => ty.clone(),
324 _ => self.table.new_type_var(),
327 let mut coerce = CoerceMany::new(result_ty);
329 let matchee_diverges = self.diverges;
330 let mut all_arms_diverge = Diverges::Always;
332 for arm in arms.iter() {
333 self.diverges = Diverges::Maybe;
334 let _pat_ty = self.infer_pat(arm.pat, &input_ty, BindingMode::default());
335 if let Some(guard_expr) = arm.guard {
338 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
342 let arm_ty = self.infer_expr_inner(arm.expr, &expected);
343 all_arms_diverge &= self.diverges;
344 coerce.coerce(self, Some(arm.expr), &arm_ty);
347 self.diverges = matchee_diverges | all_arms_diverge;
352 // FIXME this could be more efficient...
353 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
354 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or_else(|| self.err_ty())
356 Expr::Continue { .. } => TyKind::Never.intern(Interner),
357 Expr::Break { expr, label } => {
358 let mut coerce = match find_breakable(&mut self.breakables, label.as_ref()) {
360 // avoiding the borrowck
363 CoerceMany::new(self.result.standard_types.unknown.clone()),
366 None => CoerceMany::new(self.result.standard_types.unknown.clone()),
369 let val_ty = if let Some(expr) = *expr {
370 self.infer_expr(expr, &Expectation::none())
375 // FIXME: create a synthetic `()` during lowering so we have something to refer to here?
376 coerce.coerce(self, *expr, &val_ty);
378 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
379 ctxt.coerce = coerce;
380 ctxt.may_break = true;
382 self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop {
387 TyKind::Never.intern(Interner)
389 Expr::Return { expr } => {
390 if let Some(expr) = expr {
391 self.infer_expr_coerce(*expr, &Expectation::has_type(self.return_ty.clone()));
393 let unit = TyBuilder::unit();
394 let _ = self.coerce(Some(tgt_expr), &unit, &self.return_ty.clone());
396 TyKind::Never.intern(Interner)
398 Expr::Yield { expr } => {
399 // FIXME: track yield type for coercion
400 if let Some(expr) = expr {
401 self.infer_expr(*expr, &Expectation::none());
403 TyKind::Never.intern(Interner)
405 Expr::RecordLit { path, fields, spread } => {
406 let (ty, def_id) = self.resolve_variant(path.as_deref(), false);
407 if let Some(variant) = def_id {
408 self.write_variant_resolution(tgt_expr.into(), variant);
411 if let Some(t) = expected.only_has_type(&mut self.table) {
417 .map(|(_, s)| s.clone())
418 .unwrap_or_else(|| Substitution::empty(Interner));
419 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
420 let variant_data = def_id.map(|it| it.variant_data(self.db.upcast()));
421 for field in fields.iter() {
423 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
424 Some(local_id) => Some(FieldId { parent: def_id.unwrap(), local_id }),
426 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
432 let field_ty = field_def.map_or(self.err_ty(), |it| {
433 field_types[it.local_id].clone().substitute(Interner, &substs)
435 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
437 if let Some(expr) = spread {
438 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
442 Expr::Field { expr, name } => {
443 let receiver_ty = self.infer_expr_inner(*expr, &Expectation::none());
445 let mut autoderef = Autoderef::new(&mut self.table, receiver_ty);
446 let ty = autoderef.by_ref().find_map(|(derefed_ty, _)| {
447 let (field_id, parameters) = match derefed_ty.kind(Interner) {
448 TyKind::Tuple(_, substs) => {
449 return name.as_tuple_index().and_then(|idx| {
453 .map(|a| a.assert_ty_ref(Interner))
457 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
458 let local_id = self.db.struct_data(*s).variant_data.field(name)?;
459 let field = FieldId { parent: (*s).into(), local_id };
460 (field, parameters.clone())
462 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
463 let local_id = self.db.union_data(*u).variant_data.field(name)?;
464 let field = FieldId { parent: (*u).into(), local_id };
465 (field, parameters.clone())
469 let module = self.resolver.module();
470 let is_visible = module
472 self.db.field_visibilities(field_id.parent)[field_id.local_id]
473 .is_visible_from(self.db.upcast(), mod_id)
477 // Write down the first field resolution even if it is not visible
478 // This aids IDE features for private fields like goto def and in
479 // case of autoderef finding an applicable field, this will be
480 // overwritten in a following cycle
481 if let Entry::Vacant(entry) = self.result.field_resolutions.entry(tgt_expr)
483 entry.insert(field_id);
487 // can't have `write_field_resolution` here because `self.table` is borrowed :(
488 self.result.field_resolutions.insert(tgt_expr, field_id);
489 let ty = self.db.field_types(field_id.parent)[field_id.local_id]
491 .substitute(Interner, ¶meters);
496 let adjustments = auto_deref_adjust_steps(&autoderef);
497 self.write_expr_adj(*expr, adjustments);
498 let ty = self.insert_type_vars(ty);
499 let ty = self.normalize_associated_types_in(ty);
506 Expr::Await { expr } => {
507 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
508 self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
510 Expr::Try { expr } => {
511 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
512 self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
514 Expr::Cast { expr, type_ref } => {
515 // FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
516 let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
517 let cast_ty = self.make_ty(type_ref);
518 // FIXME check the cast...
521 Expr::Ref { expr, rawness, mutability } => {
522 let mutability = lower_to_chalk_mutability(*mutability);
523 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = expected
524 .only_has_type(&mut self.table)
526 .and_then(|t| t.as_reference_or_ptr())
528 if exp_mutability == Mutability::Mut && mutability == Mutability::Not {
529 // FIXME: record type error - expected mut reference but found shared ref,
530 // which cannot be coerced
532 if exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
533 // FIXME: record type error - expected reference but found ptr,
534 // which cannot be coerced
536 Expectation::rvalue_hint(&mut self.table, Ty::clone(exp_inner))
540 let inner_ty = self.infer_expr_inner(*expr, &expectation);
542 Rawness::RawPtr => TyKind::Raw(mutability, inner_ty),
543 Rawness::Ref => TyKind::Ref(mutability, static_lifetime(), inner_ty),
547 Expr::Box { expr } => {
548 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
549 if let Some(box_) = self.resolve_boxed_box() {
550 TyBuilder::adt(self.db, box_)
552 .fill_with_defaults(self.db, || self.table.new_type_var())
558 Expr::UnaryOp { expr, op } => {
559 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
560 let inner_ty = self.resolve_ty_shallow(&inner_ty);
563 autoderef::deref(&mut self.table, inner_ty).unwrap_or_else(|| self.err_ty())
566 match inner_ty.kind(Interner) {
567 // Fast path for builtins
568 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_))
569 | TyKind::InferenceVar(
571 TyVariableKind::Integer | TyVariableKind::Float,
573 // Otherwise we resolve via the std::ops::Neg trait
575 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
579 match inner_ty.kind(Interner) {
580 // Fast path for builtins
581 TyKind::Scalar(Scalar::Bool | Scalar::Int(_) | Scalar::Uint(_))
582 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
583 // Otherwise we resolve via the std::ops::Not trait
585 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
590 Expr::BinaryOp { lhs, rhs, op } => match op {
591 Some(BinaryOp::Assignment { op: None }) => {
592 let lhs_ty = self.infer_expr(*lhs, &Expectation::none());
593 self.infer_expr_coerce(*rhs, &Expectation::has_type(lhs_ty));
594 self.result.standard_types.unit.clone()
596 Some(BinaryOp::LogicOp(_)) => {
597 let bool_ty = self.result.standard_types.bool_.clone();
598 self.infer_expr_coerce(*lhs, &Expectation::HasType(bool_ty.clone()));
599 let lhs_diverges = self.diverges;
600 self.infer_expr_coerce(*rhs, &Expectation::HasType(bool_ty.clone()));
601 // Depending on the LHS' value, the RHS can never execute.
602 self.diverges = lhs_diverges;
605 Some(op) => self.infer_overloadable_binop(*lhs, *op, *rhs, tgt_expr),
608 Expr::Range { lhs, rhs, range_type } => {
609 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
610 let rhs_expect = lhs_ty
612 .map_or_else(Expectation::none, |ty| Expectation::has_type(ty.clone()));
613 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
614 match (range_type, lhs_ty, rhs_ty) {
615 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
616 Some(adt) => TyBuilder::adt(self.db, adt).build(),
617 None => self.err_ty(),
619 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
620 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
621 None => self.err_ty(),
623 (RangeOp::Inclusive, None, Some(ty)) => {
624 match self.resolve_range_to_inclusive() {
625 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
626 None => self.err_ty(),
629 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
630 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
631 None => self.err_ty(),
633 (RangeOp::Inclusive, Some(_), Some(ty)) => {
634 match self.resolve_range_inclusive() {
635 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
636 None => self.err_ty(),
639 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
640 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
641 None => self.err_ty(),
643 (RangeOp::Inclusive, _, None) => self.err_ty(),
646 Expr::Index { base, index } => {
647 let base_ty = self.infer_expr_inner(*base, &Expectation::none());
648 let index_ty = self.infer_expr(*index, &Expectation::none());
650 if let Some(index_trait) = self.resolve_ops_index() {
651 let canonicalized = self.canonicalize(base_ty.clone());
652 let receiver_adjustments = method_resolution::resolve_indexing_op(
654 self.trait_env.clone(),
658 let (self_ty, adj) = receiver_adjustments
659 .map_or((self.err_ty(), Vec::new()), |adj| {
660 adj.apply(&mut self.table, base_ty)
662 self.write_expr_adj(*base, adj);
663 self.resolve_associated_type_with_params(
665 self.resolve_ops_index_output(),
672 Expr::Tuple { exprs } => {
673 let mut tys = match expected
674 .only_has_type(&mut self.table)
676 .map(|t| t.kind(Interner))
678 Some(TyKind::Tuple(_, substs)) => substs
680 .map(|a| a.assert_ty_ref(Interner).clone())
681 .chain(repeat_with(|| self.table.new_type_var()))
683 .collect::<Vec<_>>(),
684 _ => (0..exprs.len()).map(|_| self.table.new_type_var()).collect(),
687 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
688 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
691 TyKind::Tuple(tys.len(), Substitution::from_iter(Interner, tys)).intern(Interner)
693 Expr::Array(array) => {
695 match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(Interner)) {
696 Some(TyKind::Array(st, _) | TyKind::Slice(st)) => st.clone(),
697 _ => self.table.new_type_var(),
699 let mut coerce = CoerceMany::new(elem_ty.clone());
701 let expected = Expectation::has_type(elem_ty.clone());
702 let len = match array {
703 Array::ElementList(items) => {
704 for &expr in items.iter() {
705 let cur_elem_ty = self.infer_expr_inner(expr, &expected);
706 coerce.coerce(self, Some(expr), &cur_elem_ty);
708 Some(items.len() as u64)
710 &Array::Repeat { initializer, repeat } => {
711 self.infer_expr_coerce(initializer, &Expectation::has_type(elem_ty));
714 &Expectation::has_type(
715 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(Interner),
719 consteval::eval_usize(
721 consteval::ConstEvalCtx {
724 local_data: Default::default(),
725 infer: &mut |x| self.infer_expr(x, &expected),
731 TyKind::Array(coerce.complete(), consteval::usize_const(len)).intern(Interner)
733 Expr::Literal(lit) => match lit {
734 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
735 Literal::String(..) => {
736 TyKind::Ref(Mutability::Not, static_lifetime(), TyKind::Str.intern(Interner))
739 Literal::ByteString(bs) => {
740 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner);
742 let len = consteval::usize_const(Some(bs.len() as u64));
744 let array_type = TyKind::Array(byte_type, len).intern(Interner);
745 TyKind::Ref(Mutability::Not, static_lifetime(), array_type).intern(Interner)
747 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(Interner),
748 Literal::Int(_v, ty) => match ty {
750 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
753 None => self.table.new_integer_var(),
755 Literal::Uint(_v, ty) => match ty {
757 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
760 None => self.table.new_integer_var(),
762 Literal::Float(_v, ty) => match ty {
764 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
767 None => self.table.new_float_var(),
770 Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
772 // use a new type variable if we got unknown here
773 let ty = self.insert_type_vars_shallow(ty);
774 self.write_expr_ty(tgt_expr, ty.clone());
778 fn infer_overloadable_binop(
785 let lhs_expectation = Expectation::none();
786 let lhs_ty = self.infer_expr(lhs, &lhs_expectation);
787 let rhs_ty = self.table.new_type_var();
789 let func = self.resolve_binop_method(op);
790 let func = match func {
793 let rhs_ty = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone());
794 let rhs_ty = self.infer_expr_coerce(rhs, &Expectation::from_option(rhs_ty));
796 .builtin_binary_op_return_ty(op, lhs_ty, rhs_ty)
797 .unwrap_or_else(|| self.err_ty());
801 let subst = TyBuilder::subst_for_def(self.db, func)
802 .push(lhs_ty.clone())
803 .push(rhs_ty.clone())
805 self.write_method_resolution(tgt_expr, func, subst.clone());
807 let method_ty = self.db.value_ty(func.into()).substitute(Interner, &subst);
808 self.register_obligations_for_call(&method_ty);
810 self.infer_expr_coerce(rhs, &Expectation::has_type(rhs_ty.clone()));
812 let ret_ty = match method_ty.callable_sig(self.db) {
813 Some(sig) => sig.ret().clone(),
814 None => self.err_ty(),
817 let ret_ty = self.normalize_associated_types_in(ret_ty);
819 // FIXME: record autoref adjustments
821 // use knowledge of built-in binary ops, which can sometimes help inference
822 if let Some(builtin_rhs) = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone()) {
823 self.unify(&builtin_rhs, &rhs_ty);
825 if let Some(builtin_ret) = self.builtin_binary_op_return_ty(op, lhs_ty, rhs_ty) {
826 self.unify(&builtin_ret, &ret_ty);
835 statements: &[Statement],
836 tail: Option<ExprId>,
837 expected: &Expectation,
839 for stmt in statements {
841 Statement::Let { pat, type_ref, initializer, else_branch } => {
842 let decl_ty = type_ref
844 .map(|tr| self.make_ty(tr))
845 .unwrap_or_else(|| self.err_ty());
847 // Always use the declared type when specified
848 let mut ty = decl_ty.clone();
850 if let Some(expr) = initializer {
852 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
853 if decl_ty.is_unknown() {
858 if let Some(expr) = else_branch {
859 self.infer_expr_coerce(
861 &Expectation::has_type(Ty::new(Interner, TyKind::Never)),
865 self.infer_pat(*pat, &ty, BindingMode::default());
867 Statement::Expr { expr, .. } => {
868 self.infer_expr(*expr, &Expectation::none());
873 if let Some(expr) = tail {
874 self.infer_expr_coerce(expr, expected)
876 // Citing rustc: if there is no explicit tail expression,
877 // that is typically equivalent to a tail expression
878 // of `()` -- except if the block diverges. In that
879 // case, there is no value supplied from the tail
880 // expression (assuming there are no other breaks,
881 // this implies that the type of the block will be
883 if self.diverges.is_always() {
884 // we don't even make an attempt at coercion
885 self.table.new_maybe_never_var()
887 if let Some(t) = expected.only_has_type(&mut self.table) {
888 let _ = self.coerce(Some(expr), &TyBuilder::unit(), &t);
895 fn infer_method_call(
901 generic_args: Option<&GenericArgs>,
902 expected: &Expectation,
904 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
905 let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
907 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
909 let resolved = method_resolution::lookup_method(
910 &canonicalized_receiver.value,
912 self.trait_env.clone(),
914 self.resolver.module().into(),
917 let (receiver_ty, method_ty, substs) = match resolved {
918 Some((adjust, func)) => {
919 let (ty, adjustments) = adjust.apply(&mut self.table, receiver_ty);
920 let generics = generics(self.db.upcast(), func.into());
921 let substs = self.substs_for_method_call(generics, generic_args);
922 self.write_expr_adj(receiver, adjustments);
923 self.write_method_resolution(tgt_expr, func, substs.clone());
924 (ty, self.db.value_ty(func.into()), substs)
928 Binders::empty(Interner, self.err_ty()),
929 Substitution::empty(Interner),
932 let method_ty = method_ty.substitute(Interner, &substs);
933 self.register_obligations_for_call(&method_ty);
934 let (formal_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
936 if !sig.params().is_empty() {
937 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
939 (self.err_ty(), Vec::new(), sig.ret().clone())
942 None => (self.err_ty(), Vec::new(), self.err_ty()),
944 self.unify(&formal_receiver_ty, &receiver_ty);
946 let expected_inputs =
947 self.expected_inputs_for_expected_output(expected, ret_ty.clone(), param_tys.clone());
949 self.check_call_arguments(args, &expected_inputs, ¶m_tys);
950 self.normalize_associated_types_in(ret_ty)
953 fn expected_inputs_for_expected_output(
955 expected_output: &Expectation,
959 if let Some(expected_ty) = expected_output.to_option(&mut self.table) {
960 self.table.fudge_inference(|table| {
961 if table.try_unify(&expected_ty, &output).is_ok() {
962 table.resolve_with_fallback(inputs, &|var, kind, _, _| match kind {
963 chalk_ir::VariableKind::Ty(tk) => var.to_ty(Interner, tk).cast(Interner),
964 chalk_ir::VariableKind::Lifetime => {
965 var.to_lifetime(Interner).cast(Interner)
967 chalk_ir::VariableKind::Const(ty) => {
968 var.to_const(Interner, ty).cast(Interner)
980 fn check_call_arguments(&mut self, args: &[ExprId], expected_inputs: &[Ty], param_tys: &[Ty]) {
981 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
982 // We do this in a pretty awful way: first we type-check any arguments
983 // that are not closures, then we type-check the closures. This is so
984 // that we have more information about the types of arguments when we
985 // type-check the functions. This isn't really the right way to do this.
986 for &check_closures in &[false, true] {
987 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
988 let expected_iter = expected_inputs
991 .chain(param_iter.clone().skip(expected_inputs.len()));
992 for ((&arg, param_ty), expected_ty) in args.iter().zip(param_iter).zip(expected_iter) {
993 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
994 if is_closure != check_closures {
998 // the difference between param_ty and expected here is that
999 // expected is the parameter when the expected *return* type is
1000 // taken into account. So in `let _: &[i32] = identity(&[1, 2])`
1001 // the expected type is already `&[i32]`, whereas param_ty is
1002 // still an unbound type variable. We don't always want to force
1003 // the parameter to coerce to the expected type (for example in
1004 // `coerce_unsize_expected_type_4`).
1005 let param_ty = self.normalize_associated_types_in(param_ty);
1006 let expected = Expectation::rvalue_hint(&mut self.table, expected_ty);
1007 // infer with the expected type we have...
1008 let ty = self.infer_expr_inner(arg, &expected);
1010 // then coerce to either the expected type or just the formal parameter type
1011 let coercion_target = if let Some(ty) = expected.only_has_type(&mut self.table) {
1012 // if we are coercing to the expectation, unify with the
1013 // formal parameter type to connect everything
1014 self.unify(&ty, ¶m_ty);
1019 if !coercion_target.is_unknown() {
1020 if self.coerce(Some(arg), &ty, &coercion_target).is_err() {
1021 self.result.type_mismatches.insert(
1023 TypeMismatch { expected: coercion_target, actual: ty.clone() },
1031 fn substs_for_method_call(
1033 def_generics: Generics,
1034 generic_args: Option<&GenericArgs>,
1036 let (parent_params, self_params, type_params, impl_trait_params) =
1037 def_generics.provenance_split();
1038 assert_eq!(self_params, 0); // method shouldn't have another Self param
1039 let total_len = parent_params + type_params + impl_trait_params;
1040 let mut substs = Vec::with_capacity(total_len);
1041 // Parent arguments are unknown
1042 for _ in def_generics.iter_parent() {
1043 substs.push(self.table.new_type_var());
1045 // handle provided type arguments
1046 if let Some(generic_args) = generic_args {
1047 // if args are provided, it should be all of them, but we can't rely on that
1048 for arg in generic_args
1051 .filter(|arg| matches!(arg, GenericArg::Type(_)))
1055 GenericArg::Type(type_ref) => {
1056 let ty = self.make_ty(type_ref);
1059 GenericArg::Lifetime(_) => {}
1063 let supplied_params = substs.len();
1064 for _ in supplied_params..total_len {
1065 substs.push(self.table.new_type_var());
1067 assert_eq!(substs.len(), total_len);
1068 Substitution::from_iter(Interner, substs)
1071 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
1072 let callable_ty = self.resolve_ty_shallow(callable_ty);
1073 if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(Interner) {
1074 let def: CallableDefId = from_chalk(self.db, *fn_def);
1075 let generic_predicates = self.db.generic_predicates(def.into());
1076 for predicate in generic_predicates.iter() {
1077 let (predicate, binders) = predicate
1079 .substitute(Interner, parameters)
1080 .into_value_and_skipped_binders();
1081 always!(binders.len(Interner) == 0); // quantified where clauses not yet handled
1082 self.push_obligation(predicate.cast(Interner));
1084 // add obligation for trait implementation, if this is a trait method
1086 CallableDefId::FunctionId(f) => {
1087 if let ItemContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container {
1088 // construct a TraitRef
1089 let substs = crate::subst_prefix(
1091 generics(self.db.upcast(), trait_.into()).len(),
1093 self.push_obligation(
1094 TraitRef { trait_id: to_chalk_trait_id(trait_), substitution: substs }
1099 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}
1104 fn builtin_binary_op_return_ty(&mut self, op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Option<Ty> {
1105 let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
1106 let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
1108 BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => {
1109 Some(TyKind::Scalar(Scalar::Bool).intern(Interner))
1111 BinaryOp::Assignment { .. } => Some(TyBuilder::unit()),
1112 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => {
1113 // all integer combinations are valid here
1115 lhs_ty.kind(Interner),
1116 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1117 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1119 rhs_ty.kind(Interner),
1120 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1121 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1128 BinaryOp::ArithOp(_) => match (lhs_ty.kind(Interner), rhs_ty.kind(Interner)) {
1129 // (int, int) | (uint, uint) | (float, float)
1130 (TyKind::Scalar(Scalar::Int(_)), TyKind::Scalar(Scalar::Int(_)))
1131 | (TyKind::Scalar(Scalar::Uint(_)), TyKind::Scalar(Scalar::Uint(_)))
1132 | (TyKind::Scalar(Scalar::Float(_)), TyKind::Scalar(Scalar::Float(_))) => {
1135 // ({int}, int) | ({int}, uint)
1137 TyKind::InferenceVar(_, TyVariableKind::Integer),
1138 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1140 // (int, {int}) | (uint, {int})
1142 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1143 TyKind::InferenceVar(_, TyVariableKind::Integer),
1145 // ({float} | float)
1147 TyKind::InferenceVar(_, TyVariableKind::Float),
1148 TyKind::Scalar(Scalar::Float(_)),
1152 TyKind::Scalar(Scalar::Float(_)),
1153 TyKind::InferenceVar(_, TyVariableKind::Float),
1155 // ({int}, {int}) | ({float}, {float})
1157 TyKind::InferenceVar(_, TyVariableKind::Integer),
1158 TyKind::InferenceVar(_, TyVariableKind::Integer),
1161 TyKind::InferenceVar(_, TyVariableKind::Float),
1162 TyKind::InferenceVar(_, TyVariableKind::Float),
1169 fn builtin_binary_op_rhs_expectation(&mut self, op: BinaryOp, lhs_ty: Ty) -> Option<Ty> {
1171 BinaryOp::LogicOp(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
1172 BinaryOp::Assignment { op: None } => lhs_ty,
1173 BinaryOp::CmpOp(CmpOp::Eq { .. }) => match self
1174 .resolve_ty_shallow(&lhs_ty)
1177 TyKind::Scalar(_) | TyKind::Str => lhs_ty,
1178 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1181 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => return None,
1182 BinaryOp::CmpOp(CmpOp::Ord { .. })
1183 | BinaryOp::Assignment { op: Some(_) }
1184 | BinaryOp::ArithOp(_) => match self.resolve_ty_shallow(&lhs_ty).kind(Interner) {
1185 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_)) => lhs_ty,
1186 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1192 fn resolve_binop_method(&self, op: BinaryOp) -> Option<FunctionId> {
1193 let (name, lang_item) = match op {
1194 BinaryOp::LogicOp(_) => return None,
1195 BinaryOp::ArithOp(aop) => match aop {
1196 ArithOp::Add => (name!(add), name!(add)),
1197 ArithOp::Mul => (name!(mul), name!(mul)),
1198 ArithOp::Sub => (name!(sub), name!(sub)),
1199 ArithOp::Div => (name!(div), name!(div)),
1200 ArithOp::Rem => (name!(rem), name!(rem)),
1201 ArithOp::Shl => (name!(shl), name!(shl)),
1202 ArithOp::Shr => (name!(shr), name!(shr)),
1203 ArithOp::BitXor => (name!(bitxor), name!(bitxor)),
1204 ArithOp::BitOr => (name!(bitor), name!(bitor)),
1205 ArithOp::BitAnd => (name!(bitand), name!(bitand)),
1207 BinaryOp::Assignment { op: Some(aop) } => match aop {
1208 ArithOp::Add => (name!(add_assign), name!(add_assign)),
1209 ArithOp::Mul => (name!(mul_assign), name!(mul_assign)),
1210 ArithOp::Sub => (name!(sub_assign), name!(sub_assign)),
1211 ArithOp::Div => (name!(div_assign), name!(div_assign)),
1212 ArithOp::Rem => (name!(rem_assign), name!(rem_assign)),
1213 ArithOp::Shl => (name!(shl_assign), name!(shl_assign)),
1214 ArithOp::Shr => (name!(shr_assign), name!(shr_assign)),
1215 ArithOp::BitXor => (name!(bitxor_assign), name!(bitxor_assign)),
1216 ArithOp::BitOr => (name!(bitor_assign), name!(bitor_assign)),
1217 ArithOp::BitAnd => (name!(bitand_assign), name!(bitand_assign)),
1219 BinaryOp::CmpOp(cop) => match cop {
1220 CmpOp::Eq { negated: false } => (name!(eq), name!(eq)),
1221 CmpOp::Eq { negated: true } => (name!(ne), name!(eq)),
1222 CmpOp::Ord { ordering: Ordering::Less, strict: false } => {
1223 (name!(le), name!(partial_ord))
1225 CmpOp::Ord { ordering: Ordering::Less, strict: true } => {
1226 (name!(lt), name!(partial_ord))
1228 CmpOp::Ord { ordering: Ordering::Greater, strict: false } => {
1229 (name!(ge), name!(partial_ord))
1231 CmpOp::Ord { ordering: Ordering::Greater, strict: true } => {
1232 (name!(gt), name!(partial_ord))
1235 BinaryOp::Assignment { op: None } => return None,
1238 let trait_ = self.resolve_lang_item(lang_item)?.as_trait()?;
1240 self.db.trait_data(trait_).method_by_name(&name)