2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_lint_pass, declare_tool_lint};
4 use rustc_errors::Applicability;
9 /// **What it does:** Checks for expressions of the form `a * b + c`
10 /// or `c + a * b` where `a`, `b`, `c` are floats and suggests using
11 /// `a.mul_add(b, c)` instead.
13 /// **Why is this bad?** Calculating `a * b + c` may lead to slight
14 /// numerical inaccuracies as `a * b` is rounded before being added to
15 /// `c`. Depending on the target architecture, `mul_add()` may be more
18 /// **Known problems:** This lint can emit semantic incorrect suggestions.
19 /// For example, for `a * b * c + d` the suggestion `a * b.mul_add(c, d)`
20 /// is emitted, which is equivalent to `a * (b * c + d)`. (#4735)
28 /// let foo = (a * b) + c;
37 /// let foo = a.mul_add(b, c);
41 "Using `a.mul_add(b, c)` for floating points has higher numerical precision than `a * b + c`"
44 declare_lint_pass!(MulAddCheck => [MANUAL_MUL_ADD]);
46 fn is_float<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr) -> bool {
47 cx.tables.expr_ty(expr).is_floating_point()
50 // Checks whether expression is multiplication of two floats
51 fn is_float_mult_expr<'a, 'tcx, 'b>(cx: &LateContext<'a, 'tcx>, expr: &'b Expr) -> Option<(&'b Expr, &'b Expr)> {
52 if let ExprKind::Binary(op, lhs, rhs) = &expr.kind {
53 if let BinOpKind::Mul = op.node {
54 if is_float(cx, &lhs) && is_float(cx, &rhs) {
55 return Some((&lhs, &rhs));
63 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MulAddCheck {
64 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
65 if let ExprKind::Binary(op, lhs, rhs) = &expr.kind {
66 if let BinOpKind::Add = op.node {
67 //Converts mult_lhs * mult_rhs + rhs to mult_lhs.mult_add(mult_rhs, rhs)
68 if let Some((mult_lhs, mult_rhs)) = is_float_mult_expr(cx, lhs) {
69 if is_float(cx, rhs) {
74 "consider using mul_add() for better numerical precision",
78 snippet(cx, mult_lhs.span, "_"),
79 snippet(cx, mult_rhs.span, "_"),
80 snippet(cx, rhs.span, "_"),
82 Applicability::MaybeIncorrect,
86 //Converts lhs + mult_lhs * mult_rhs to mult_lhs.mult_add(mult_rhs, lhs)
87 if let Some((mult_lhs, mult_rhs)) = is_float_mult_expr(cx, rhs) {
88 if is_float(cx, lhs) {
93 "consider using mul_add() for better numerical precision",
97 snippet(cx, mult_lhs.span, "_"),
98 snippet(cx, mult_rhs.span, "_"),
99 snippet(cx, lhs.span, "_"),
101 Applicability::MaybeIncorrect,