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 generics::TypeOrConstParamData,
14 path::{GenericArg, GenericArgs},
15 resolver::resolver_for_expr,
16 FieldId, FunctionId, ItemContainerId, Lookup,
18 use hir_expand::name::{name, Name};
20 use syntax::ast::RangeOp;
23 autoderef::{self, Autoderef},
25 infer::coerce::CoerceMany,
26 lower::lower_to_chalk_mutability,
29 primitive::{self, UintTy},
30 static_lifetime, to_chalk_trait_id,
31 utils::{generics, Generics},
32 AdtId, Binders, CallableDefId, FnPointer, FnSig, FnSubst, Interner, Rawness, Scalar,
33 Substitution, TraitRef, Ty, TyBuilder, TyExt, TyKind,
37 coerce::auto_deref_adjust_steps, find_breakable, BindingMode, BreakableContext, Diverges,
38 Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch,
41 impl<'a> InferenceContext<'a> {
42 pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
43 let ty = self.infer_expr_inner(tgt_expr, expected);
44 if self.resolve_ty_shallow(&ty).is_never() {
45 // Any expression that produces a value of type `!` must have diverged
46 self.diverges = Diverges::Always;
48 if let Some(expected_ty) = expected.only_has_type(&mut self.table) {
49 let could_unify = self.unify(&ty, &expected_ty);
51 self.result.type_mismatches.insert(
53 TypeMismatch { expected: expected_ty, actual: ty.clone() },
60 /// Infer type of expression with possibly implicit coerce to the expected type.
61 /// Return the type after possible coercion.
62 pub(super) fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty {
63 let ty = self.infer_expr_inner(expr, expected);
64 if let Some(target) = expected.only_has_type(&mut self.table) {
65 match self.coerce(Some(expr), &ty, &target) {
70 .insert(expr.into(), TypeMismatch { expected: target, actual: ty.clone() });
71 // Return actual type when type mismatch.
72 // This is needed for diagnostic when return type mismatch.
81 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
82 self.db.unwind_if_cancelled();
84 let body = Arc::clone(&self.body); // avoid borrow checker problem
85 let ty = match &body[tgt_expr] {
86 Expr::Missing => self.err_ty(),
87 &Expr::If { condition, then_branch, else_branch } => {
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()),
189 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
191 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
192 let _ctxt = self.breakables.pop().expect("breakable stack broken");
193 // the body may not run, so it diverging doesn't mean we diverge
194 self.diverges = Diverges::Maybe;
197 Expr::For { iterable, body, pat, label } => {
198 let iterable_ty = self.infer_expr(*iterable, &Expectation::none());
200 self.breakables.push(BreakableContext {
202 coerce: CoerceMany::new(self.err_ty()),
203 label: label.map(|label| self.body[label].name.clone()),
206 self.resolve_associated_type(iterable_ty, self.resolve_into_iter_item());
208 self.infer_pat(*pat, &pat_ty, BindingMode::default());
210 self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
211 let _ctxt = self.breakables.pop().expect("breakable stack broken");
212 // the body may not run, so it diverging doesn't mean we diverge
213 self.diverges = Diverges::Maybe;
216 Expr::Lambda { body, args, ret_type, arg_types } => {
217 assert_eq!(args.len(), arg_types.len());
219 let mut sig_tys = Vec::new();
221 // collect explicitly written argument types
222 for arg_type in arg_types.iter() {
223 let arg_ty = match arg_type {
224 Some(type_ref) => self.make_ty(type_ref),
225 None => self.table.new_type_var(),
227 sig_tys.push(arg_ty);
231 let ret_ty = match ret_type {
232 Some(type_ref) => self.make_ty(type_ref),
233 None => self.table.new_type_var(),
235 sig_tys.push(ret_ty.clone());
236 let sig_ty = TyKind::Function(FnPointer {
238 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
239 substitution: FnSubst(
240 Substitution::from_iter(Interner, sig_tys.clone()).shifted_in(Interner),
244 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
246 TyKind::Closure(closure_id, Substitution::from1(Interner, sig_ty.clone()))
249 // Eagerly try to relate the closure type with the expected
250 // type, otherwise we often won't have enough information to
252 self.deduce_closure_type_from_expectations(
259 // Now go through the argument patterns
260 for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
261 self.infer_pat(*arg_pat, &arg_ty, BindingMode::default());
264 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
265 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
267 self.infer_expr_coerce(*body, &Expectation::has_type(ret_ty));
269 self.diverges = prev_diverges;
270 self.return_ty = prev_ret_ty;
274 Expr::Call { callee, args } => {
275 let callee_ty = self.infer_expr(*callee, &Expectation::none());
276 let mut derefs = Autoderef::new(&mut self.table, callee_ty.clone());
278 // manual loop to be able to access `derefs.table`
279 while let Some((callee_deref_ty, _)) = derefs.next() {
280 res = derefs.table.callable_sig(&callee_deref_ty, args.len());
285 let (param_tys, ret_ty): (Vec<Ty>, Ty) = match res {
287 let adjustments = auto_deref_adjust_steps(&derefs);
288 self.write_expr_adj(*callee, adjustments);
291 None => (Vec::new(), self.err_ty()),
293 self.register_obligations_for_call(&callee_ty);
295 let expected_inputs = self.expected_inputs_for_expected_output(
301 self.check_call_arguments(args, &expected_inputs, ¶m_tys);
302 self.normalize_associated_types_in(ret_ty)
304 Expr::MethodCall { receiver, args, method_name, generic_args } => self
310 generic_args.as_deref(),
313 Expr::Match { expr, arms } => {
314 let input_ty = self.infer_expr(*expr, &Expectation::none());
316 let expected = expected.adjust_for_branches(&mut self.table);
318 let result_ty = if arms.is_empty() {
319 TyKind::Never.intern(Interner)
322 Expectation::HasType(ty) => ty.clone(),
323 _ => self.table.new_type_var(),
326 let mut coerce = CoerceMany::new(result_ty);
328 let matchee_diverges = self.diverges;
329 let mut all_arms_diverge = Diverges::Always;
331 for arm in arms.iter() {
332 self.diverges = Diverges::Maybe;
333 let _pat_ty = self.infer_pat(arm.pat, &input_ty, BindingMode::default());
334 if let Some(guard_expr) = arm.guard {
337 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(Interner)),
341 let arm_ty = self.infer_expr_inner(arm.expr, &expected);
342 all_arms_diverge &= self.diverges;
343 coerce.coerce(self, Some(arm.expr), &arm_ty);
346 self.diverges = matchee_diverges | all_arms_diverge;
351 // FIXME this could be more efficient...
352 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
353 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or_else(|| self.err_ty())
355 Expr::Continue { .. } => TyKind::Never.intern(Interner),
356 Expr::Break { expr, label } => {
357 let mut coerce = match find_breakable(&mut self.breakables, label.as_ref()) {
359 // avoiding the borrowck
362 CoerceMany::new(self.result.standard_types.unknown.clone()),
365 None => CoerceMany::new(self.result.standard_types.unknown.clone()),
368 let val_ty = if let Some(expr) = *expr {
369 self.infer_expr(expr, &Expectation::none())
374 // FIXME: create a synthetic `()` during lowering so we have something to refer to here?
375 coerce.coerce(self, *expr, &val_ty);
377 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
378 ctxt.coerce = coerce;
379 ctxt.may_break = true;
381 self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop {
386 TyKind::Never.intern(Interner)
388 Expr::Return { expr } => {
389 if let Some(expr) = expr {
390 self.infer_expr_coerce(*expr, &Expectation::has_type(self.return_ty.clone()));
392 let unit = TyBuilder::unit();
393 let _ = self.coerce(Some(tgt_expr), &unit, &self.return_ty.clone());
395 TyKind::Never.intern(Interner)
397 Expr::Yield { expr } => {
398 // FIXME: track yield type for coercion
399 if let Some(expr) = expr {
400 self.infer_expr(*expr, &Expectation::none());
402 TyKind::Never.intern(Interner)
404 Expr::RecordLit { path, fields, spread } => {
405 let (ty, def_id) = self.resolve_variant(path.as_deref(), false);
406 if let Some(variant) = def_id {
407 self.write_variant_resolution(tgt_expr.into(), variant);
410 if let Some(t) = expected.only_has_type(&mut self.table) {
416 .map(|(_, s)| s.clone())
417 .unwrap_or_else(|| Substitution::empty(Interner));
418 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
419 let variant_data = def_id.map(|it| it.variant_data(self.db.upcast()));
420 for field in fields.iter() {
422 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
423 Some(local_id) => Some(FieldId { parent: def_id.unwrap(), local_id }),
425 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
431 let field_ty = field_def.map_or(self.err_ty(), |it| {
432 field_types[it.local_id].clone().substitute(Interner, &substs)
434 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
436 if let Some(expr) = spread {
437 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
441 Expr::Field { expr, name } => {
442 let receiver_ty = self.infer_expr_inner(*expr, &Expectation::none());
444 let mut autoderef = Autoderef::new(&mut self.table, receiver_ty);
445 let ty = autoderef.by_ref().find_map(|(derefed_ty, _)| {
446 let (field_id, parameters) = match derefed_ty.kind(Interner) {
447 TyKind::Tuple(_, substs) => {
448 return name.as_tuple_index().and_then(|idx| {
452 .map(|a| a.assert_ty_ref(Interner))
456 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
457 let local_id = self.db.struct_data(*s).variant_data.field(name)?;
458 let field = FieldId { parent: (*s).into(), local_id };
459 (field, parameters.clone())
461 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
462 let local_id = self.db.union_data(*u).variant_data.field(name)?;
463 let field = FieldId { parent: (*u).into(), local_id };
464 (field, parameters.clone())
468 let module = self.resolver.module();
469 let is_visible = module
471 self.db.field_visibilities(field_id.parent)[field_id.local_id]
472 .is_visible_from(self.db.upcast(), mod_id)
476 // Write down the first field resolution even if it is not visible
477 // This aids IDE features for private fields like goto def and in
478 // case of autoderef finding an applicable field, this will be
479 // overwritten in a following cycle
480 if let Entry::Vacant(entry) = self.result.field_resolutions.entry(tgt_expr)
482 entry.insert(field_id);
486 // can't have `write_field_resolution` here because `self.table` is borrowed :(
487 self.result.field_resolutions.insert(tgt_expr, field_id);
488 let ty = self.db.field_types(field_id.parent)[field_id.local_id]
490 .substitute(Interner, ¶meters);
495 let adjustments = auto_deref_adjust_steps(&autoderef);
496 self.write_expr_adj(*expr, adjustments);
497 let ty = self.insert_type_vars(ty);
498 let ty = self.normalize_associated_types_in(ty);
505 Expr::Await { expr } => {
506 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
507 self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
509 Expr::Try { expr } => {
510 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
511 self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
513 Expr::Cast { expr, type_ref } => {
514 // FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
515 let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
516 let cast_ty = self.make_ty(type_ref);
517 // FIXME check the cast...
520 Expr::Ref { expr, rawness, mutability } => {
521 let mutability = lower_to_chalk_mutability(*mutability);
522 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = expected
523 .only_has_type(&mut self.table)
525 .and_then(|t| t.as_reference_or_ptr())
527 if exp_mutability == Mutability::Mut && mutability == Mutability::Not {
528 // FIXME: record type error - expected mut reference but found shared ref,
529 // which cannot be coerced
531 if exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
532 // FIXME: record type error - expected reference but found ptr,
533 // which cannot be coerced
535 Expectation::rvalue_hint(&mut self.table, Ty::clone(exp_inner))
539 let inner_ty = self.infer_expr_inner(*expr, &expectation);
541 Rawness::RawPtr => TyKind::Raw(mutability, inner_ty),
542 Rawness::Ref => TyKind::Ref(mutability, static_lifetime(), inner_ty),
546 Expr::Box { expr } => {
547 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
548 if let Some(box_) = self.resolve_boxed_box() {
549 TyBuilder::adt(self.db, box_)
551 .fill_with_defaults(self.db, || self.table.new_type_var())
557 Expr::UnaryOp { expr, op } => {
558 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
559 let inner_ty = self.resolve_ty_shallow(&inner_ty);
562 autoderef::deref(&mut self.table, inner_ty).unwrap_or_else(|| self.err_ty())
565 match inner_ty.kind(Interner) {
566 // Fast path for builtins
567 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_))
568 | TyKind::InferenceVar(
570 TyVariableKind::Integer | TyVariableKind::Float,
572 // Otherwise we resolve via the std::ops::Neg trait
574 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
578 match inner_ty.kind(Interner) {
579 // Fast path for builtins
580 TyKind::Scalar(Scalar::Bool | Scalar::Int(_) | Scalar::Uint(_))
581 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
582 // Otherwise we resolve via the std::ops::Not trait
584 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
589 Expr::BinaryOp { lhs, rhs, op } => match op {
590 Some(BinaryOp::Assignment { op: None }) => {
591 let lhs_ty = self.infer_expr(*lhs, &Expectation::none());
592 self.infer_expr_coerce(*rhs, &Expectation::has_type(lhs_ty));
593 self.result.standard_types.unit.clone()
595 Some(BinaryOp::LogicOp(_)) => {
596 let bool_ty = self.result.standard_types.bool_.clone();
597 self.infer_expr_coerce(*lhs, &Expectation::HasType(bool_ty.clone()));
598 let lhs_diverges = self.diverges;
599 self.infer_expr_coerce(*rhs, &Expectation::HasType(bool_ty.clone()));
600 // Depending on the LHS' value, the RHS can never execute.
601 self.diverges = lhs_diverges;
604 Some(op) => self.infer_overloadable_binop(*lhs, *op, *rhs, tgt_expr),
607 Expr::Range { lhs, rhs, range_type } => {
608 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
609 let rhs_expect = lhs_ty
611 .map_or_else(Expectation::none, |ty| Expectation::has_type(ty.clone()));
612 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
613 match (range_type, lhs_ty, rhs_ty) {
614 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
615 Some(adt) => TyBuilder::adt(self.db, adt).build(),
616 None => self.err_ty(),
618 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
619 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
620 None => self.err_ty(),
622 (RangeOp::Inclusive, None, Some(ty)) => {
623 match self.resolve_range_to_inclusive() {
624 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
625 None => self.err_ty(),
628 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
629 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
630 None => self.err_ty(),
632 (RangeOp::Inclusive, Some(_), Some(ty)) => {
633 match self.resolve_range_inclusive() {
634 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
635 None => self.err_ty(),
638 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
639 Some(adt) => TyBuilder::adt(self.db, adt).push(ty).build(),
640 None => self.err_ty(),
642 (RangeOp::Inclusive, _, None) => self.err_ty(),
645 Expr::Index { base, index } => {
646 let base_ty = self.infer_expr_inner(*base, &Expectation::none());
647 let index_ty = self.infer_expr(*index, &Expectation::none());
649 if let Some(index_trait) = self.resolve_ops_index() {
650 let canonicalized = self.canonicalize(base_ty.clone());
651 let receiver_adjustments = method_resolution::resolve_indexing_op(
653 self.trait_env.clone(),
657 let (self_ty, adj) = receiver_adjustments
658 .map_or((self.err_ty(), Vec::new()), |adj| {
659 adj.apply(&mut self.table, base_ty)
661 self.write_expr_adj(*base, adj);
662 self.resolve_associated_type_with_params(
664 self.resolve_ops_index_output(),
671 Expr::Tuple { exprs } => {
672 let mut tys = match expected
673 .only_has_type(&mut self.table)
675 .map(|t| t.kind(Interner))
677 Some(TyKind::Tuple(_, substs)) => substs
679 .map(|a| a.assert_ty_ref(Interner).clone())
680 .chain(repeat_with(|| self.table.new_type_var()))
682 .collect::<Vec<_>>(),
683 _ => (0..exprs.len()).map(|_| self.table.new_type_var()).collect(),
686 for (expr, ty) in exprs.iter().zip(tys.iter_mut()) {
687 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
690 TyKind::Tuple(tys.len(), Substitution::from_iter(Interner, tys)).intern(Interner)
692 Expr::Array(array) => {
694 match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(Interner)) {
695 Some(TyKind::Array(st, _) | TyKind::Slice(st)) => st.clone(),
696 _ => self.table.new_type_var(),
698 let mut coerce = CoerceMany::new(elem_ty.clone());
700 let expected = Expectation::has_type(elem_ty.clone());
701 let len = match array {
702 Array::ElementList(items) => {
703 for &expr in items.iter() {
704 let cur_elem_ty = self.infer_expr_inner(expr, &expected);
705 coerce.coerce(self, Some(expr), &cur_elem_ty);
707 Some(items.len() as u64)
709 &Array::Repeat { initializer, repeat } => {
710 self.infer_expr_coerce(initializer, &Expectation::has_type(elem_ty));
713 &Expectation::has_type(
714 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(Interner),
718 consteval::eval_usize(
720 consteval::ConstEvalCtx {
723 local_data: Default::default(),
724 infer: &mut |x| self.infer_expr(x, &expected),
730 TyKind::Array(coerce.complete(), consteval::usize_const(len)).intern(Interner)
732 Expr::Literal(lit) => match lit {
733 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
734 Literal::String(..) => {
735 TyKind::Ref(Mutability::Not, static_lifetime(), TyKind::Str.intern(Interner))
738 Literal::ByteString(bs) => {
739 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner);
741 let len = consteval::usize_const(Some(bs.len() as u64));
743 let array_type = TyKind::Array(byte_type, len).intern(Interner);
744 TyKind::Ref(Mutability::Not, static_lifetime(), array_type).intern(Interner)
746 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(Interner),
747 Literal::Int(_v, ty) => match ty {
749 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
752 None => self.table.new_integer_var(),
754 Literal::Uint(_v, ty) => match ty {
756 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
759 None => self.table.new_integer_var(),
761 Literal::Float(_v, ty) => match ty {
763 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
766 None => self.table.new_float_var(),
769 Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
771 // use a new type variable if we got unknown here
772 let ty = self.insert_type_vars_shallow(ty);
773 self.write_expr_ty(tgt_expr, ty.clone());
777 fn infer_overloadable_binop(
784 let lhs_expectation = Expectation::none();
785 let lhs_ty = self.infer_expr(lhs, &lhs_expectation);
786 let rhs_ty = self.table.new_type_var();
788 let func = self.resolve_binop_method(op);
789 let func = match func {
792 let rhs_ty = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone());
793 let rhs_ty = self.infer_expr_coerce(rhs, &Expectation::from_option(rhs_ty));
795 .builtin_binary_op_return_ty(op, lhs_ty, rhs_ty)
796 .unwrap_or_else(|| self.err_ty());
800 let subst = TyBuilder::subst_for_def(self.db, func)
801 .push(lhs_ty.clone())
802 .push(rhs_ty.clone())
804 self.write_method_resolution(tgt_expr, func, subst.clone());
806 let method_ty = self.db.value_ty(func.into()).substitute(Interner, &subst);
807 self.register_obligations_for_call(&method_ty);
809 self.infer_expr_coerce(rhs, &Expectation::has_type(rhs_ty.clone()));
811 let ret_ty = match method_ty.callable_sig(self.db) {
812 Some(sig) => sig.ret().clone(),
813 None => self.err_ty(),
816 let ret_ty = self.normalize_associated_types_in(ret_ty);
818 // FIXME: record autoref adjustments
820 // use knowledge of built-in binary ops, which can sometimes help inference
821 if let Some(builtin_rhs) = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone()) {
822 self.unify(&builtin_rhs, &rhs_ty);
824 if let Some(builtin_ret) = self.builtin_binary_op_return_ty(op, lhs_ty, rhs_ty) {
825 self.unify(&builtin_ret, &ret_ty);
834 statements: &[Statement],
835 tail: Option<ExprId>,
836 expected: &Expectation,
838 for stmt in statements {
840 Statement::Let { pat, type_ref, initializer, else_branch } => {
841 let decl_ty = type_ref
843 .map(|tr| self.make_ty(tr))
844 .unwrap_or_else(|| self.err_ty());
846 // Always use the declared type when specified
847 let mut ty = decl_ty.clone();
849 if let Some(expr) = initializer {
851 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
852 if decl_ty.is_unknown() {
857 if let Some(expr) = else_branch {
858 self.infer_expr_coerce(
860 &Expectation::has_type(Ty::new(Interner, TyKind::Never)),
864 self.infer_pat(*pat, &ty, BindingMode::default());
866 Statement::Expr { expr, .. } => {
867 self.infer_expr(*expr, &Expectation::none());
872 if let Some(expr) = tail {
873 self.infer_expr_coerce(expr, expected)
875 // Citing rustc: if there is no explicit tail expression,
876 // that is typically equivalent to a tail expression
877 // of `()` -- except if the block diverges. In that
878 // case, there is no value supplied from the tail
879 // expression (assuming there are no other breaks,
880 // this implies that the type of the block will be
882 if self.diverges.is_always() {
883 // we don't even make an attempt at coercion
884 self.table.new_maybe_never_var()
886 if let Some(t) = expected.only_has_type(&mut self.table) {
887 let _ = self.coerce(Some(expr), &TyBuilder::unit(), &t);
894 fn infer_method_call(
900 generic_args: Option<&GenericArgs>,
901 expected: &Expectation,
903 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
904 let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
906 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
908 let resolved = method_resolution::lookup_method(
909 &canonicalized_receiver.value,
911 self.trait_env.clone(),
913 self.resolver.module().into(),
916 let (receiver_ty, method_ty, substs) = match resolved {
917 Some((adjust, func)) => {
918 let (ty, adjustments) = adjust.apply(&mut self.table, receiver_ty);
919 let generics = generics(self.db.upcast(), func.into());
920 let substs = self.substs_for_method_call(generics, generic_args);
921 self.write_expr_adj(receiver, adjustments);
922 self.write_method_resolution(tgt_expr, func, substs.clone());
923 (ty, self.db.value_ty(func.into()), substs)
927 Binders::empty(Interner, self.err_ty()),
928 Substitution::empty(Interner),
931 let method_ty = method_ty.substitute(Interner, &substs);
932 self.register_obligations_for_call(&method_ty);
933 let (formal_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
935 if !sig.params().is_empty() {
936 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
938 (self.err_ty(), Vec::new(), sig.ret().clone())
941 None => (self.err_ty(), Vec::new(), self.err_ty()),
943 self.unify(&formal_receiver_ty, &receiver_ty);
945 let expected_inputs =
946 self.expected_inputs_for_expected_output(expected, ret_ty.clone(), param_tys.clone());
948 self.check_call_arguments(args, &expected_inputs, ¶m_tys);
949 self.normalize_associated_types_in(ret_ty)
952 fn expected_inputs_for_expected_output(
954 expected_output: &Expectation,
958 if let Some(expected_ty) = expected_output.to_option(&mut self.table) {
959 self.table.fudge_inference(|table| {
960 if table.try_unify(&expected_ty, &output).is_ok() {
961 table.resolve_with_fallback(inputs, &|var, kind, _, _| match kind {
962 chalk_ir::VariableKind::Ty(tk) => var.to_ty(Interner, tk).cast(Interner),
963 chalk_ir::VariableKind::Lifetime => {
964 var.to_lifetime(Interner).cast(Interner)
966 chalk_ir::VariableKind::Const(ty) => {
967 var.to_const(Interner, ty).cast(Interner)
979 fn check_call_arguments(&mut self, args: &[ExprId], expected_inputs: &[Ty], param_tys: &[Ty]) {
980 // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
981 // We do this in a pretty awful way: first we type-check any arguments
982 // that are not closures, then we type-check the closures. This is so
983 // that we have more information about the types of arguments when we
984 // type-check the functions. This isn't really the right way to do this.
985 for &check_closures in &[false, true] {
986 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
987 let expected_iter = expected_inputs
990 .chain(param_iter.clone().skip(expected_inputs.len()));
991 for ((&arg, param_ty), expected_ty) in args.iter().zip(param_iter).zip(expected_iter) {
992 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
993 if is_closure != check_closures {
997 // the difference between param_ty and expected here is that
998 // expected is the parameter when the expected *return* type is
999 // taken into account. So in `let _: &[i32] = identity(&[1, 2])`
1000 // the expected type is already `&[i32]`, whereas param_ty is
1001 // still an unbound type variable. We don't always want to force
1002 // the parameter to coerce to the expected type (for example in
1003 // `coerce_unsize_expected_type_4`).
1004 let param_ty = self.normalize_associated_types_in(param_ty);
1005 let expected = Expectation::rvalue_hint(&mut self.table, expected_ty);
1006 // infer with the expected type we have...
1007 let ty = self.infer_expr_inner(arg, &expected);
1009 // then coerce to either the expected type or just the formal parameter type
1010 let coercion_target = if let Some(ty) = expected.only_has_type(&mut self.table) {
1011 // if we are coercing to the expectation, unify with the
1012 // formal parameter type to connect everything
1013 self.unify(&ty, ¶m_ty);
1018 if !coercion_target.is_unknown() {
1019 if self.coerce(Some(arg), &ty, &coercion_target).is_err() {
1020 self.result.type_mismatches.insert(
1022 TypeMismatch { expected: coercion_target, actual: ty.clone() },
1030 fn substs_for_method_call(
1032 def_generics: Generics,
1033 generic_args: Option<&GenericArgs>,
1035 let (parent_params, self_params, type_params, const_params, impl_trait_params) =
1036 def_generics.provenance_split();
1037 assert_eq!(self_params, 0); // method shouldn't have another Self param
1038 let total_len = parent_params + type_params + const_params + impl_trait_params;
1039 let mut substs = Vec::with_capacity(total_len);
1040 // Parent arguments are unknown
1041 for (_id, param) in def_generics.iter_parent() {
1043 TypeOrConstParamData::TypeParamData(_) => {
1044 substs.push(self.table.new_type_var());
1046 TypeOrConstParamData::ConstParamData(_) => {
1047 // FIXME: here we should do something else
1048 substs.push(self.table.new_type_var());
1052 // handle provided type arguments
1053 if let Some(generic_args) = generic_args {
1054 // if args are provided, it should be all of them, but we can't rely on that
1055 for arg in generic_args
1058 .filter(|arg| matches!(arg, GenericArg::Type(_)))
1062 GenericArg::Type(type_ref) => {
1063 let ty = self.make_ty(type_ref);
1066 GenericArg::Lifetime(_) => {}
1070 let supplied_params = substs.len();
1071 for _ in supplied_params..total_len {
1072 substs.push(self.table.new_type_var());
1074 assert_eq!(substs.len(), total_len);
1075 Substitution::from_iter(Interner, substs)
1078 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
1079 let callable_ty = self.resolve_ty_shallow(callable_ty);
1080 if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(Interner) {
1081 let def: CallableDefId = from_chalk(self.db, *fn_def);
1082 let generic_predicates = self.db.generic_predicates(def.into());
1083 for predicate in generic_predicates.iter() {
1084 let (predicate, binders) = predicate
1086 .substitute(Interner, parameters)
1087 .into_value_and_skipped_binders();
1088 always!(binders.len(Interner) == 0); // quantified where clauses not yet handled
1089 self.push_obligation(predicate.cast(Interner));
1091 // add obligation for trait implementation, if this is a trait method
1093 CallableDefId::FunctionId(f) => {
1094 if let ItemContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container {
1095 // construct a TraitRef
1096 let substs = crate::subst_prefix(
1098 generics(self.db.upcast(), trait_.into()).len(),
1100 self.push_obligation(
1101 TraitRef { trait_id: to_chalk_trait_id(trait_), substitution: substs }
1106 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}
1111 fn builtin_binary_op_return_ty(&mut self, op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Option<Ty> {
1112 let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
1113 let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
1115 BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => {
1116 Some(TyKind::Scalar(Scalar::Bool).intern(Interner))
1118 BinaryOp::Assignment { .. } => Some(TyBuilder::unit()),
1119 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => {
1120 // all integer combinations are valid here
1122 lhs_ty.kind(Interner),
1123 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1124 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1126 rhs_ty.kind(Interner),
1127 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
1128 | TyKind::InferenceVar(_, TyVariableKind::Integer)
1135 BinaryOp::ArithOp(_) => match (lhs_ty.kind(Interner), rhs_ty.kind(Interner)) {
1136 // (int, int) | (uint, uint) | (float, float)
1137 (TyKind::Scalar(Scalar::Int(_)), TyKind::Scalar(Scalar::Int(_)))
1138 | (TyKind::Scalar(Scalar::Uint(_)), TyKind::Scalar(Scalar::Uint(_)))
1139 | (TyKind::Scalar(Scalar::Float(_)), TyKind::Scalar(Scalar::Float(_))) => {
1142 // ({int}, int) | ({int}, uint)
1144 TyKind::InferenceVar(_, TyVariableKind::Integer),
1145 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1147 // (int, {int}) | (uint, {int})
1149 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
1150 TyKind::InferenceVar(_, TyVariableKind::Integer),
1152 // ({float} | float)
1154 TyKind::InferenceVar(_, TyVariableKind::Float),
1155 TyKind::Scalar(Scalar::Float(_)),
1159 TyKind::Scalar(Scalar::Float(_)),
1160 TyKind::InferenceVar(_, TyVariableKind::Float),
1162 // ({int}, {int}) | ({float}, {float})
1164 TyKind::InferenceVar(_, TyVariableKind::Integer),
1165 TyKind::InferenceVar(_, TyVariableKind::Integer),
1168 TyKind::InferenceVar(_, TyVariableKind::Float),
1169 TyKind::InferenceVar(_, TyVariableKind::Float),
1176 fn builtin_binary_op_rhs_expectation(&mut self, op: BinaryOp, lhs_ty: Ty) -> Option<Ty> {
1178 BinaryOp::LogicOp(..) => TyKind::Scalar(Scalar::Bool).intern(Interner),
1179 BinaryOp::Assignment { op: None } => lhs_ty,
1180 BinaryOp::CmpOp(CmpOp::Eq { .. }) => match self
1181 .resolve_ty_shallow(&lhs_ty)
1184 TyKind::Scalar(_) | TyKind::Str => lhs_ty,
1185 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1188 BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => return None,
1189 BinaryOp::CmpOp(CmpOp::Ord { .. })
1190 | BinaryOp::Assignment { op: Some(_) }
1191 | BinaryOp::ArithOp(_) => match self.resolve_ty_shallow(&lhs_ty).kind(Interner) {
1192 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_)) => lhs_ty,
1193 TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
1199 fn resolve_binop_method(&self, op: BinaryOp) -> Option<FunctionId> {
1200 let (name, lang_item) = match op {
1201 BinaryOp::LogicOp(_) => return None,
1202 BinaryOp::ArithOp(aop) => match aop {
1203 ArithOp::Add => (name!(add), name!(add)),
1204 ArithOp::Mul => (name!(mul), name!(mul)),
1205 ArithOp::Sub => (name!(sub), name!(sub)),
1206 ArithOp::Div => (name!(div), name!(div)),
1207 ArithOp::Rem => (name!(rem), name!(rem)),
1208 ArithOp::Shl => (name!(shl), name!(shl)),
1209 ArithOp::Shr => (name!(shr), name!(shr)),
1210 ArithOp::BitXor => (name!(bitxor), name!(bitxor)),
1211 ArithOp::BitOr => (name!(bitor), name!(bitor)),
1212 ArithOp::BitAnd => (name!(bitand), name!(bitand)),
1214 BinaryOp::Assignment { op: Some(aop) } => match aop {
1215 ArithOp::Add => (name!(add_assign), name!(add_assign)),
1216 ArithOp::Mul => (name!(mul_assign), name!(mul_assign)),
1217 ArithOp::Sub => (name!(sub_assign), name!(sub_assign)),
1218 ArithOp::Div => (name!(div_assign), name!(div_assign)),
1219 ArithOp::Rem => (name!(rem_assign), name!(rem_assign)),
1220 ArithOp::Shl => (name!(shl_assign), name!(shl_assign)),
1221 ArithOp::Shr => (name!(shr_assign), name!(shr_assign)),
1222 ArithOp::BitXor => (name!(bitxor_assign), name!(bitxor_assign)),
1223 ArithOp::BitOr => (name!(bitor_assign), name!(bitor_assign)),
1224 ArithOp::BitAnd => (name!(bitand_assign), name!(bitand_assign)),
1226 BinaryOp::CmpOp(cop) => match cop {
1227 CmpOp::Eq { negated: false } => (name!(eq), name!(eq)),
1228 CmpOp::Eq { negated: true } => (name!(ne), name!(eq)),
1229 CmpOp::Ord { ordering: Ordering::Less, strict: false } => {
1230 (name!(le), name!(partial_ord))
1232 CmpOp::Ord { ordering: Ordering::Less, strict: true } => {
1233 (name!(lt), name!(partial_ord))
1235 CmpOp::Ord { ordering: Ordering::Greater, strict: false } => {
1236 (name!(ge), name!(partial_ord))
1238 CmpOp::Ord { ordering: Ordering::Greater, strict: true } => {
1239 (name!(gt), name!(partial_ord))
1242 BinaryOp::Assignment { op: None } => return None,
1245 let trait_ = self.resolve_lang_item(lang_item)?.as_trait()?;
1247 self.db.trait_data(trait_).method_by_name(&name)