]> git.lizzy.rs Git - rust.git/blobdiff - crates/hir_ty/src/infer/expr.rs
Merge #10204
[rust.git] / crates / hir_ty / src / infer / expr.rs
index d535e7f432e3880b7b0d6c63a4ae8bc909ca1713..b0306d9148ae8c1f4e5a7793d0afe5d5134c1301 100644 (file)
@@ -8,10 +8,13 @@
 
 use chalk_ir::{cast::Cast, fold::Shift, Mutability, TyVariableKind};
 use hir_def::{
-    expr::{Array, BinaryOp, Expr, ExprId, Literal, MatchGuard, 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;
@@ -23,7 +26,7 @@
     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,
@@ -60,7 +63,7 @@ pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) ->
     /// 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 let Some(target) = expected.only_has_type(&mut self.table) {
             match self.coerce(Some(expr), &ty, &target) {
                 Ok(res) => res.value,
                 Err(_) => {
@@ -74,9 +77,7 @@ pub(super) fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation)
             }
         } else {
             ty
-        };
-
-        ty
+        }
     }
 
     fn callable_sig_from_fn_trait(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
@@ -327,10 +328,8 @@ fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
                     },
                 );
                 let res = derefs.by_ref().find_map(|(callee_deref_ty, _)| {
-                    self.callable_sig(
-                        &canonicalized.decanonicalize_ty(callee_deref_ty.value),
-                        args.len(),
-                    )
+                    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) => {
@@ -509,17 +508,20 @@ fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
                     },
                 );
                 let ty = autoderef.by_ref().find_map(|(derefed_ty, _)| {
-                    let def_db = self.db.upcast();
                     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)
@@ -636,7 +638,7 @@ fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
                                 },
                             ) {
                                 Some(derefed_ty) => {
-                                    canonicalized.decanonicalize_ty(derefed_ty.value)
+                                    canonicalized.decanonicalize_ty(&mut self.table, derefed_ty)
                                 }
                                 None => self.err_ty(),
                             }
@@ -669,33 +671,21 @@ fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
                 }
             }
             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 } => {
@@ -751,8 +741,9 @@ fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
                         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(),
@@ -861,6 +852,60 @@ fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> 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,
@@ -895,7 +940,7 @@ fn infer_block(
             }
         }
 
-        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,
@@ -914,8 +959,7 @@ fn infer_block(
                 }
                 TyBuilder::unit()
             }
-        };
-        ty
+        }
     }
 
     fn infer_method_call(
@@ -945,7 +989,7 @@ fn infer_method_call(
         });
         let (receiver_ty, method_ty, substs) = match resolved {
             Some((ty, func)) => {
-                let ty = canonicalized_receiver.decanonicalize_ty(ty);
+                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());
@@ -985,21 +1029,21 @@ fn expected_inputs_for_expected_output(
         inputs: Vec<Ty>,
     ) -> Vec<Ty> {
         if let Some(expected_ty) = expected_output.to_option(&mut self.table) {
-            let snapshot = self.table.snapshot();
-            let result = if self.table.try_unify(&expected_ty, &output).is_ok() {
-                // FIXME: the unification could introduce lifetime variables, which we'd need to handle here
-                self.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()
-            };
-            self.table.rollback_to(snapshot);
-            result
+            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()
         }
@@ -1134,4 +1178,141 @@ fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
             }
         }
     }
+
+    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)
+    }
 }