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 let ret_ty = self.table.new_type_var();
161 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
162 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
164 let inner_ty = self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
166 self.diverges = prev_diverges;
167 self.return_ty = prev_ret_ty;
169 // Use the first type parameter as the output type of future.
170 // existential type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
171 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
172 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
173 TyKind::OpaqueType(opaque_ty_id, Substitution::from1(Interner, inner_ty))
176 Expr::Loop { body, label } => {
177 self.breakables.push(BreakableContext {
179 coerce: CoerceMany::new(self.table.new_type_var()),
180 label: label.map(|label| self.body[label].name.clone()),
182 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
184 let ctxt = self.breakables.pop().expect("breakable stack broken");
187 self.diverges = Diverges::Maybe;
188 ctxt.coerce.complete()
190 TyKind::Never.intern(Interner)
193 Expr::While { condition, body, label } => {
194 self.breakables.push(BreakableContext {
196 coerce: CoerceMany::new(self.err_ty()),
197 label: label.map(|label| self.body[label].name.clone()),
201 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
203 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
204 let _ctxt = self.breakables.pop().expect("breakable stack broken");
205 // the body may not run, so it diverging doesn't mean we diverge
206 self.diverges = Diverges::Maybe;
209 Expr::For { iterable, body, pat, label } => {
210 let iterable_ty = self.infer_expr(*iterable, &Expectation::none());
212 self.breakables.push(BreakableContext {
214 coerce: CoerceMany::new(self.err_ty()),
215 label: label.map(|label| self.body[label].name.clone()),
218 self.resolve_associated_type(iterable_ty, self.resolve_into_iter_item());
220 self.infer_pat(*pat, &pat_ty, BindingMode::default());
222 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
223 let _ctxt = self.breakables.pop().expect("breakable stack broken");
224 // the body may not run, so it diverging doesn't mean we diverge
225 self.diverges = Diverges::Maybe;
228 Expr::Lambda { body, args, ret_type, arg_types } => {
229 assert_eq!(args.len(), arg_types.len());
231 let mut sig_tys = Vec::new();
233 // collect explicitly written argument types
234 for arg_type in arg_types.iter() {
235 let arg_ty = match arg_type {
236 Some(type_ref) => self.make_ty(type_ref),
237 None => self.table.new_type_var(),
239 sig_tys.push(arg_ty);
243 let ret_ty = match ret_type {
244 Some(type_ref) => self.make_ty(type_ref),
245 None => self.table.new_type_var(),
247 sig_tys.push(ret_ty.clone());
248 let sig_ty = TyKind::Function(FnPointer {
250 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
251 substitution: FnSubst(
252 Substitution::from_iter(Interner, sig_tys.clone()).shifted_in(Interner),
256 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
258 TyKind::Closure(closure_id, Substitution::from1(Interner, sig_ty.clone()))
261 // Eagerly try to relate the closure type with the expected
262 // type, otherwise we often won't have enough information to
264 self.deduce_closure_type_from_expectations(
271 // Now go through the argument patterns
272 for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
273 self.infer_pat(*arg_pat, &arg_ty, BindingMode::default());
276 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
277 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
279 self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
281 self.diverges = prev_diverges;
282 self.return_ty = prev_ret_ty;
286 Expr::Call { callee, args } => {
287 let callee_ty = self.infer_expr(*callee, &Expectation::none());
288 let mut derefs = Autoderef::new(&mut self.table, callee_ty.clone());
290 let mut derefed_callee = callee_ty.clone();
291 // manual loop to be able to access `derefs.table`
292 while let Some((callee_deref_ty, _)) = derefs.next() {
293 res = derefs.table.callable_sig(&callee_deref_ty, args.len());
295 derefed_callee = callee_deref_ty;
299 let (param_tys, ret_ty) = match res {
301 let adjustments = auto_deref_adjust_steps(&derefs);
302 self.write_expr_adj(*callee, adjustments);
305 None => (Vec::new(), self.err_ty()),
307 let indices_to_skip = self.check_legacy_const_generics(derefed_callee, args);
308 self.register_obligations_for_call(&callee_ty);
310 let expected_inputs = self.expected_inputs_for_expected_output(
316 self.check_call_arguments(args, &expected_inputs, ¶m_tys, &indices_to_skip);
317 self.normalize_associated_types_in(ret_ty)
319 Expr::MethodCall { receiver, args, method_name, generic_args } => self
325 generic_args.as_deref(),
328 Expr::Match { expr, arms } => {
329 let input_ty = self.infer_expr(*expr, &Expectation::none());
331 let expected = expected.adjust_for_branches(&mut self.table);
333 let result_ty = if arms.is_empty() {
334 TyKind::Never.intern(Interner)
337 Expectation::HasType(ty) => ty.clone(),
338 _ => self.table.new_type_var(),
341 let mut coerce = CoerceMany::new(result_ty);
343 let matchee_diverges = self.diverges;
344 let mut all_arms_diverge = Diverges::Always;
346 for arm in arms.iter() {
347 self.diverges = Diverges::Maybe;
348 let _pat_ty = self.infer_pat(arm.pat, &input_ty, BindingMode::default());
349 if let Some(guard_expr) = arm.guard {
352 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
356 let arm_ty = self.infer_expr_inner(arm.expr, &expected);
357 all_arms_diverge &= self.diverges;
358 coerce.coerce(self, Some(arm.expr), &arm_ty);
361 self.diverges = matchee_diverges | all_arms_diverge;
366 // FIXME this could be more efficient...
367 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
368 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or_else(|| self.err_ty())
370 Expr::Continue { .. } => TyKind::Never.intern(Interner),
371 Expr::Break { expr, label } => {
372 let mut coerce = match find_breakable(&mut self.breakables, label.as_ref()) {
374 // avoiding the borrowck
377 CoerceMany::new(self.result.standard_types.unknown.clone()),
380 None => CoerceMany::new(self.result.standard_types.unknown.clone()),
383 let val_ty = if let Some(expr) = *expr {
384 self.infer_expr(expr, &Expectation::none())
389 // FIXME: create a synthetic `()` during lowering so we have something to refer to here?
390 coerce.coerce(self, *expr, &val_ty);
392 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
393 ctxt.coerce = coerce;
394 ctxt.may_break = true;
396 self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop {
401 TyKind::Never.intern(Interner)
403 Expr::Return { expr } => {
404 if let Some(expr) = expr {
405 self.infer_expr_coerce(*expr, &Expectation::has_type(self.return_ty.clone()));
407 let unit = TyBuilder::unit();
408 let _ = self.coerce(Some(tgt_expr), &unit, &self.return_ty.clone());
410 TyKind::Never.intern(Interner)
412 Expr::Yield { expr } => {
413 // FIXME: track yield type for coercion
414 if let Some(expr) = expr {
415 self.infer_expr(*expr, &Expectation::none());
417 TyKind::Never.intern(Interner)
419 Expr::RecordLit { path, fields, spread } => {
420 let (ty, def_id) = self.resolve_variant(path.as_deref(), false);
421 if let Some(variant) = def_id {
422 self.write_variant_resolution(tgt_expr.into(), variant);
425 if let Some(t) = expected.only_has_type(&mut self.table) {
431 .map(|(_, s)| s.clone())
432 .unwrap_or_else(|| Substitution::empty(Interner));
433 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
434 let variant_data = def_id.map(|it| it.variant_data(self.db.upcast()));
435 for field in fields.iter() {
437 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
438 Some(local_id) => Some(FieldId { parent: def_id.unwrap(), local_id }),
440 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
446 let field_ty = field_def.map_or(self.err_ty(), |it| {
447 field_types[it.local_id].clone().substitute(Interner, &substs)
449 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
451 if let Some(expr) = spread {
452 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
456 Expr::Field { expr, name } => {
457 let receiver_ty = self.infer_expr_inner(*expr, &Expectation::none());
459 let mut autoderef = Autoderef::new(&mut self.table, receiver_ty);
460 let ty = autoderef.by_ref().find_map(|(derefed_ty, _)| {
461 let (field_id, parameters) = match derefed_ty.kind(Interner) {
462 TyKind::Tuple(_, substs) => {
463 return name.as_tuple_index().and_then(|idx| {
467 .map(|a| a.assert_ty_ref(Interner))
471 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
472 let local_id = self.db.struct_data(*s).variant_data.field(name)?;
473 let field = FieldId { parent: (*s).into(), local_id };
474 (field, parameters.clone())
476 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
477 let local_id = self.db.union_data(*u).variant_data.field(name)?;
478 let field = FieldId { parent: (*u).into(), local_id };
479 (field, parameters.clone())
483 let module = self.resolver.module();
484 let is_visible = module
486 self.db.field_visibilities(field_id.parent)[field_id.local_id]
487 .is_visible_from(self.db.upcast(), mod_id)
491 // Write down the first field resolution even if it is not visible
492 // This aids IDE features for private fields like goto def and in
493 // case of autoderef finding an applicable field, this will be
494 // overwritten in a following cycle
495 if let Entry::Vacant(entry) = self.result.field_resolutions.entry(tgt_expr)
497 entry.insert(field_id);
501 // can't have `write_field_resolution` here because `self.table` is borrowed :(
502 self.result.field_resolutions.insert(tgt_expr, field_id);
503 let ty = self.db.field_types(field_id.parent)[field_id.local_id]
505 .substitute(Interner, ¶meters);
510 let adjustments = auto_deref_adjust_steps(&autoderef);
511 self.write_expr_adj(*expr, adjustments);
512 let ty = self.insert_type_vars(ty);
513 let ty = self.normalize_associated_types_in(ty);
520 Expr::Await { expr } => {
521 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
522 self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
524 Expr::Try { expr } => {
525 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
526 self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
528 Expr::Cast { expr, type_ref } => {
529 // FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
530 let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
531 let cast_ty = self.make_ty(type_ref);
532 // FIXME check the cast...
535 Expr::Ref { expr, rawness, mutability } => {
536 let mutability = lower_to_chalk_mutability(*mutability);
537 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = expected
538 .only_has_type(&mut self.table)
540 .and_then(|t| t.as_reference_or_ptr())
542 if exp_mutability == Mutability::Mut && mutability == Mutability::Not {
543 // FIXME: record type error - expected mut reference but found shared ref,
544 // which cannot be coerced
546 if exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
547 // FIXME: record type error - expected reference but found ptr,
548 // which cannot be coerced
550 Expectation::rvalue_hint(&mut self.table, Ty::clone(exp_inner))
554 let inner_ty = self.infer_expr_inner(*expr, &expectation);
556 Rawness::RawPtr => TyKind::Raw(mutability, inner_ty),
557 Rawness::Ref => TyKind::Ref(mutability, static_lifetime(), inner_ty),
561 Expr::Box { expr } => {
562 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
563 if let Some(box_) = self.resolve_boxed_box() {
564 TyBuilder::adt(self.db, box_)
566 .fill_with_defaults(self.db, || self.table.new_type_var())
572 Expr::UnaryOp { expr, op } => {
573 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
574 let inner_ty = self.resolve_ty_shallow(&inner_ty);
577 autoderef::deref(&mut self.table, inner_ty).unwrap_or_else(|| self.err_ty())
580 match inner_ty.kind(Interner) {
581 // Fast path for builtins
582 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_))
583 | TyKind::InferenceVar(
585 TyVariableKind::Integer | TyVariableKind::Float,
587 // Otherwise we resolve via the std::ops::Neg trait
589 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
593 match inner_ty.kind(Interner) {
594 // Fast path for builtins
595 TyKind::Scalar(Scalar::Bool | Scalar::Int(_) | Scalar::Uint(_))
596 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
597 // Otherwise we resolve via the std::ops::Not trait
599 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
604 Expr::BinaryOp { lhs, rhs, op } => match op {
605 Some(BinaryOp::Assignment { op: None }) => {
606 let lhs_ty = self.infer_expr(*lhs, &Expectation::none());
607 self.infer_expr_coerce(*rhs, &Expectation::has_type(lhs_ty));
608 self.result.standard_types.unit.clone()
610 Some(BinaryOp::LogicOp(_)) => {
611 let bool_ty = self.result.standard_types.bool_.clone();
612 self.infer_expr_coerce(*lhs, &Expectation::HasType(bool_ty.clone()));
613 let lhs_diverges = self.diverges;
614 self.infer_expr_coerce(*rhs, &Expectation::HasType(bool_ty.clone()));
615 // Depending on the LHS' value, the RHS can never execute.
616 self.diverges = lhs_diverges;
619 Some(op) => self.infer_overloadable_binop(*lhs, *op, *rhs, tgt_expr),
622 Expr::Range { lhs, rhs, range_type } => {
623 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
624 let rhs_expect = lhs_ty
626 .map_or_else(Expectation::none, |ty| Expectation::has_type(ty.clone()));
627 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
628 match (range_type, lhs_ty, rhs_ty) {
629 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
630 Some(adt) => TyBuilder::adt(self.db, adt).build(),
631 None => self.err_ty(),
633 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
634 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
635 None => self.err_ty(),
637 (RangeOp::Inclusive, None, Some(ty)) => {
638 match self.resolve_range_to_inclusive() {
639 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
640 None => self.err_ty(),
643 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
644 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
645 None => self.err_ty(),
647 (RangeOp::Inclusive, Some(_), Some(ty)) => {
648 match self.resolve_range_inclusive() {
649 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
650 None => self.err_ty(),
653 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
654 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
655 None => self.err_ty(),
657 (RangeOp::Inclusive, _, None) => self.err_ty(),
660 Expr::Index { base, index } => {
661 let base_ty = self.infer_expr_inner(*base, &Expectation::none());
662 let index_ty = self.infer_expr(*index, &Expectation::none());
664 if let Some(index_trait) = self.resolve_ops_index() {
665 let canonicalized = self.canonicalize(base_ty.clone());
666 let receiver_adjustments = method_resolution::resolve_indexing_op(
668 self.trait_env.clone(),
672 let (self_ty, adj) = receiver_adjustments
673 .map_or((self.err_ty(), Vec::new()), |adj| {
674 adj.apply(&mut self.table, base_ty)
676 self.write_expr_adj(*base, adj);
677 self.resolve_associated_type_with_params(
679 self.resolve_ops_index_output(),
680 &[GenericArgData::Ty(index_ty).intern(Interner)],
686 Expr::Tuple { exprs } => {
687 let mut tys = match expected
688 .only_has_type(&mut self.table)
690 .map(|t| t.kind(Interner))
692 Some(TyKind::Tuple(_, substs)) => substs
694 .map(|a| a.assert_ty_ref(Interner).clone())
695 .chain(repeat_with(|| self.table.new_type_var()))
697 .collect::<Vec<_>>(),
698 _ => (0..exprs.len()).map(|_| self.table.new_type_var()).collect(),
701 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
702 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
705 TyKind::Tuple(tys.len(), Substitution::from_iter(Interner, tys)).intern(Interner)
707 Expr::Array(array) => {
709 match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(Interner)) {
710 Some(TyKind::Array(st, _) | TyKind::Slice(st)) => st.clone(),
711 _ => self.table.new_type_var(),
713 let mut coerce = CoerceMany::new(elem_ty.clone());
715 let expected = Expectation::has_type(elem_ty.clone());
716 let len = match array {
717 Array::ElementList(items) => {
718 for &expr in items.iter() {
719 let cur_elem_ty = self.infer_expr_inner(expr, &expected);
720 coerce.coerce(self, Some(expr), &cur_elem_ty);
722 consteval::usize_const(Some(items.len() as u64))
724 &Array::Repeat { initializer, repeat } => {
725 self.infer_expr_coerce(initializer, &Expectation::has_type(elem_ty));
728 &Expectation::has_type(
729 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(Interner),
733 if let Some(g_def) = self.owner.as_generic_def_id() {
734 let generics = generics(self.db.upcast(), g_def);
735 consteval::eval_to_const(
737 ParamLoweringMode::Placeholder,
740 DebruijnIndex::INNERMOST,
743 consteval::usize_const(None)
748 TyKind::Array(coerce.complete(), len).intern(Interner)
750 Expr::Literal(lit) => match lit {
751 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
752 Literal::String(..) => {
753 TyKind::Ref(Mutability::Not, static_lifetime(), TyKind::Str.intern(Interner))
756 Literal::ByteString(bs) => {
757 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner);
759 let len = consteval::usize_const(Some(bs.len() as u64));
761 let array_type = TyKind::Array(byte_type, len).intern(Interner);
762 TyKind::Ref(Mutability::Not, static_lifetime(), array_type).intern(Interner)
764 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(Interner),
765 Literal::Int(_v, ty) => match ty {
767 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
770 None => self.table.new_integer_var(),
772 Literal::Uint(_v, ty) => match ty {
774 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
777 None => self.table.new_integer_var(),
779 Literal::Float(_v, ty) => match ty {
781 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
784 None => self.table.new_float_var(),
787 Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
789 // use a new type variable if we got unknown here
790 let ty = self.insert_type_vars_shallow(ty);
791 self.write_expr_ty(tgt_expr, ty.clone());
795 fn infer_overloadable_binop(
802 let lhs_expectation = Expectation::none();
803 let lhs_ty = self.infer_expr(lhs, &lhs_expectation);
804 let rhs_ty = self.table.new_type_var();
806 let func = self.resolve_binop_method(op);
807 let func = match func {
810 let rhs_ty = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone());
811 let rhs_ty = self.infer_expr_coerce(rhs, &Expectation::from_option(rhs_ty));
813 .builtin_binary_op_return_ty(op, lhs_ty, rhs_ty)
814 .unwrap_or_else(|| self.err_ty());
818 let subst = TyBuilder::subst_for_def(self.db, func)
819 .push(lhs_ty.clone())
820 .push(rhs_ty.clone())
822 self.write_method_resolution(tgt_expr, func, subst.clone());
824 let method_ty = self.db.value_ty(func.into()).substitute(Interner, &subst);
825 self.register_obligations_for_call(&method_ty);
827 self.infer_expr_coerce(rhs, &Expectation::has_type(rhs_ty.clone()));
829 let ret_ty = match method_ty.callable_sig(self.db) {
830 Some(sig) => sig.ret().clone(),
831 None => self.err_ty(),
834 let ret_ty = self.normalize_associated_types_in(ret_ty);
836 // FIXME: record autoref adjustments
838 // use knowledge of built-in binary ops, which can sometimes help inference
839 if let Some(builtin_rhs) = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone()) {
840 self.unify(&builtin_rhs, &rhs_ty);
842 if let Some(builtin_ret) = self.builtin_binary_op_return_ty(op, lhs_ty, rhs_ty) {
843 self.unify(&builtin_ret, &ret_ty);
852 statements: &[Statement],
853 tail: Option<ExprId>,
854 expected: &Expectation,
856 for stmt in statements {
858 Statement::Let { pat, type_ref, initializer, else_branch } => {
859 let decl_ty = type_ref
861 .map(|tr| self.make_ty(tr))
862 .unwrap_or_else(|| self.err_ty());
864 // Always use the declared type when specified
865 let mut ty = decl_ty.clone();
867 if let Some(expr) = initializer {
869 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
870 if decl_ty.is_unknown() {
875 if let Some(expr) = else_branch {
876 self.infer_expr_coerce(
878 &Expectation::has_type(Ty::new(Interner, TyKind::Never)),
882 self.infer_pat(*pat, &ty, BindingMode::default());
884 Statement::Expr { expr, .. } => {
885 self.infer_expr(*expr, &Expectation::none());
890 if let Some(expr) = tail {
891 self.infer_expr_coerce(expr, expected)
893 // Citing rustc: if there is no explicit tail expression,
894 // that is typically equivalent to a tail expression
895 // of `()` -- except if the block diverges. In that
896 // case, there is no value supplied from the tail
897 // expression (assuming there are no other breaks,
898 // this implies that the type of the block will be
900 if self.diverges.is_always() {
901 // we don't even make an attempt at coercion
902 self.table.new_maybe_never_var()
904 if let Some(t) = expected.only_has_type(&mut self.table) {
905 let _ = self.coerce(Some(expr), &TyBuilder::unit(), &t);
912 fn infer_method_call(
918 generic_args: Option<&GenericArgs>,
919 expected: &Expectation,
921 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
922 let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
924 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
926 let resolved = method_resolution::lookup_method(
927 &canonicalized_receiver.value,
929 self.trait_env.clone(),
931 self.resolver.module().into(),
934 let (receiver_ty, method_ty, substs) = match resolved {
935 Some((adjust, func)) => {
936 let (ty, adjustments) = adjust.apply(&mut self.table, receiver_ty);
937 let generics = generics(self.db.upcast(), func.into());
938 let substs = self.substs_for_method_call(generics, generic_args);
939 self.write_expr_adj(receiver, adjustments);
940 self.write_method_resolution(tgt_expr, func, substs.clone());
941 (ty, self.db.value_ty(func.into()), substs)
945 Binders::empty(Interner, self.err_ty()),
946 Substitution::empty(Interner),
949 let method_ty = method_ty.substitute(Interner, &substs);
950 self.register_obligations_for_call(&method_ty);
951 let (formal_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
953 if !sig.params().is_empty() {
954 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
956 (self.err_ty(), Vec::new(), sig.ret().clone())
959 None => (self.err_ty(), Vec::new(), self.err_ty()),
961 self.unify(&formal_receiver_ty, &receiver_ty);
963 let expected_inputs =
964 self.expected_inputs_for_expected_output(expected, ret_ty.clone(), param_tys.clone());
966 self.check_call_arguments(args, &expected_inputs, ¶m_tys, &[]);
967 self.normalize_associated_types_in(ret_ty)
970 fn expected_inputs_for_expected_output(
972 expected_output: &Expectation,
976 if let Some(expected_ty) = expected_output.to_option(&mut self.table) {
977 self.table.fudge_inference(|table| {
978 if table.try_unify(&expected_ty, &output).is_ok() {
979 table.resolve_with_fallback(inputs, &|var, kind, _, _| match kind {
980 chalk_ir::VariableKind::Ty(tk) => var.to_ty(Interner, tk).cast(Interner),
981 chalk_ir::VariableKind::Lifetime => {
982 var.to_lifetime(Interner).cast(Interner)
984 chalk_ir::VariableKind::Const(ty) => {
985 var.to_const(Interner, ty).cast(Interner)
997 fn check_call_arguments(
1000 expected_inputs: &[Ty],
1002 skip_indices: &[u32],
1004 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
1005 // We do this in a pretty awful way: first we type-check any arguments
1006 // that are not closures, then we type-check the closures. This is so
1007 // that we have more information about the types of arguments when we
1008 // type-check the functions. This isn't really the right way to do this.
1009 for &check_closures in &[false, true] {
1010 let mut skip_indices = skip_indices.into_iter().copied().fuse().peekable();
1011 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
1012 let expected_iter = expected_inputs
1015 .chain(param_iter.clone().skip(expected_inputs.len()));
1016 for (idx, ((&arg, param_ty), expected_ty)) in
1017 args.iter().zip(param_iter).zip(expected_iter).enumerate()
1019 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
1020 if is_closure != check_closures {
1024 while skip_indices.peek().map_or(false, |i| *i < idx as u32) {
1025 skip_indices.next();
1027 if skip_indices.peek().copied() == Some(idx as u32) {
1031 // the difference between param_ty and expected here is that
1032 // expected is the parameter when the expected *return* type is
1033 // taken into account. So in `let _: &[i32] = identity(&[1, 2])`
1034 // the expected type is already `&[i32]`, whereas param_ty is
1035 // still an unbound type variable. We don't always want to force
1036 // the parameter to coerce to the expected type (for example in
1037 // `coerce_unsize_expected_type_4`).
1038 let param_ty = self.normalize_associated_types_in(param_ty);
1039 let expected = Expectation::rvalue_hint(&mut self.table, expected_ty);
1040 // infer with the expected type we have...
1041 let ty = self.infer_expr_inner(arg, &expected);
1043 // then coerce to either the expected type or just the formal parameter type
1044 let coercion_target = if let Some(ty) = expected.only_has_type(&mut self.table) {
1045 // if we are coercing to the expectation, unify with the
1046 // formal parameter type to connect everything
1047 self.unify(&ty, ¶m_ty);
1052 if !coercion_target.is_unknown() {
1053 if self.coerce(Some(arg), &ty, &coercion_target).is_err() {
1054 self.result.type_mismatches.insert(
1056 TypeMismatch { expected: coercion_target, actual: ty.clone() },
1064 fn substs_for_method_call(
1066 def_generics: Generics,
1067 generic_args: Option<&GenericArgs>,
1069 let (parent_params, self_params, type_params, const_params, impl_trait_params) =
1070 def_generics.provenance_split();
1071 assert_eq!(self_params, 0); // method shouldn't have another Self param
1072 let total_len = parent_params + type_params + const_params + impl_trait_params;
1073 let mut substs = Vec::with_capacity(total_len);
1074 // Parent arguments are unknown
1075 for (id, param) in def_generics.iter_parent() {
1077 TypeOrConstParamData::TypeParamData(_) => {
1078 substs.push(GenericArgData::Ty(self.table.new_type_var()).intern(Interner));
1080 TypeOrConstParamData::ConstParamData(_) => {
1081 let ty = self.db.const_param_ty(ConstParamId::from_unchecked(id));
1083 .push(GenericArgData::Const(self.table.new_const_var(ty)).intern(Interner));
1087 // handle provided arguments
1088 if let Some(generic_args) = generic_args {
1089 // if args are provided, it should be all of them, but we can't rely on that
1090 for (arg, kind_id) in generic_args
1093 .filter(|arg| !matches!(arg, GenericArg::Lifetime(_)))
1094 .take(type_params + const_params)
1095 .zip(def_generics.iter_id().skip(parent_params))
1097 if let Some(g) = generic_arg_to_chalk(
1102 |this, type_ref| this.make_ty(type_ref),
1104 const_or_path_to_chalk(
1108 ParamLoweringMode::Placeholder,
1109 || generics(this.db.upcast(), (&this.resolver).generic_def().unwrap()),
1110 DebruijnIndex::INNERMOST,
1118 for (id, data) in def_generics.iter().skip(substs.len()) {
1120 TypeOrConstParamData::TypeParamData(_) => {
1121 substs.push(GenericArgData::Ty(self.table.new_type_var()).intern(Interner))
1123 TypeOrConstParamData::ConstParamData(_) => {
1125 GenericArgData::Const(self.table.new_const_var(
1126 self.db.const_param_ty(ConstParamId::from_unchecked(id)),
1133 assert_eq!(substs.len(), total_len);
1134 Substitution::from_iter(Interner, substs)
1137 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
1138 let callable_ty = self.resolve_ty_shallow(callable_ty);
1139 if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(Interner) {
1140 let def: CallableDefId = from_chalk(self.db, *fn_def);
1141 let generic_predicates = self.db.generic_predicates(def.into());
1142 for predicate in generic_predicates.iter() {
1143 let (predicate, binders) = predicate
1145 .substitute(Interner, parameters)
1146 .into_value_and_skipped_binders();
1147 always!(binders.len(Interner) == 0); // quantified where clauses not yet handled
1148 self.push_obligation(predicate.cast(Interner));
1150 // add obligation for trait implementation, if this is a trait method
1152 CallableDefId::FunctionId(f) => {
1153 if let ItemContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container {
1154 // construct a TraitRef
1155 let substs = crate::subst_prefix(
1157 generics(self.db.upcast(), trait_.into()).len(),
1159 self.push_obligation(
1160 TraitRef { trait_id: to_chalk_trait_id(trait_), substitution: substs }
1165 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}
1170 /// Returns the argument indices to skip.
1171 fn check_legacy_const_generics(&mut self, callee: Ty, args: &[ExprId]) -> Vec<u32> {
1172 let (func, subst) = match callee.kind(Interner) {
1173 TyKind::FnDef(fn_id, subst) => {
1174 let callable = CallableDefId::from_chalk(self.db, *fn_id);
1175 let func = match callable {
1176 CallableDefId::FunctionId(f) => f,
1177 _ => return Vec::new(),
1181 _ => return Vec::new(),
1184 let data = self.db.function_data(func);
1185 if data.legacy_const_generics_indices.is_empty() {
1189 // only use legacy const generics if the param count matches with them
1190 if data.params.len() + data.legacy_const_generics_indices.len() != args.len() {
1194 // check legacy const parameters
1195 for (subst_idx, arg_idx) in data.legacy_const_generics_indices.iter().copied().enumerate() {
1196 let arg = match subst.at(Interner, subst_idx).constant(Interner) {
1198 None => continue, // not a const parameter?
1200 if arg_idx >= args.len() as u32 {
1203 let _ty = arg.data(Interner).ty.clone();
1204 let expected = Expectation::none(); // FIXME use actual const ty, when that is lowered correctly
1205 self.infer_expr(args[arg_idx as usize], &expected);
1206 // FIXME: evaluate and unify with the const
1208 let mut indices = data.legacy_const_generics_indices.clone();
1213 fn builtin_binary_op_return_ty(&mut self, op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Option<Ty> {
1214 let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
1215 let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
1217 BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => {
1218 Some(TyKind::Scalar(Scalar::Bool).intern(Interner))
1220 BinaryOp::Assignment { .. } => Some(TyBuilder::unit()),
1221 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => {
1222 // all integer combinations are valid here
1224 lhs_ty.kind(Interner),
1225 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1226 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1228 rhs_ty.kind(Interner),
1229 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1230 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1237 BinaryOp::ArithOp(_) => match (lhs_ty.kind(Interner), rhs_ty.kind(Interner)) {
1238 // (int, int) | (uint, uint) | (float, float)
1239 (TyKind::Scalar(Scalar::Int(_)), TyKind::Scalar(Scalar::Int(_)))
1240 | (TyKind::Scalar(Scalar::Uint(_)), TyKind::Scalar(Scalar::Uint(_)))
1241 | (TyKind::Scalar(Scalar::Float(_)), TyKind::Scalar(Scalar::Float(_))) => {
1244 // ({int}, int) | ({int}, uint)
1246 TyKind::InferenceVar(_, TyVariableKind::Integer),
1247 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1249 // (int, {int}) | (uint, {int})
1251 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1252 TyKind::InferenceVar(_, TyVariableKind::Integer),
1254 // ({float} | float)
1256 TyKind::InferenceVar(_, TyVariableKind::Float),
1257 TyKind::Scalar(Scalar::Float(_)),
1261 TyKind::Scalar(Scalar::Float(_)),
1262 TyKind::InferenceVar(_, TyVariableKind::Float),
1264 // ({int}, {int}) | ({float}, {float})
1266 TyKind::InferenceVar(_, TyVariableKind::Integer),
1267 TyKind::InferenceVar(_, TyVariableKind::Integer),
1270 TyKind::InferenceVar(_, TyVariableKind::Float),
1271 TyKind::InferenceVar(_, TyVariableKind::Float),
1278 fn builtin_binary_op_rhs_expectation(&mut self, op: BinaryOp, lhs_ty: Ty) -> Option<Ty> {
1280 BinaryOp::LogicOp(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
1281 BinaryOp::Assignment { op: None } => lhs_ty,
1282 BinaryOp::CmpOp(CmpOp::Eq { .. }) => match self
1283 .resolve_ty_shallow(&lhs_ty)
1286 TyKind::Scalar(_) | TyKind::Str => lhs_ty,
1287 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1290 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => return None,
1291 BinaryOp::CmpOp(CmpOp::Ord { .. })
1292 | BinaryOp::Assignment { op: Some(_) }
1293 | BinaryOp::ArithOp(_) => match self.resolve_ty_shallow(&lhs_ty).kind(Interner) {
1294 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_)) => lhs_ty,
1295 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1301 fn resolve_binop_method(&self, op: BinaryOp) -> Option<FunctionId> {
1302 let (name, lang_item) = match op {
1303 BinaryOp::LogicOp(_) => return None,
1304 BinaryOp::ArithOp(aop) => match aop {
1305 ArithOp::Add => (name!(add), name!(add)),
1306 ArithOp::Mul => (name!(mul), name!(mul)),
1307 ArithOp::Sub => (name!(sub), name!(sub)),
1308 ArithOp::Div => (name!(div), name!(div)),
1309 ArithOp::Rem => (name!(rem), name!(rem)),
1310 ArithOp::Shl => (name!(shl), name!(shl)),
1311 ArithOp::Shr => (name!(shr), name!(shr)),
1312 ArithOp::BitXor => (name!(bitxor), name!(bitxor)),
1313 ArithOp::BitOr => (name!(bitor), name!(bitor)),
1314 ArithOp::BitAnd => (name!(bitand), name!(bitand)),
1316 BinaryOp::Assignment { op: Some(aop) } => match aop {
1317 ArithOp::Add => (name!(add_assign), name!(add_assign)),
1318 ArithOp::Mul => (name!(mul_assign), name!(mul_assign)),
1319 ArithOp::Sub => (name!(sub_assign), name!(sub_assign)),
1320 ArithOp::Div => (name!(div_assign), name!(div_assign)),
1321 ArithOp::Rem => (name!(rem_assign), name!(rem_assign)),
1322 ArithOp::Shl => (name!(shl_assign), name!(shl_assign)),
1323 ArithOp::Shr => (name!(shr_assign), name!(shr_assign)),
1324 ArithOp::BitXor => (name!(bitxor_assign), name!(bitxor_assign)),
1325 ArithOp::BitOr => (name!(bitor_assign), name!(bitor_assign)),
1326 ArithOp::BitAnd => (name!(bitand_assign), name!(bitand_assign)),
1328 BinaryOp::CmpOp(cop) => match cop {
1329 CmpOp::Eq { negated: false } => (name!(eq), name!(eq)),
1330 CmpOp::Eq { negated: true } => (name!(ne), name!(eq)),
1331 CmpOp::Ord { ordering: Ordering::Less, strict: false } => {
1332 (name!(le), name!(partial_ord))
1334 CmpOp::Ord { ordering: Ordering::Less, strict: true } => {
1335 (name!(lt), name!(partial_ord))
1337 CmpOp::Ord { ordering: Ordering::Greater, strict: false } => {
1338 (name!(ge), name!(partial_ord))
1340 CmpOp::Ord { ordering: Ordering::Greater, strict: true } => {
1341 (name!(gt), name!(partial_ord))
1344 BinaryOp::Assignment { op: None } => return None,
1347 let trait_ = self.resolve_lang_item(lang_item)?.as_trait()?;
1349 self.db.trait_data(trait_).method_by_name(&name)