//! Type inference for expressions.
-use std::iter::{repeat, repeat_with};
-use std::{mem, sync::Arc};
+use std::{
+ iter::{repeat, repeat_with},
+ mem,
+ sync::Arc,
+};
use chalk_ir::{cast::Cast, fold::Shift, Mutability, TyVariableKind};
use hir_def::{
- expr::{Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp},
+ expr::{
+ ArithOp, Array, BinaryOp, CmpOp, Expr, ExprId, Literal, MatchGuard, Ordering, Statement,
+ UnaryOp,
+ },
path::{GenericArg, GenericArgs},
resolver::resolver_for_expr,
- AssocContainerId, FieldId, Lookup,
+ AssocContainerId, FieldId, FunctionId, Lookup,
};
use hir_expand::name::{name, Name};
use stdx::always;
use syntax::ast::RangeOp;
use crate::{
- autoderef, consteval,
+ autoderef::{self, Autoderef},
+ consteval,
+ infer::coerce::CoerceMany,
lower::lower_to_chalk_mutability,
mapping::from_chalk,
- method_resolution, op,
+ method_resolution,
primitive::{self, UintTy},
static_lifetime, to_chalk_trait_id,
traits::FnTrait,
if !could_unify {
self.result.type_mismatches.insert(
tgt_expr.into(),
- TypeMismatch { expected: expected_ty.clone(), actual: ty.clone() },
+ TypeMismatch { expected: expected_ty, actual: ty.clone() },
);
}
}
/// Infer type of expression with possibly implicit coerce to the expected type.
/// Return the type after possible coercion.
pub(super) fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty {
- let ty = self.infer_expr_inner(expr, &expected);
- let ty = if let Some(target) = expected.only_has_type(&mut self.table) {
- if !self.coerce(&ty, &target) {
- self.result.type_mismatches.insert(
- expr.into(),
- TypeMismatch { expected: target.clone(), actual: ty.clone() },
- );
- // Return actual type when type mismatch.
- // This is needed for diagnostic when return type mismatch.
- ty
- } else {
- target.clone()
+ let ty = self.infer_expr_inner(expr, expected);
+ if let Some(target) = expected.only_has_type(&mut self.table) {
+ match self.coerce(Some(expr), &ty, &target) {
+ Ok(res) => res.value,
+ Err(_) => {
+ self.result
+ .type_mismatches
+ .insert(expr.into(), TypeMismatch { expected: target, actual: ty.clone() });
+ // Return actual type when type mismatch.
+ // This is needed for diagnostic when return type mismatch.
+ ty
+ }
}
} else {
ty
- };
-
- ty
+ }
}
fn callable_sig_from_fn_trait(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
}
fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
- self.db.check_canceled();
+ self.db.unwind_if_cancelled();
let body = Arc::clone(&self.body); // avoid borrow checker problem
let ty = match &body[tgt_expr] {
Expr::Missing => self.err_ty(),
- Expr::If { condition, then_branch, else_branch } => {
+ &Expr::If { condition, then_branch, else_branch } => {
// if let is desugared to match, so this is always simple if
self.infer_expr(
- *condition,
+ condition,
&Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
);
let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
let mut both_arms_diverge = Diverges::Always;
- let mut result_ty = self.table.new_type_var();
- let then_ty = self.infer_expr_inner(*then_branch, &expected);
+ let result_ty = self.table.new_type_var();
+ let then_ty = self.infer_expr_inner(then_branch, expected);
both_arms_diverge &= mem::replace(&mut self.diverges, Diverges::Maybe);
- result_ty = self.coerce_merge_branch(Some(*then_branch), &result_ty, &then_ty);
+ let mut coerce = CoerceMany::new(result_ty);
+ coerce.coerce(self, Some(then_branch), &then_ty);
let else_ty = match else_branch {
- Some(else_branch) => self.infer_expr_inner(*else_branch, &expected),
+ Some(else_branch) => self.infer_expr_inner(else_branch, expected),
None => TyBuilder::unit(),
};
both_arms_diverge &= self.diverges;
// FIXME: create a synthetic `else {}` so we have something to refer to here instead of None?
- result_ty = self.coerce_merge_branch(*else_branch, &result_ty, &else_ty);
+ coerce.coerce(self, else_branch, &else_ty);
self.diverges = condition_diverges | both_arms_diverge;
- result_ty
+ coerce.complete()
}
Expr::Block { statements, tail, label, id: _ } => {
let old_resolver = mem::replace(
let break_ty = self.table.new_type_var();
self.breakables.push(BreakableContext {
may_break: false,
- break_ty: break_ty.clone(),
+ coerce: CoerceMany::new(break_ty.clone()),
label: label.map(|label| self.body[label].name.clone()),
});
- let ty =
- self.infer_block(statements, *tail, &Expectation::has_type(break_ty));
+ let ty = self.infer_block(
+ tgt_expr,
+ statements,
+ *tail,
+ &Expectation::has_type(break_ty),
+ );
let ctxt = self.breakables.pop().expect("breakable stack broken");
if ctxt.may_break {
- ctxt.break_ty
+ ctxt.coerce.complete()
} else {
ty
}
}
- None => self.infer_block(statements, *tail, expected),
+ None => self.infer_block(tgt_expr, statements, *tail, expected),
};
self.resolver = old_resolver;
ty
}
Expr::Async { body } => {
// Use the first type parameter as the output type of future.
- // existenail type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
+ // existential type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
let inner_ty = self.infer_expr(*body, &Expectation::none());
let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
Expr::Loop { body, label } => {
self.breakables.push(BreakableContext {
may_break: false,
- break_ty: self.table.new_type_var(),
+ coerce: CoerceMany::new(self.table.new_type_var()),
label: label.map(|label| self.body[label].name.clone()),
});
self.infer_expr(*body, &Expectation::has_type(TyBuilder::unit()));
let ctxt = self.breakables.pop().expect("breakable stack broken");
- if ctxt.may_break {
- self.diverges = Diverges::Maybe;
- }
if ctxt.may_break {
- ctxt.break_ty
+ self.diverges = Diverges::Maybe;
+ ctxt.coerce.complete()
} else {
TyKind::Never.intern(&Interner)
}
Expr::While { condition, body, label } => {
self.breakables.push(BreakableContext {
may_break: false,
- break_ty: self.err_ty(),
+ coerce: CoerceMany::new(self.err_ty()),
label: label.map(|label| self.body[label].name.clone()),
});
// while let is desugared to a match loop, so this is always simple while
self.breakables.push(BreakableContext {
may_break: false,
- break_ty: self.err_ty(),
+ coerce: CoerceMany::new(self.err_ty()),
label: label.map(|label| self.body[label].name.clone()),
});
let pat_ty =
.intern(&Interner);
let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
let closure_ty =
- TyKind::Closure(closure_id, Substitution::from1(&Interner, sig_ty))
+ TyKind::Closure(closure_id, Substitution::from1(&Interner, sig_ty.clone()))
.intern(&Interner);
// Eagerly try to relate the closure type with the expected
// type, otherwise we often won't have enough information to
// infer the body.
- if let Some(t) = expected.only_has_type(&mut self.table) {
- self.coerce(&closure_ty, &t);
- }
+ self.deduce_closure_type_from_expectations(
+ tgt_expr,
+ &closure_ty,
+ &sig_ty,
+ expected,
+ );
// Now go through the argument patterns
for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
Expr::Call { callee, args } => {
let callee_ty = self.infer_expr(*callee, &Expectation::none());
let canonicalized = self.canonicalize(callee_ty.clone());
- let mut derefs = autoderef(
+ let mut derefs = Autoderef::new(
self.db,
self.resolver.krate(),
InEnvironment {
environment: self.table.trait_env.env.clone(),
},
);
- let (param_tys, ret_ty): (Vec<Ty>, Ty) = derefs
- .find_map(|callee_deref_ty| {
- self.callable_sig(
- &canonicalized.decanonicalize_ty(callee_deref_ty.value),
- args.len(),
- )
- })
- .unwrap_or((Vec::new(), self.err_ty()));
+ let res = derefs.by_ref().find_map(|(callee_deref_ty, _)| {
+ let ty = &canonicalized.decanonicalize_ty(&mut self.table, callee_deref_ty);
+ self.callable_sig(ty, args.len())
+ });
+ let (param_tys, ret_ty): (Vec<Ty>, Ty) = match res {
+ Some(res) => {
+ self.write_expr_adj(*callee, self.auto_deref_adjust_steps(&derefs));
+ res
+ }
+ None => (Vec::new(), self.err_ty()),
+ };
self.register_obligations_for_call(&callee_ty);
- self.check_call_arguments(args, ¶m_tys);
+
+ let expected_inputs = self.expected_inputs_for_expected_output(
+ expected,
+ ret_ty.clone(),
+ param_tys.clone(),
+ );
+
+ self.check_call_arguments(args, &expected_inputs, ¶m_tys);
self.normalize_associated_types_in(ret_ty)
}
Expr::MethodCall { receiver, args, method_name, generic_args } => self
.infer_method_call(
tgt_expr,
*receiver,
- &args,
- &method_name,
+ args,
+ method_name,
generic_args.as_deref(),
+ expected,
),
Expr::Match { expr, arms } => {
let input_ty = self.infer_expr(*expr, &Expectation::none());
- let mut result_ty = if arms.is_empty() {
+ let expected = expected.adjust_for_branches(&mut self.table);
+
+ let result_ty = if arms.is_empty() {
TyKind::Never.intern(&Interner)
} else {
- self.table.new_type_var()
+ match &expected {
+ Expectation::HasType(ty) => ty.clone(),
+ _ => self.table.new_type_var(),
+ }
};
+ let mut coerce = CoerceMany::new(result_ty);
let matchee_diverges = self.diverges;
let mut all_arms_diverge = Diverges::Always;
for arm in arms {
self.diverges = Diverges::Maybe;
let _pat_ty = self.infer_pat(arm.pat, &input_ty, BindingMode::default());
- if let Some(guard_expr) = arm.guard {
- self.infer_expr(
- guard_expr,
- &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
- );
+ match arm.guard {
+ Some(MatchGuard::If { expr: guard_expr }) => {
+ self.infer_expr(
+ guard_expr,
+ &Expectation::has_type(
+ TyKind::Scalar(Scalar::Bool).intern(&Interner),
+ ),
+ );
+ }
+ Some(MatchGuard::IfLet { expr, pat }) => {
+ let input_ty = self.infer_expr(expr, &Expectation::none());
+ let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default());
+ }
+ _ => {}
}
let arm_ty = self.infer_expr_inner(arm.expr, &expected);
all_arms_diverge &= self.diverges;
- result_ty = self.coerce_merge_branch(Some(arm.expr), &result_ty, &arm_ty);
+ coerce.coerce(self, Some(arm.expr), &arm_ty);
}
self.diverges = matchee_diverges | all_arms_diverge;
- result_ty
+ coerce.complete()
}
Expr::Path(p) => {
// FIXME this could be more efficient...
let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
- self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(self.err_ty())
+ self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or_else(|| self.err_ty())
}
Expr::Continue { .. } => TyKind::Never.intern(&Interner),
Expr::Break { expr, label } => {
- let last_ty =
- if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
- ctxt.break_ty.clone()
- } else {
- self.err_ty()
- };
+ let mut coerce = match find_breakable(&mut self.breakables, label.as_ref()) {
+ Some(ctxt) => {
+ // avoiding the borrowck
+ mem::replace(
+ &mut ctxt.coerce,
+ CoerceMany::new(self.result.standard_types.unknown.clone()),
+ )
+ }
+ None => CoerceMany::new(self.result.standard_types.unknown.clone()),
+ };
- let val_ty = if let Some(expr) = expr {
- self.infer_expr(*expr, &Expectation::none())
+ let val_ty = if let Some(expr) = *expr {
+ self.infer_expr(expr, &Expectation::none())
} else {
TyBuilder::unit()
};
// FIXME: create a synthetic `()` during lowering so we have something to refer to here?
- let merged_type = self.coerce_merge_branch(*expr, &last_ty, &val_ty);
+ coerce.coerce(self, *expr, &val_ty);
if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
- ctxt.break_ty = merged_type;
+ ctxt.coerce = coerce;
ctxt.may_break = true;
} else {
self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop {
expr: tgt_expr,
});
- }
+ };
+
TyKind::Never.intern(&Interner)
}
Expr::Return { expr } => {
self.infer_expr_coerce(*expr, &Expectation::has_type(self.return_ty.clone()));
} else {
let unit = TyBuilder::unit();
- self.coerce(&unit, &self.return_ty.clone());
+ let _ = self.coerce(Some(tgt_expr), &unit, &self.return_ty.clone());
}
TyKind::Never.intern(&Interner)
}
TyKind::Never.intern(&Interner)
}
Expr::RecordLit { path, fields, spread } => {
- let (ty, def_id) = self.resolve_variant(path.as_deref());
+ let (ty, def_id) = self.resolve_variant(path.as_deref(), false);
if let Some(variant) = def_id {
self.write_variant_resolution(tgt_expr.into(), variant);
}
Expr::Field { expr, name } => {
let receiver_ty = self.infer_expr_inner(*expr, &Expectation::none());
let canonicalized = self.canonicalize(receiver_ty);
- let ty = autoderef::autoderef(
+
+ let mut autoderef = Autoderef::new(
self.db,
self.resolver.krate(),
InEnvironment {
goal: canonicalized.value.clone(),
environment: self.trait_env.env.clone(),
},
- )
- .find_map(|derefed_ty| {
- let def_db = self.db.upcast();
+ );
+ let ty = autoderef.by_ref().find_map(|(derefed_ty, _)| {
let module = self.resolver.module();
+ let db = self.db;
let is_visible = |field_id: &FieldId| {
module
.map(|mod_id| {
- self.db.field_visibilities(field_id.parent)[field_id.local_id]
- .is_visible_from(def_db, mod_id)
+ db.field_visibilities(field_id.parent)[field_id.local_id]
+ .is_visible_from(db.upcast(), mod_id)
})
.unwrap_or(true)
};
- match canonicalized.decanonicalize_ty(derefed_ty.value).kind(&Interner) {
+ match canonicalized
+ .decanonicalize_ty(&mut self.table, derefed_ty)
+ .kind(&Interner)
+ {
TyKind::Tuple(_, substs) => name.as_tuple_index().and_then(|idx| {
substs
.as_slice(&Interner)
}
_ => None,
}
- })
- .unwrap_or(self.err_ty());
+ });
+ let ty = match ty {
+ Some(ty) => {
+ self.write_expr_adj(*expr, self.auto_deref_adjust_steps(&autoderef));
+ ty
+ }
+ None => self.err_ty(),
+ };
let ty = self.insert_type_vars(ty);
self.normalize_associated_types_in(ty)
}
// FIXME: record type error - expected reference but found ptr,
// which cannot be coerced
}
- Expectation::rvalue_hint(Ty::clone(exp_inner))
+ Expectation::rvalue_hint(&mut self.table, Ty::clone(exp_inner))
} else {
Expectation::none()
};
},
) {
Some(derefed_ty) => {
- canonicalized.decanonicalize_ty(derefed_ty.value)
+ canonicalized.decanonicalize_ty(&mut self.table, derefed_ty)
}
None => self.err_ty(),
}
UnaryOp::Neg => {
match inner_ty.kind(&Interner) {
// Fast path for builtins
- TyKind::Scalar(Scalar::Int(_))
- | TyKind::Scalar(Scalar::Uint(_))
- | TyKind::Scalar(Scalar::Float(_))
- | TyKind::InferenceVar(_, TyVariableKind::Integer)
- | TyKind::InferenceVar(_, TyVariableKind::Float) => inner_ty,
+ TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_))
+ | TyKind::InferenceVar(
+ _,
+ TyVariableKind::Integer | TyVariableKind::Float,
+ ) => inner_ty,
// Otherwise we resolve via the std::ops::Neg trait
_ => self
.resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
UnaryOp::Not => {
match inner_ty.kind(&Interner) {
// Fast path for builtins
- TyKind::Scalar(Scalar::Bool)
- | TyKind::Scalar(Scalar::Int(_))
- | TyKind::Scalar(Scalar::Uint(_))
+ TyKind::Scalar(Scalar::Bool | Scalar::Int(_) | Scalar::Uint(_))
| TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
// Otherwise we resolve via the std::ops::Not trait
_ => self
}
}
Expr::BinaryOp { lhs, rhs, op } => match op {
- Some(op) => {
- let lhs_expectation = match op {
- BinaryOp::LogicOp(..) => {
- Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner))
- }
- _ => Expectation::none(),
- };
- let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
- let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
- let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty.clone());
- let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation));
- let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
-
- let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone());
-
- if ret.is_unknown() {
- cov_mark::hit!(infer_expr_inner_binary_operator_overload);
-
- self.resolve_associated_type_with_params(
- lhs_ty,
- self.resolve_binary_op_output(op),
- &[rhs_ty],
- )
- } else {
- ret
- }
+ Some(BinaryOp::Assignment { op: None }) => {
+ let lhs_ty = self.infer_expr(*lhs, &Expectation::none());
+ self.infer_expr_coerce(*rhs, &Expectation::has_type(lhs_ty));
+ self.result.standard_types.unit.clone()
}
+ Some(BinaryOp::LogicOp(_)) => {
+ let bool_ty = self.result.standard_types.bool_.clone();
+ self.infer_expr_coerce(*lhs, &Expectation::HasType(bool_ty.clone()));
+ let lhs_diverges = self.diverges;
+ self.infer_expr_coerce(*rhs, &Expectation::HasType(bool_ty.clone()));
+ // Depending on the LHS' value, the RHS can never execute.
+ self.diverges = lhs_diverges;
+ bool_ty
+ }
+ Some(op) => self.infer_overloadable_binop(*lhs, *op, *rhs, tgt_expr),
_ => self.err_ty(),
},
Expr::Range { lhs, rhs, range_type } => {
krate,
index_trait,
);
- let self_ty =
- self_ty.map_or(self.err_ty(), |t| canonicalized.decanonicalize_ty(t.value));
+ let self_ty = self_ty.map_or(self.err_ty(), |t| {
+ canonicalized.decanonicalize_ty(&mut self.table, t)
+ });
self.resolve_associated_type_with_params(
self_ty,
self.resolve_ops_index_output(),
Expr::Array(array) => {
let elem_ty =
match expected.to_option(&mut self.table).as_ref().map(|t| t.kind(&Interner)) {
- Some(TyKind::Array(st, _)) | Some(TyKind::Slice(st)) => st.clone(),
+ Some(TyKind::Array(st, _) | TyKind::Slice(st)) => st.clone(),
_ => self.table.new_type_var(),
};
+ let mut coerce = CoerceMany::new(elem_ty.clone());
+ let expected = Expectation::has_type(elem_ty.clone());
let len = match array {
Array::ElementList(items) => {
- for expr in items.iter() {
- // FIXME: use CoerceMany (coerce_merge_branch)
- self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone()));
+ for &expr in items.iter() {
+ let cur_elem_ty = self.infer_expr_inner(expr, &expected);
+ coerce.coerce(self, Some(expr), &cur_elem_ty);
}
Some(items.len() as u64)
}
- Array::Repeat { initializer, repeat } => {
- self.infer_expr_coerce(
- *initializer,
- &Expectation::has_type(elem_ty.clone()),
- );
+ &Array::Repeat { initializer, repeat } => {
+ self.infer_expr_coerce(initializer, &Expectation::has_type(elem_ty));
self.infer_expr(
- *repeat,
+ repeat,
&Expectation::has_type(
TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner),
),
);
- let repeat_expr = &self.body.exprs[*repeat];
+ let repeat_expr = &self.body.exprs[repeat];
consteval::eval_usize(repeat_expr)
}
};
- TyKind::Array(elem_ty, consteval::usize_const(len)).intern(&Interner)
+ TyKind::Array(coerce.complete(), consteval::usize_const(len)).intern(&Interner)
}
Expr::Literal(lit) => match lit {
Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(&Interner),
None => self.table.new_float_var(),
},
},
- Expr::MacroStmts { tail } => self.infer_expr(*tail, expected),
+ Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
};
// use a new type variable if we got unknown here
let ty = self.insert_type_vars_shallow(ty);
ty
}
+ fn infer_overloadable_binop(
+ &mut self,
+ lhs: ExprId,
+ op: BinaryOp,
+ rhs: ExprId,
+ tgt_expr: ExprId,
+ ) -> Ty {
+ let lhs_expectation = Expectation::none();
+ let lhs_ty = self.infer_expr(lhs, &lhs_expectation);
+ let rhs_ty = self.table.new_type_var();
+
+ let func = self.resolve_binop_method(op);
+ let func = match func {
+ Some(func) => func,
+ None => {
+ let rhs_ty = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone());
+ let rhs_ty = self.infer_expr_coerce(rhs, &Expectation::from_option(rhs_ty));
+ return self
+ .builtin_binary_op_return_ty(op, lhs_ty, rhs_ty)
+ .unwrap_or_else(|| self.err_ty());
+ }
+ };
+
+ let subst = TyBuilder::subst_for_def(self.db, func)
+ .push(lhs_ty.clone())
+ .push(rhs_ty.clone())
+ .build();
+ self.write_method_resolution(tgt_expr, func, subst.clone());
+
+ let method_ty = self.db.value_ty(func.into()).substitute(&Interner, &subst);
+ self.register_obligations_for_call(&method_ty);
+
+ self.infer_expr_coerce(rhs, &Expectation::has_type(rhs_ty.clone()));
+
+ let ret_ty = match method_ty.callable_sig(self.db) {
+ Some(sig) => sig.ret().clone(),
+ None => self.err_ty(),
+ };
+
+ let ret_ty = self.normalize_associated_types_in(ret_ty);
+
+ // FIXME: record autoref adjustments
+
+ // use knowledge of built-in binary ops, which can sometimes help inference
+ if let Some(builtin_rhs) = self.builtin_binary_op_rhs_expectation(op, lhs_ty.clone()) {
+ self.unify(&builtin_rhs, &rhs_ty);
+ }
+ if let Some(builtin_ret) = self.builtin_binary_op_return_ty(op, lhs_ty, rhs_ty) {
+ self.unify(&builtin_ret, &ret_ty);
+ }
+
+ ret_ty
+ }
+
fn infer_block(
&mut self,
+ expr: ExprId,
statements: &[Statement],
tail: Option<ExprId>,
expected: &Expectation,
for stmt in statements {
match stmt {
Statement::Let { pat, type_ref, initializer } => {
- let decl_ty =
- type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(self.err_ty());
+ let decl_ty = type_ref
+ .as_ref()
+ .map(|tr| self.make_ty(tr))
+ .unwrap_or_else(|| self.err_ty());
// Always use the declared type when specified
let mut ty = decl_ty.clone();
}
}
- let ty = if let Some(expr) = tail {
+ if let Some(expr) = tail {
self.infer_expr_coerce(expr, expected)
} else {
// Citing rustc: if there is no explicit tail expression,
self.table.new_maybe_never_var()
} else {
if let Some(t) = expected.only_has_type(&mut self.table) {
- self.coerce(&TyBuilder::unit(), &t);
+ let _ = self.coerce(Some(expr), &TyBuilder::unit(), &t);
}
TyBuilder::unit()
}
- };
- ty
+ }
}
fn infer_method_call(
args: &[ExprId],
method_name: &Name,
generic_args: Option<&GenericArgs>,
+ expected: &Expectation,
) -> Ty {
let receiver_ty = self.infer_expr(receiver, &Expectation::none());
let canonicalized_receiver = self.canonicalize(receiver_ty.clone());
method_name,
)
});
- let (derefed_receiver_ty, method_ty, def_generics) = match resolved {
+ let (receiver_ty, method_ty, substs) = match resolved {
Some((ty, func)) => {
- let ty = canonicalized_receiver.decanonicalize_ty(ty);
- self.write_method_resolution(tgt_expr, func);
- (ty, self.db.value_ty(func.into()), Some(generics(self.db.upcast(), func.into())))
+ let ty = canonicalized_receiver.decanonicalize_ty(&mut self.table, ty);
+ let generics = generics(self.db.upcast(), func.into());
+ let substs = self.substs_for_method_call(generics, generic_args, &ty);
+ self.write_method_resolution(tgt_expr, func, substs.clone());
+ (ty, self.db.value_ty(func.into()), substs)
}
- None => (receiver_ty, Binders::empty(&Interner, self.err_ty()), None),
+ None => (
+ receiver_ty,
+ Binders::empty(&Interner, self.err_ty()),
+ Substitution::empty(&Interner),
+ ),
};
- let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty);
let method_ty = method_ty.substitute(&Interner, &substs);
- let method_ty = self.insert_type_vars(method_ty);
self.register_obligations_for_call(&method_ty);
- let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
+ let (formal_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
Some(sig) => {
if !sig.params().is_empty() {
(sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
}
None => (self.err_ty(), Vec::new(), self.err_ty()),
};
- // Apply autoref so the below unification works correctly
- // FIXME: return correct autorefs from lookup_method
- let actual_receiver_ty = match self.resolve_ty_shallow(&expected_receiver_ty).as_reference()
- {
- Some((_, lifetime, mutability)) => {
- TyKind::Ref(mutability, lifetime, derefed_receiver_ty).intern(&Interner)
- }
- _ => derefed_receiver_ty,
- };
- self.unify(&expected_receiver_ty, &actual_receiver_ty);
+ self.unify(&formal_receiver_ty, &receiver_ty);
+
+ let expected_inputs =
+ self.expected_inputs_for_expected_output(expected, ret_ty.clone(), param_tys.clone());
- self.check_call_arguments(args, ¶m_tys);
+ self.check_call_arguments(args, &expected_inputs, ¶m_tys);
self.normalize_associated_types_in(ret_ty)
}
- fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) {
+ fn expected_inputs_for_expected_output(
+ &mut self,
+ expected_output: &Expectation,
+ output: Ty,
+ inputs: Vec<Ty>,
+ ) -> Vec<Ty> {
+ if let Some(expected_ty) = expected_output.to_option(&mut self.table) {
+ self.table.fudge_inference(|table| {
+ if table.try_unify(&expected_ty, &output).is_ok() {
+ table.resolve_with_fallback(inputs, |var, kind, _, _| match kind {
+ chalk_ir::VariableKind::Ty(tk) => var.to_ty(&Interner, tk).cast(&Interner),
+ chalk_ir::VariableKind::Lifetime => {
+ var.to_lifetime(&Interner).cast(&Interner)
+ }
+ chalk_ir::VariableKind::Const(ty) => {
+ var.to_const(&Interner, ty).cast(&Interner)
+ }
+ })
+ } else {
+ Vec::new()
+ }
+ })
+ } else {
+ Vec::new()
+ }
+ }
+
+ fn check_call_arguments(&mut self, args: &[ExprId], expected_inputs: &[Ty], param_tys: &[Ty]) {
// Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 --
// We do this in a pretty awful way: first we type-check any arguments
// that are not closures, then we type-check the closures. This is so
// type-check the functions. This isn't really the right way to do this.
for &check_closures in &[false, true] {
let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
- for (&arg, param_ty) in args.iter().zip(param_iter) {
+ let expected_iter = expected_inputs
+ .iter()
+ .cloned()
+ .chain(param_iter.clone().skip(expected_inputs.len()));
+ for ((&arg, param_ty), expected_ty) in args.iter().zip(param_iter).zip(expected_iter) {
let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
if is_closure != check_closures {
continue;
}
+ // the difference between param_ty and expected here is that
+ // expected is the parameter when the expected *return* type is
+ // taken into account. So in `let _: &[i32] = identity(&[1, 2])`
+ // the expected type is already `&[i32]`, whereas param_ty is
+ // still an unbound type variable. We don't always want to force
+ // the parameter to coerce to the expected type (for example in
+ // `coerce_unsize_expected_type_4`).
let param_ty = self.normalize_associated_types_in(param_ty);
- self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone()));
+ let expected = Expectation::rvalue_hint(&mut self.table, expected_ty);
+ // infer with the expected type we have...
+ let ty = self.infer_expr_inner(arg, &expected);
+
+ // then coerce to either the expected type or just the formal parameter type
+ let coercion_target = if let Some(ty) = expected.only_has_type(&mut self.table) {
+ // if we are coercing to the expectation, unify with the
+ // formal parameter type to connect everything
+ self.unify(&ty, ¶m_ty);
+ ty
+ } else {
+ param_ty
+ };
+ if !coercion_target.is_unknown() {
+ if self.coerce(Some(arg), &ty, &coercion_target).is_err() {
+ self.result.type_mismatches.insert(
+ arg.into(),
+ TypeMismatch { expected: coercion_target, actual: ty.clone() },
+ );
+ }
+ }
}
}
}
fn substs_for_method_call(
&mut self,
- def_generics: Option<Generics>,
+ def_generics: Generics,
generic_args: Option<&GenericArgs>,
receiver_ty: &Ty,
) -> Substitution {
let (parent_params, self_params, type_params, impl_trait_params) =
- def_generics.as_ref().map_or((0, 0, 0, 0), |g| g.provenance_split());
+ def_generics.provenance_split();
assert_eq!(self_params, 0); // method shouldn't have another Self param
let total_len = parent_params + type_params + impl_trait_params;
let mut substs = Vec::with_capacity(total_len);
// Parent arguments are unknown, except for the receiver type
- if let Some(parent_generics) = def_generics.as_ref().map(|p| p.iter_parent()) {
- for (_id, param) in parent_generics {
- if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
- substs.push(receiver_ty.clone());
- } else {
- substs.push(self.err_ty());
- }
+ for (_id, param) in def_generics.iter_parent() {
+ if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
+ substs.push(receiver_ty.clone());
+ } else {
+ substs.push(self.table.new_type_var());
}
}
// handle provided type arguments
};
let supplied_params = substs.len();
for _ in supplied_params..total_len {
- substs.push(self.err_ty());
+ substs.push(self.table.new_type_var());
}
assert_eq!(substs.len(), total_len);
Substitution::from_iter(&Interner, substs)
}
fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
- let callable_ty = self.resolve_ty_shallow(&callable_ty);
+ let callable_ty = self.resolve_ty_shallow(callable_ty);
if let TyKind::FnDef(fn_def, parameters) = callable_ty.kind(&Interner) {
let def: CallableDefId = from_chalk(self.db, *fn_def);
let generic_predicates = self.db.generic_predicates(def.into());
}
}
}
+
+ fn builtin_binary_op_return_ty(&mut self, op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Option<Ty> {
+ let lhs_ty = self.resolve_ty_shallow(&lhs_ty);
+ let rhs_ty = self.resolve_ty_shallow(&rhs_ty);
+ match op {
+ BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => {
+ Some(TyKind::Scalar(Scalar::Bool).intern(&Interner))
+ }
+ BinaryOp::Assignment { .. } => Some(TyBuilder::unit()),
+ BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => {
+ // all integer combinations are valid here
+ if matches!(
+ lhs_ty.kind(&Interner),
+ TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
+ | TyKind::InferenceVar(_, TyVariableKind::Integer)
+ ) && matches!(
+ rhs_ty.kind(&Interner),
+ TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
+ | TyKind::InferenceVar(_, TyVariableKind::Integer)
+ ) {
+ Some(lhs_ty)
+ } else {
+ None
+ }
+ }
+ BinaryOp::ArithOp(_) => match (lhs_ty.kind(&Interner), rhs_ty.kind(&Interner)) {
+ // (int, int) | (uint, uint) | (float, float)
+ (TyKind::Scalar(Scalar::Int(_)), TyKind::Scalar(Scalar::Int(_)))
+ | (TyKind::Scalar(Scalar::Uint(_)), TyKind::Scalar(Scalar::Uint(_)))
+ | (TyKind::Scalar(Scalar::Float(_)), TyKind::Scalar(Scalar::Float(_))) => {
+ Some(rhs_ty)
+ }
+ // ({int}, int) | ({int}, uint)
+ (
+ TyKind::InferenceVar(_, TyVariableKind::Integer),
+ TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
+ ) => Some(rhs_ty),
+ // (int, {int}) | (uint, {int})
+ (
+ TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)),
+ TyKind::InferenceVar(_, TyVariableKind::Integer),
+ ) => Some(lhs_ty),
+ // ({float} | float)
+ (
+ TyKind::InferenceVar(_, TyVariableKind::Float),
+ TyKind::Scalar(Scalar::Float(_)),
+ ) => Some(rhs_ty),
+ // (float, {float})
+ (
+ TyKind::Scalar(Scalar::Float(_)),
+ TyKind::InferenceVar(_, TyVariableKind::Float),
+ ) => Some(lhs_ty),
+ // ({int}, {int}) | ({float}, {float})
+ (
+ TyKind::InferenceVar(_, TyVariableKind::Integer),
+ TyKind::InferenceVar(_, TyVariableKind::Integer),
+ )
+ | (
+ TyKind::InferenceVar(_, TyVariableKind::Float),
+ TyKind::InferenceVar(_, TyVariableKind::Float),
+ ) => Some(rhs_ty),
+ _ => None,
+ },
+ }
+ }
+
+ fn builtin_binary_op_rhs_expectation(&mut self, op: BinaryOp, lhs_ty: Ty) -> Option<Ty> {
+ Some(match op {
+ BinaryOp::LogicOp(..) => TyKind::Scalar(Scalar::Bool).intern(&Interner),
+ BinaryOp::Assignment { op: None } => lhs_ty,
+ BinaryOp::CmpOp(CmpOp::Eq { .. }) => match self
+ .resolve_ty_shallow(&lhs_ty)
+ .kind(&Interner)
+ {
+ TyKind::Scalar(_) | TyKind::Str => lhs_ty,
+ TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
+ _ => return None,
+ },
+ BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) => return None,
+ BinaryOp::CmpOp(CmpOp::Ord { .. })
+ | BinaryOp::Assignment { op: Some(_) }
+ | BinaryOp::ArithOp(_) => match self.resolve_ty_shallow(&lhs_ty).kind(&Interner) {
+ TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_) | Scalar::Float(_)) => lhs_ty,
+ TyKind::InferenceVar(_, TyVariableKind::Integer | TyVariableKind::Float) => lhs_ty,
+ _ => return None,
+ },
+ })
+ }
+
+ fn resolve_binop_method(&self, op: BinaryOp) -> Option<FunctionId> {
+ let (name, lang_item) = match op {
+ BinaryOp::LogicOp(_) => return None,
+ BinaryOp::ArithOp(aop) => match aop {
+ ArithOp::Add => (name!(add), "add"),
+ ArithOp::Mul => (name!(mul), "mul"),
+ ArithOp::Sub => (name!(sub), "sub"),
+ ArithOp::Div => (name!(div), "div"),
+ ArithOp::Rem => (name!(rem), "rem"),
+ ArithOp::Shl => (name!(shl), "shl"),
+ ArithOp::Shr => (name!(shr), "shr"),
+ ArithOp::BitXor => (name!(bitxor), "bitxor"),
+ ArithOp::BitOr => (name!(bitor), "bitor"),
+ ArithOp::BitAnd => (name!(bitand), "bitand"),
+ },
+ BinaryOp::Assignment { op: Some(aop) } => match aop {
+ ArithOp::Add => (name!(add_assign), "add_assign"),
+ ArithOp::Mul => (name!(mul_assign), "mul_assign"),
+ ArithOp::Sub => (name!(sub_assign), "sub_assign"),
+ ArithOp::Div => (name!(div_assign), "div_assign"),
+ ArithOp::Rem => (name!(rem_assign), "rem_assign"),
+ ArithOp::Shl => (name!(shl_assign), "shl_assign"),
+ ArithOp::Shr => (name!(shr_assign), "shr_assign"),
+ ArithOp::BitXor => (name!(bitxor_assign), "bitxor_assign"),
+ ArithOp::BitOr => (name!(bitor_assign), "bitor_assign"),
+ ArithOp::BitAnd => (name!(bitand_assign), "bitand_assign"),
+ },
+ BinaryOp::CmpOp(cop) => match cop {
+ CmpOp::Eq { negated: false } => (name!(eq), "eq"),
+ CmpOp::Eq { negated: true } => (name!(ne), "eq"),
+ CmpOp::Ord { ordering: Ordering::Less, strict: false } => {
+ (name!(le), "partial_ord")
+ }
+ CmpOp::Ord { ordering: Ordering::Less, strict: true } => (name!(lt), "partial_ord"),
+ CmpOp::Ord { ordering: Ordering::Greater, strict: false } => {
+ (name!(ge), "partial_ord")
+ }
+ CmpOp::Ord { ordering: Ordering::Greater, strict: true } => {
+ (name!(gt), "partial_ord")
+ }
+ },
+ BinaryOp::Assignment { op: None } => return None,
+ };
+
+ let trait_ = self.resolve_lang_item(lang_item)?.as_trait()?;
+
+ self.db.trait_data(trait_).method_by_name(&name)
+ }
}