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) {
74 .insert(expr.into(), TypeMismatch { expected: target, actual: ty.clone() });
75 // Return actual type when type mismatch.
76 // This is needed for diagnostic when return type mismatch.
85 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
86 self.db.unwind_if_cancelled();
88 let body = Arc::clone(&self.body); // avoid borrow checker problem
89 let ty = match &body[tgt_expr] {
90 Expr::Missing => self.err_ty(),
91 &Expr::If { condition, then_branch, else_branch } => {
94 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
97 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
98 let mut both_arms_diverge = Diverges::Always;
100 let result_ty = self.table.new_type_var();
101 let then_ty = self.infer_expr_inner(then_branch, expected);
102 both_arms_diverge &= mem::replace(&mut self.diverges, Diverges::Maybe);
103 let mut coerce = CoerceMany::new(result_ty);
104 coerce.coerce(self, Some(then_branch), &then_ty);
105 let else_ty = match else_branch {
106 Some(else_branch) => self.infer_expr_inner(else_branch, expected),
107 None => TyBuilder::unit(),
109 both_arms_diverge &= self.diverges;
110 // FIXME: create a synthetic `else {}` so we have something to refer to here instead of None?
111 coerce.coerce(self, else_branch, &else_ty);
113 self.diverges = condition_diverges | both_arms_diverge;
117 &Expr::Let { pat, expr } => {
118 let input_ty = self.infer_expr(expr, &Expectation::none());
119 self.infer_pat(pat, &input_ty, BindingMode::default());
120 TyKind::Scalar(Scalar::Bool).intern(Interner)
122 Expr::Block { statements, tail, label, id: _ } => {
123 let old_resolver = mem::replace(
125 resolver_for_expr(self.db.upcast(), self.owner, tgt_expr),
127 let ty = match label {
129 let break_ty = self.table.new_type_var();
130 self.breakables.push(BreakableContext {
132 coerce: CoerceMany::new(break_ty.clone()),
133 label: label.map(|label| self.body[label].name.clone()),
135 let ty = self.infer_block(
139 &Expectation::has_type(break_ty),
141 let ctxt = self.breakables.pop().expect("breakable stack broken");
143 ctxt.coerce.complete()
148 None => self.infer_block(tgt_expr, statements, *tail, expected),
150 self.resolver = old_resolver;
153 Expr::Unsafe { body } | Expr::Const { body } => self.infer_expr(*body, expected),
154 Expr::TryBlock { body } => {
155 let _inner = self.infer_expr(*body, expected);
156 // FIXME should be std::result::Result<{inner}, _>
159 Expr::Async { body } => {
160 // Use the first type parameter as the output type of future.
161 // existential type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
162 let inner_ty = self.infer_expr(*body, &Expectation::none());
163 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
164 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
165 TyKind::OpaqueType(opaque_ty_id, Substitution::from1(Interner, inner_ty))
168 Expr::Loop { body, label } => {
169 self.breakables.push(BreakableContext {
171 coerce: CoerceMany::new(self.table.new_type_var()),
172 label: label.map(|label| self.body[label].name.clone()),
174 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
176 let ctxt = self.breakables.pop().expect("breakable stack broken");
179 self.diverges = Diverges::Maybe;
180 ctxt.coerce.complete()
182 TyKind::Never.intern(Interner)
185 Expr::While { condition, body, label } => {
186 self.breakables.push(BreakableContext {
188 coerce: CoerceMany::new(self.err_ty()),
189 label: label.map(|label| self.body[label].name.clone()),
193 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
195 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
196 let _ctxt = self.breakables.pop().expect("breakable stack broken");
197 // the body may not run, so it diverging doesn't mean we diverge
198 self.diverges = Diverges::Maybe;
201 Expr::For { iterable, body, pat, label } => {
202 let iterable_ty = self.infer_expr(*iterable, &Expectation::none());
204 self.breakables.push(BreakableContext {
206 coerce: CoerceMany::new(self.err_ty()),
207 label: label.map(|label| self.body[label].name.clone()),
210 self.resolve_associated_type(iterable_ty, self.resolve_into_iter_item());
212 self.infer_pat(*pat, &pat_ty, BindingMode::default());
214 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
215 let _ctxt = self.breakables.pop().expect("breakable stack broken");
216 // the body may not run, so it diverging doesn't mean we diverge
217 self.diverges = Diverges::Maybe;
220 Expr::Lambda { body, args, ret_type, arg_types } => {
221 assert_eq!(args.len(), arg_types.len());
223 let mut sig_tys = Vec::new();
225 // collect explicitly written argument types
226 for arg_type in arg_types.iter() {
227 let arg_ty = match arg_type {
228 Some(type_ref) => self.make_ty(type_ref),
229 None => self.table.new_type_var(),
231 sig_tys.push(arg_ty);
235 let ret_ty = match ret_type {
236 Some(type_ref) => self.make_ty(type_ref),
237 None => self.table.new_type_var(),
239 sig_tys.push(ret_ty.clone());
240 let sig_ty = TyKind::Function(FnPointer {
242 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
243 substitution: FnSubst(
244 Substitution::from_iter(Interner, sig_tys.clone()).shifted_in(Interner),
248 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
250 TyKind::Closure(closure_id, Substitution::from1(Interner, sig_ty.clone()))
253 // Eagerly try to relate the closure type with the expected
254 // type, otherwise we often won't have enough information to
256 self.deduce_closure_type_from_expectations(
263 // Now go through the argument patterns
264 for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
265 self.infer_pat(*arg_pat, &arg_ty, BindingMode::default());
268 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
269 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
271 self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
273 self.diverges = prev_diverges;
274 self.return_ty = prev_ret_ty;
278 Expr::Call { callee, args } => {
279 let callee_ty = self.infer_expr(*callee, &Expectation::none());
280 let mut derefs = Autoderef::new(&mut self.table, callee_ty.clone());
282 let mut derefed_callee = callee_ty.clone();
283 // manual loop to be able to access `derefs.table`
284 while let Some((callee_deref_ty, _)) = derefs.next() {
285 res = derefs.table.callable_sig(&callee_deref_ty, args.len());
287 derefed_callee = callee_deref_ty;
291 let (param_tys, ret_ty) = match res {
293 let adjustments = auto_deref_adjust_steps(&derefs);
294 self.write_expr_adj(*callee, adjustments);
297 None => (Vec::new(), self.err_ty()),
299 let indices_to_skip = self.check_legacy_const_generics(derefed_callee, args);
300 self.register_obligations_for_call(&callee_ty);
302 let expected_inputs = self.expected_inputs_for_expected_output(
308 self.check_call_arguments(args, &expected_inputs, ¶m_tys, &indices_to_skip);
309 self.normalize_associated_types_in(ret_ty)
311 Expr::MethodCall { receiver, args, method_name, generic_args } => self
317 generic_args.as_deref(),
320 Expr::Match { expr, arms } => {
321 let input_ty = self.infer_expr(*expr, &Expectation::none());
323 let expected = expected.adjust_for_branches(&mut self.table);
325 let result_ty = if arms.is_empty() {
326 TyKind::Never.intern(Interner)
329 Expectation::HasType(ty) => ty.clone(),
330 _ => self.table.new_type_var(),
333 let mut coerce = CoerceMany::new(result_ty);
335 let matchee_diverges = self.diverges;
336 let mut all_arms_diverge = Diverges::Always;
338 for arm in arms.iter() {
339 self.diverges = Diverges::Maybe;
340 let _pat_ty = self.infer_pat(arm.pat, &input_ty, BindingMode::default());
341 if let Some(guard_expr) = arm.guard {
344 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
348 let arm_ty = self.infer_expr_inner(arm.expr, &expected);
349 all_arms_diverge &= self.diverges;
350 coerce.coerce(self, Some(arm.expr), &arm_ty);
353 self.diverges = matchee_diverges | all_arms_diverge;
358 // FIXME this could be more efficient...
359 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
360 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or_else(|| self.err_ty())
362 Expr::Continue { .. } => TyKind::Never.intern(Interner),
363 Expr::Break { expr, label } => {
364 let mut coerce = match find_breakable(&mut self.breakables, label.as_ref()) {
366 // avoiding the borrowck
369 CoerceMany::new(self.result.standard_types.unknown.clone()),
372 None => CoerceMany::new(self.result.standard_types.unknown.clone()),
375 let val_ty = if let Some(expr) = *expr {
376 self.infer_expr(expr, &Expectation::none())
381 // FIXME: create a synthetic `()` during lowering so we have something to refer to here?
382 coerce.coerce(self, *expr, &val_ty);
384 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
385 ctxt.coerce = coerce;
386 ctxt.may_break = true;
388 self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop {
393 TyKind::Never.intern(Interner)
395 Expr::Return { expr } => {
396 if let Some(expr) = expr {
397 self.infer_expr_coerce(*expr, &Expectation::has_type(self.return_ty.clone()));
399 let unit = TyBuilder::unit();
400 let _ = self.coerce(Some(tgt_expr), &unit, &self.return_ty.clone());
402 TyKind::Never.intern(Interner)
404 Expr::Yield { expr } => {
405 // FIXME: track yield type for coercion
406 if let Some(expr) = expr {
407 self.infer_expr(*expr, &Expectation::none());
409 TyKind::Never.intern(Interner)
411 Expr::RecordLit { path, fields, spread } => {
412 let (ty, def_id) = self.resolve_variant(path.as_deref(), false);
413 if let Some(variant) = def_id {
414 self.write_variant_resolution(tgt_expr.into(), variant);
417 if let Some(t) = expected.only_has_type(&mut self.table) {
423 .map(|(_, s)| s.clone())
424 .unwrap_or_else(|| Substitution::empty(Interner));
425 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
426 let variant_data = def_id.map(|it| it.variant_data(self.db.upcast()));
427 for field in fields.iter() {
429 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
430 Some(local_id) => Some(FieldId { parent: def_id.unwrap(), local_id }),
432 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
438 let field_ty = field_def.map_or(self.err_ty(), |it| {
439 field_types[it.local_id].clone().substitute(Interner, &substs)
441 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
443 if let Some(expr) = spread {
444 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
448 Expr::Field { expr, name } => {
449 let receiver_ty = self.infer_expr_inner(*expr, &Expectation::none());
451 let mut autoderef = Autoderef::new(&mut self.table, receiver_ty);
452 let ty = autoderef.by_ref().find_map(|(derefed_ty, _)| {
453 let (field_id, parameters) = match derefed_ty.kind(Interner) {
454 TyKind::Tuple(_, substs) => {
455 return name.as_tuple_index().and_then(|idx| {
459 .map(|a| a.assert_ty_ref(Interner))
463 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
464 let local_id = self.db.struct_data(*s).variant_data.field(name)?;
465 let field = FieldId { parent: (*s).into(), local_id };
466 (field, parameters.clone())
468 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
469 let local_id = self.db.union_data(*u).variant_data.field(name)?;
470 let field = FieldId { parent: (*u).into(), local_id };
471 (field, parameters.clone())
475 let module = self.resolver.module();
476 let is_visible = module
478 self.db.field_visibilities(field_id.parent)[field_id.local_id]
479 .is_visible_from(self.db.upcast(), mod_id)
483 // Write down the first field resolution even if it is not visible
484 // This aids IDE features for private fields like goto def and in
485 // case of autoderef finding an applicable field, this will be
486 // overwritten in a following cycle
487 if let Entry::Vacant(entry) = self.result.field_resolutions.entry(tgt_expr)
489 entry.insert(field_id);
493 // can't have `write_field_resolution` here because `self.table` is borrowed :(
494 self.result.field_resolutions.insert(tgt_expr, field_id);
495 let ty = self.db.field_types(field_id.parent)[field_id.local_id]
497 .substitute(Interner, ¶meters);
502 let adjustments = auto_deref_adjust_steps(&autoderef);
503 self.write_expr_adj(*expr, adjustments);
504 let ty = self.insert_type_vars(ty);
505 let ty = self.normalize_associated_types_in(ty);
512 Expr::Await { expr } => {
513 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
514 self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
516 Expr::Try { expr } => {
517 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
518 self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
520 Expr::Cast { expr, type_ref } => {
521 // FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
522 let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
523 let cast_ty = self.make_ty(type_ref);
524 // FIXME check the cast...
527 Expr::Ref { expr, rawness, mutability } => {
528 let mutability = lower_to_chalk_mutability(*mutability);
529 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = expected
530 .only_has_type(&mut self.table)
532 .and_then(|t| t.as_reference_or_ptr())
534 if exp_mutability == Mutability::Mut && mutability == Mutability::Not {
535 // FIXME: record type error - expected mut reference but found shared ref,
536 // which cannot be coerced
538 if exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
539 // FIXME: record type error - expected reference but found ptr,
540 // which cannot be coerced
542 Expectation::rvalue_hint(&mut self.table, Ty::clone(exp_inner))
546 let inner_ty = self.infer_expr_inner(*expr, &expectation);
548 Rawness::RawPtr => TyKind::Raw(mutability, inner_ty),
549 Rawness::Ref => TyKind::Ref(mutability, static_lifetime(), inner_ty),
553 Expr::Box { expr } => {
554 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
555 if let Some(box_) = self.resolve_boxed_box() {
556 TyBuilder::adt(self.db, box_)
558 .fill_with_defaults(self.db, || self.table.new_type_var())
564 Expr::UnaryOp { expr, op } => {
565 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
566 let inner_ty = self.resolve_ty_shallow(&inner_ty);
569 autoderef::deref(&mut self.table, inner_ty).unwrap_or_else(|| self.err_ty())
572 match inner_ty.kind(Interner) {
573 // Fast path for builtins
574 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_))
575 | TyKind::InferenceVar(
577 TyVariableKind::Integer | TyVariableKind::Float,
579 // Otherwise we resolve via the std::ops::Neg trait
581 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
585 match inner_ty.kind(Interner) {
586 // Fast path for builtins
587 TyKind::Scalar(Scalar::Bool | Scalar::Int(_) | Scalar::Uint(_))
588 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
589 // Otherwise we resolve via the std::ops::Not trait
591 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
596 Expr::BinaryOp { lhs, rhs, op } => match op {
597 Some(BinaryOp::Assignment { op: None }) => {
598 let lhs_ty = self.infer_expr(*lhs, &Expectation::none());
599 self.infer_expr_coerce(*rhs, &Expectation::has_type(lhs_ty));
600 self.result.standard_types.unit.clone()
602 Some(BinaryOp::LogicOp(_)) => {
603 let bool_ty = self.result.standard_types.bool_.clone();
604 self.infer_expr_coerce(*lhs, &Expectation::HasType(bool_ty.clone()));
605 let lhs_diverges = self.diverges;
606 self.infer_expr_coerce(*rhs, &Expectation::HasType(bool_ty.clone()));
607 // Depending on the LHS' value, the RHS can never execute.
608 self.diverges = lhs_diverges;
611 Some(op) => self.infer_overloadable_binop(*lhs, *op, *rhs, tgt_expr),
614 Expr::Range { lhs, rhs, range_type } => {
615 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
616 let rhs_expect = lhs_ty
618 .map_or_else(Expectation::none, |ty| Expectation::has_type(ty.clone()));
619 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
620 match (range_type, lhs_ty, rhs_ty) {
621 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
622 Some(adt) => TyBuilder::adt(self.db, adt).build(),
623 None => self.err_ty(),
625 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
626 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
627 None => self.err_ty(),
629 (RangeOp::Inclusive, None, Some(ty)) => {
630 match self.resolve_range_to_inclusive() {
631 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
632 None => self.err_ty(),
635 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
636 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
637 None => self.err_ty(),
639 (RangeOp::Inclusive, Some(_), Some(ty)) => {
640 match self.resolve_range_inclusive() {
641 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
642 None => self.err_ty(),
645 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
646 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
647 None => self.err_ty(),
649 (RangeOp::Inclusive, _, None) => self.err_ty(),
652 Expr::Index { base, index } => {
653 let base_ty = self.infer_expr_inner(*base, &Expectation::none());
654 let index_ty = self.infer_expr(*index, &Expectation::none());
656 if let Some(index_trait) = self.resolve_ops_index() {
657 let canonicalized = self.canonicalize(base_ty.clone());
658 let receiver_adjustments = method_resolution::resolve_indexing_op(
660 self.trait_env.clone(),
664 let (self_ty, adj) = receiver_adjustments
665 .map_or((self.err_ty(), Vec::new()), |adj| {
666 adj.apply(&mut self.table, base_ty)
668 self.write_expr_adj(*base, adj);
669 self.resolve_associated_type_with_params(
671 self.resolve_ops_index_output(),
672 &[GenericArgData::Ty(index_ty).intern(Interner)],
678 Expr::Tuple { exprs } => {
679 let mut tys = match expected
680 .only_has_type(&mut self.table)
682 .map(|t| t.kind(Interner))
684 Some(TyKind::Tuple(_, substs)) => substs
686 .map(|a| a.assert_ty_ref(Interner).clone())
687 .chain(repeat_with(|| self.table.new_type_var()))
689 .collect::<Vec<_>>(),
690 _ => (0..exprs.len()).map(|_| self.table.new_type_var()).collect(),
693 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
694 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
697 TyKind::Tuple(tys.len(), Substitution::from_iter(Interner, tys)).intern(Interner)
699 Expr::Array(array) => {
701 match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(Interner)) {
702 Some(TyKind::Array(st, _) | TyKind::Slice(st)) => st.clone(),
703 _ => self.table.new_type_var(),
705 let mut coerce = CoerceMany::new(elem_ty.clone());
707 let expected = Expectation::has_type(elem_ty.clone());
708 let len = match array {
709 Array::ElementList(items) => {
710 for &expr in items.iter() {
711 let cur_elem_ty = self.infer_expr_inner(expr, &expected);
712 coerce.coerce(self, Some(expr), &cur_elem_ty);
714 consteval::usize_const(Some(items.len() as u64))
716 &Array::Repeat { initializer, repeat } => {
717 self.infer_expr_coerce(initializer, &Expectation::has_type(elem_ty));
720 &Expectation::has_type(
721 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(Interner),
725 if let Some(g_def) = self.owner.as_generic_def_id() {
726 let generics = generics(self.db.upcast(), g_def);
727 consteval::eval_to_const(
729 ParamLoweringMode::Placeholder,
732 DebruijnIndex::INNERMOST,
735 consteval::usize_const(None)
740 TyKind::Array(coerce.complete(), len).intern(Interner)
742 Expr::Literal(lit) => match lit {
743 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
744 Literal::String(..) => {
745 TyKind::Ref(Mutability::Not, static_lifetime(), TyKind::Str.intern(Interner))
748 Literal::ByteString(bs) => {
749 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner);
751 let len = consteval::usize_const(Some(bs.len() as u64));
753 let array_type = TyKind::Array(byte_type, len).intern(Interner);
754 TyKind::Ref(Mutability::Not, static_lifetime(), array_type).intern(Interner)
756 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(Interner),
757 Literal::Int(_v, ty) => match ty {
759 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
762 None => self.table.new_integer_var(),
764 Literal::Uint(_v, ty) => match ty {
766 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
769 None => self.table.new_integer_var(),
771 Literal::Float(_v, ty) => match ty {
773 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
776 None => self.table.new_float_var(),
779 Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
781 // use a new type variable if we got unknown here
782 let ty = self.insert_type_vars_shallow(ty);
783 self.write_expr_ty(tgt_expr, ty.clone());
787 fn infer_overloadable_binop(
794 let lhs_expectation = Expectation::none();
795 let lhs_ty = self.infer_expr(lhs, &lhs_expectation);
796 let rhs_ty = self.table.new_type_var();
798 let func = self.resolve_binop_method(op);
799 let func = match func {
802 let rhs_ty = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone());
803 let rhs_ty = self.infer_expr_coerce(rhs, &Expectation::from_option(rhs_ty));
805 .builtin_binary_op_return_ty(op, lhs_ty, rhs_ty)
806 .unwrap_or_else(|| self.err_ty());
810 let subst = TyBuilder::subst_for_def(self.db, func)
811 .push(lhs_ty.clone())
812 .push(rhs_ty.clone())
814 self.write_method_resolution(tgt_expr, func, subst.clone());
816 let method_ty = self.db.value_ty(func.into()).substitute(Interner, &subst);
817 self.register_obligations_for_call(&method_ty);
819 self.infer_expr_coerce(rhs, &Expectation::has_type(rhs_ty.clone()));
821 let ret_ty = match method_ty.callable_sig(self.db) {
822 Some(sig) => sig.ret().clone(),
823 None => self.err_ty(),
826 let ret_ty = self.normalize_associated_types_in(ret_ty);
828 // FIXME: record autoref adjustments
830 // use knowledge of built-in binary ops, which can sometimes help inference
831 if let Some(builtin_rhs) = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone()) {
832 self.unify(&builtin_rhs, &rhs_ty);
834 if let Some(builtin_ret) = self.builtin_binary_op_return_ty(op, lhs_ty, rhs_ty) {
835 self.unify(&builtin_ret, &ret_ty);
844 statements: &[Statement],
845 tail: Option<ExprId>,
846 expected: &Expectation,
848 for stmt in statements {
850 Statement::Let { pat, type_ref, initializer, else_branch } => {
851 let decl_ty = type_ref
853 .map(|tr| self.make_ty(tr))
854 .unwrap_or_else(|| self.err_ty());
856 // Always use the declared type when specified
857 let mut ty = decl_ty.clone();
859 if let Some(expr) = initializer {
861 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
862 if decl_ty.is_unknown() {
867 if let Some(expr) = else_branch {
868 self.infer_expr_coerce(
870 &Expectation::has_type(Ty::new(Interner, TyKind::Never)),
874 self.infer_pat(*pat, &ty, BindingMode::default());
876 Statement::Expr { expr, .. } => {
877 self.infer_expr(*expr, &Expectation::none());
882 if let Some(expr) = tail {
883 self.infer_expr_coerce(expr, expected)
885 // Citing rustc: if there is no explicit tail expression,
886 // that is typically equivalent to a tail expression
887 // of `()` -- except if the block diverges. In that
888 // case, there is no value supplied from the tail
889 // expression (assuming there are no other breaks,
890 // this implies that the type of the block will be
892 if self.diverges.is_always() {
893 // we don't even make an attempt at coercion
894 self.table.new_maybe_never_var()
896 if let Some(t) = expected.only_has_type(&mut self.table) {
897 let _ = self.coerce(Some(expr), &TyBuilder::unit(), &t);
904 fn infer_method_call(
910 generic_args: Option<&GenericArgs>,
911 expected: &Expectation,
913 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
914 let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
916 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
918 let resolved = method_resolution::lookup_method(
919 &canonicalized_receiver.value,
921 self.trait_env.clone(),
923 self.resolver.module().into(),
926 let (receiver_ty, method_ty, substs) = match resolved {
927 Some((adjust, func)) => {
928 let (ty, adjustments) = adjust.apply(&mut self.table, receiver_ty);
929 let generics = generics(self.db.upcast(), func.into());
930 let substs = self.substs_for_method_call(generics, generic_args);
931 self.write_expr_adj(receiver, adjustments);
932 self.write_method_resolution(tgt_expr, func, substs.clone());
933 (ty, self.db.value_ty(func.into()), substs)
937 Binders::empty(Interner, self.err_ty()),
938 Substitution::empty(Interner),
941 let method_ty = method_ty.substitute(Interner, &substs);
942 self.register_obligations_for_call(&method_ty);
943 let (formal_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
945 if !sig.params().is_empty() {
946 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
948 (self.err_ty(), Vec::new(), sig.ret().clone())
951 None => (self.err_ty(), Vec::new(), self.err_ty()),
953 self.unify(&formal_receiver_ty, &receiver_ty);
955 let expected_inputs =
956 self.expected_inputs_for_expected_output(expected, ret_ty.clone(), param_tys.clone());
958 self.check_call_arguments(args, &expected_inputs, ¶m_tys, &[]);
959 self.normalize_associated_types_in(ret_ty)
962 fn expected_inputs_for_expected_output(
964 expected_output: &Expectation,
968 if let Some(expected_ty) = expected_output.to_option(&mut self.table) {
969 self.table.fudge_inference(|table| {
970 if table.try_unify(&expected_ty, &output).is_ok() {
971 table.resolve_with_fallback(inputs, &|var, kind, _, _| match kind {
972 chalk_ir::VariableKind::Ty(tk) => var.to_ty(Interner, tk).cast(Interner),
973 chalk_ir::VariableKind::Lifetime => {
974 var.to_lifetime(Interner).cast(Interner)
976 chalk_ir::VariableKind::Const(ty) => {
977 var.to_const(Interner, ty).cast(Interner)
989 fn check_call_arguments(
992 expected_inputs: &[Ty],
994 skip_indices: &[u32],
996 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
997 // We do this in a pretty awful way: first we type-check any arguments
998 // that are not closures, then we type-check the closures. This is so
999 // that we have more information about the types of arguments when we
1000 // type-check the functions. This isn't really the right way to do this.
1001 for &check_closures in &[false, true] {
1002 let mut skip_indices = skip_indices.into_iter().copied().fuse().peekable();
1003 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
1004 let expected_iter = expected_inputs
1007 .chain(param_iter.clone().skip(expected_inputs.len()));
1008 for (idx, ((&arg, param_ty), expected_ty)) in
1009 args.iter().zip(param_iter).zip(expected_iter).enumerate()
1011 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
1012 if is_closure != check_closures {
1016 while skip_indices.peek().map_or(false, |i| *i < idx as u32) {
1017 skip_indices.next();
1019 if skip_indices.peek().copied() == Some(idx as u32) {
1023 // the difference between param_ty and expected here is that
1024 // expected is the parameter when the expected *return* type is
1025 // taken into account. So in `let _: &[i32] = identity(&[1, 2])`
1026 // the expected type is already `&[i32]`, whereas param_ty is
1027 // still an unbound type variable. We don't always want to force
1028 // the parameter to coerce to the expected type (for example in
1029 // `coerce_unsize_expected_type_4`).
1030 let param_ty = self.normalize_associated_types_in(param_ty);
1031 let expected = Expectation::rvalue_hint(&mut self.table, expected_ty);
1032 // infer with the expected type we have...
1033 let ty = self.infer_expr_inner(arg, &expected);
1035 // then coerce to either the expected type or just the formal parameter type
1036 let coercion_target = if let Some(ty) = expected.only_has_type(&mut self.table) {
1037 // if we are coercing to the expectation, unify with the
1038 // formal parameter type to connect everything
1039 self.unify(&ty, ¶m_ty);
1044 if !coercion_target.is_unknown() {
1045 if self.coerce(Some(arg), &ty, &coercion_target).is_err() {
1046 self.result.type_mismatches.insert(
1048 TypeMismatch { expected: coercion_target, actual: ty.clone() },
1056 fn substs_for_method_call(
1058 def_generics: Generics,
1059 generic_args: Option<&GenericArgs>,
1061 let (parent_params, self_params, type_params, const_params, impl_trait_params) =
1062 def_generics.provenance_split();
1063 assert_eq!(self_params, 0); // method shouldn't have another Self param
1064 let total_len = parent_params + type_params + const_params + impl_trait_params;
1065 let mut substs = Vec::with_capacity(total_len);
1066 // Parent arguments are unknown
1067 for (id, param) in def_generics.iter_parent() {
1069 TypeOrConstParamData::TypeParamData(_) => {
1070 substs.push(GenericArgData::Ty(self.table.new_type_var()).intern(Interner));
1072 TypeOrConstParamData::ConstParamData(_) => {
1073 let ty = self.db.const_param_ty(ConstParamId::from_unchecked(id));
1075 .push(GenericArgData::Const(self.table.new_const_var(ty)).intern(Interner));
1079 // handle provided arguments
1080 if let Some(generic_args) = generic_args {
1081 // if args are provided, it should be all of them, but we can't rely on that
1082 for (arg, kind_id) in generic_args
1085 .filter(|arg| !matches!(arg, GenericArg::Lifetime(_)))
1086 .take(type_params + const_params)
1087 .zip(def_generics.iter_id().skip(parent_params))
1089 if let Some(g) = generic_arg_to_chalk(
1094 |this, type_ref| this.make_ty(type_ref),
1096 const_or_path_to_chalk(
1100 ParamLoweringMode::Placeholder,
1101 || generics(this.db.upcast(), (&this.resolver).generic_def().unwrap()),
1102 DebruijnIndex::INNERMOST,
1110 for (id, data) in def_generics.iter().skip(substs.len()) {
1112 TypeOrConstParamData::TypeParamData(_) => {
1113 substs.push(GenericArgData::Ty(self.table.new_type_var()).intern(Interner))
1115 TypeOrConstParamData::ConstParamData(_) => {
1117 GenericArgData::Const(self.table.new_const_var(
1118 self.db.const_param_ty(ConstParamId::from_unchecked(id)),
1125 assert_eq!(substs.len(), total_len);
1126 Substitution::from_iter(Interner, substs)
1129 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
1130 let callable_ty = self.resolve_ty_shallow(callable_ty);
1131 if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(Interner) {
1132 let def: CallableDefId = from_chalk(self.db, *fn_def);
1133 let generic_predicates = self.db.generic_predicates(def.into());
1134 for predicate in generic_predicates.iter() {
1135 let (predicate, binders) = predicate
1137 .substitute(Interner, parameters)
1138 .into_value_and_skipped_binders();
1139 always!(binders.len(Interner) == 0); // quantified where clauses not yet handled
1140 self.push_obligation(predicate.cast(Interner));
1142 // add obligation for trait implementation, if this is a trait method
1144 CallableDefId::FunctionId(f) => {
1145 if let ItemContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container {
1146 // construct a TraitRef
1147 let substs = crate::subst_prefix(
1149 generics(self.db.upcast(), trait_.into()).len(),
1151 self.push_obligation(
1152 TraitRef { trait_id: to_chalk_trait_id(trait_), substitution: substs }
1157 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}
1162 /// Returns the argument indices to skip.
1163 fn check_legacy_const_generics(&mut self, callee: Ty, args: &[ExprId]) -> Vec<u32> {
1164 let (func, subst) = match callee.kind(Interner) {
1165 TyKind::FnDef(fn_id, subst) => {
1166 let callable = CallableDefId::from_chalk(self.db, *fn_id);
1167 let func = match callable {
1168 CallableDefId::FunctionId(f) => f,
1169 _ => return Vec::new(),
1173 _ => return Vec::new(),
1176 let data = self.db.function_data(func);
1177 if data.legacy_const_generics_indices.is_empty() {
1181 // only use legacy const generics if the param count matches with them
1182 if data.params.len() + data.legacy_const_generics_indices.len() != args.len() {
1186 // check legacy const parameters
1187 for (subst_idx, arg_idx) in data.legacy_const_generics_indices.iter().copied().enumerate() {
1188 let arg = match subst.at(Interner, subst_idx).constant(Interner) {
1190 None => continue, // not a const parameter?
1192 if arg_idx >= args.len() as u32 {
1195 let _ty = arg.data(Interner).ty.clone();
1196 let expected = Expectation::none(); // FIXME use actual const ty, when that is lowered correctly
1197 self.infer_expr(args[arg_idx as usize], &expected);
1198 // FIXME: evaluate and unify with the const
1200 let mut indices = data.legacy_const_generics_indices.clone();
1205 fn builtin_binary_op_return_ty(&mut self, op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Option<Ty> {
1206 let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
1207 let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
1209 BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => {
1210 Some(TyKind::Scalar(Scalar::Bool).intern(Interner))
1212 BinaryOp::Assignment { .. } => Some(TyBuilder::unit()),
1213 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => {
1214 // all integer combinations are valid here
1216 lhs_ty.kind(Interner),
1217 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1218 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1220 rhs_ty.kind(Interner),
1221 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1222 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1229 BinaryOp::ArithOp(_) => match (lhs_ty.kind(Interner), rhs_ty.kind(Interner)) {
1230 // (int, int) | (uint, uint) | (float, float)
1231 (TyKind::Scalar(Scalar::Int(_)), TyKind::Scalar(Scalar::Int(_)))
1232 | (TyKind::Scalar(Scalar::Uint(_)), TyKind::Scalar(Scalar::Uint(_)))
1233 | (TyKind::Scalar(Scalar::Float(_)), TyKind::Scalar(Scalar::Float(_))) => {
1236 // ({int}, int) | ({int}, uint)
1238 TyKind::InferenceVar(_, TyVariableKind::Integer),
1239 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1241 // (int, {int}) | (uint, {int})
1243 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1244 TyKind::InferenceVar(_, TyVariableKind::Integer),
1246 // ({float} | float)
1248 TyKind::InferenceVar(_, TyVariableKind::Float),
1249 TyKind::Scalar(Scalar::Float(_)),
1253 TyKind::Scalar(Scalar::Float(_)),
1254 TyKind::InferenceVar(_, TyVariableKind::Float),
1256 // ({int}, {int}) | ({float}, {float})
1258 TyKind::InferenceVar(_, TyVariableKind::Integer),
1259 TyKind::InferenceVar(_, TyVariableKind::Integer),
1262 TyKind::InferenceVar(_, TyVariableKind::Float),
1263 TyKind::InferenceVar(_, TyVariableKind::Float),
1270 fn builtin_binary_op_rhs_expectation(&mut self, op: BinaryOp, lhs_ty: Ty) -> Option<Ty> {
1272 BinaryOp::LogicOp(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
1273 BinaryOp::Assignment { op: None } => lhs_ty,
1274 BinaryOp::CmpOp(CmpOp::Eq { .. }) => match self
1275 .resolve_ty_shallow(&lhs_ty)
1278 TyKind::Scalar(_) | TyKind::Str => lhs_ty,
1279 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1282 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => return None,
1283 BinaryOp::CmpOp(CmpOp::Ord { .. })
1284 | BinaryOp::Assignment { op: Some(_) }
1285 | BinaryOp::ArithOp(_) => match self.resolve_ty_shallow(&lhs_ty).kind(Interner) {
1286 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_)) => lhs_ty,
1287 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1293 fn resolve_binop_method(&self, op: BinaryOp) -> Option<FunctionId> {
1294 let (name, lang_item) = match op {
1295 BinaryOp::LogicOp(_) => return None,
1296 BinaryOp::ArithOp(aop) => match aop {
1297 ArithOp::Add => (name!(add), name!(add)),
1298 ArithOp::Mul => (name!(mul), name!(mul)),
1299 ArithOp::Sub => (name!(sub), name!(sub)),
1300 ArithOp::Div => (name!(div), name!(div)),
1301 ArithOp::Rem => (name!(rem), name!(rem)),
1302 ArithOp::Shl => (name!(shl), name!(shl)),
1303 ArithOp::Shr => (name!(shr), name!(shr)),
1304 ArithOp::BitXor => (name!(bitxor), name!(bitxor)),
1305 ArithOp::BitOr => (name!(bitor), name!(bitor)),
1306 ArithOp::BitAnd => (name!(bitand), name!(bitand)),
1308 BinaryOp::Assignment { op: Some(aop) } => match aop {
1309 ArithOp::Add => (name!(add_assign), name!(add_assign)),
1310 ArithOp::Mul => (name!(mul_assign), name!(mul_assign)),
1311 ArithOp::Sub => (name!(sub_assign), name!(sub_assign)),
1312 ArithOp::Div => (name!(div_assign), name!(div_assign)),
1313 ArithOp::Rem => (name!(rem_assign), name!(rem_assign)),
1314 ArithOp::Shl => (name!(shl_assign), name!(shl_assign)),
1315 ArithOp::Shr => (name!(shr_assign), name!(shr_assign)),
1316 ArithOp::BitXor => (name!(bitxor_assign), name!(bitxor_assign)),
1317 ArithOp::BitOr => (name!(bitor_assign), name!(bitor_assign)),
1318 ArithOp::BitAnd => (name!(bitand_assign), name!(bitand_assign)),
1320 BinaryOp::CmpOp(cop) => match cop {
1321 CmpOp::Eq { negated: false } => (name!(eq), name!(eq)),
1322 CmpOp::Eq { negated: true } => (name!(ne), name!(eq)),
1323 CmpOp::Ord { ordering: Ordering::Less, strict: false } => {
1324 (name!(le), name!(partial_ord))
1326 CmpOp::Ord { ordering: Ordering::Less, strict: true } => {
1327 (name!(lt), name!(partial_ord))
1329 CmpOp::Ord { ordering: Ordering::Greater, strict: false } => {
1330 (name!(ge), name!(partial_ord))
1332 CmpOp::Ord { ordering: Ordering::Greater, strict: true } => {
1333 (name!(gt), name!(partial_ord))
1336 BinaryOp::Assignment { op: None } => return None,
1339 let trait_ = self.resolve_lang_item(lang_item)?.as_trait()?;
1341 self.db.trait_data(trait_).method_by_name(&name)