]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/floating_point_arithmetic.rs
Lint for x.powi(2) => x * x
[rust.git] / clippy_lints / src / floating_point_arithmetic.rs
1 use crate::consts::{
2     constant, constant_simple, Constant,
3     Constant::{Int, F32, F64},
4 };
5 use crate::utils::{higher, numeric_literal, span_lint_and_sugg, sugg, SpanlessEq};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Spanned;
13
14 use rustc_ast::ast;
15 use std::f32::consts as f32_consts;
16 use std::f64::consts as f64_consts;
17 use sugg::Sugg;
18
19 declare_clippy_lint! {
20     /// **What it does:** Looks for floating-point expressions that
21     /// can be expressed using built-in methods to improve accuracy
22     /// at the cost of performance.
23     ///
24     /// **Why is this bad?** Negatively impacts accuracy.
25     ///
26     /// **Known problems:** None
27     ///
28     /// **Example:**
29     ///
30     /// ```rust
31     /// let a = 3f32;
32     /// let _ = a.powf(1.0 / 3.0);
33     /// let _ = (1.0 + a).ln();
34     /// let _ = a.exp() - 1.0;
35     /// ```
36     ///
37     /// is better expressed as
38     ///
39     /// ```rust
40     /// let a = 3f32;
41     /// let _ = a.cbrt();
42     /// let _ = a.ln_1p();
43     /// let _ = a.exp_m1();
44     /// ```
45     pub IMPRECISE_FLOPS,
46     nursery,
47     "usage of imprecise floating point operations"
48 }
49
50 declare_clippy_lint! {
51     /// **What it does:** Looks for floating-point expressions that
52     /// can be expressed using built-in methods to improve both
53     /// accuracy and performance.
54     ///
55     /// **Why is this bad?** Negatively impacts accuracy and performance.
56     ///
57     /// **Known problems:** None
58     ///
59     /// **Example:**
60     ///
61     /// ```rust
62     /// use std::f32::consts::E;
63     ///
64     /// let a = 3f32;
65     /// let _ = (2f32).powf(a);
66     /// let _ = E.powf(a);
67     /// let _ = a.powf(1.0 / 2.0);
68     /// let _ = a.log(2.0);
69     /// let _ = a.log(10.0);
70     /// let _ = a.log(E);
71     /// let _ = a.powf(2.0);
72     /// let _ = a * 2.0 + 4.0;
73     /// let _ = if a < 0.0 {
74     ///     -a
75     /// } else {
76     ///     a
77     /// };
78     /// let _ = if a < 0.0 {
79     ///     a
80     /// } else {
81     ///     -a
82     /// };
83     /// ```
84     ///
85     /// is better expressed as
86     ///
87     /// ```rust
88     /// use std::f32::consts::E;
89     ///
90     /// let a = 3f32;
91     /// let _ = a.exp2();
92     /// let _ = a.exp();
93     /// let _ = a.sqrt();
94     /// let _ = a.log2();
95     /// let _ = a.log10();
96     /// let _ = a.ln();
97     /// let _ = a.powi(2);
98     /// let _ = a.mul_add(2.0, 4.0);
99     /// let _ = a.abs();
100     /// let _ = -a.abs();
101     /// ```
102     pub SUBOPTIMAL_FLOPS,
103     nursery,
104     "usage of sub-optimal floating point operations"
105 }
106
107 declare_lint_pass!(FloatingPointArithmetic => [
108     IMPRECISE_FLOPS,
109     SUBOPTIMAL_FLOPS
110 ]);
111
112 // Returns the specialized log method for a given base if base is constant
113 // and is one of 2, 10 and e
114 fn get_specialized_log_method(cx: &LateContext<'_>, base: &Expr<'_>) -> Option<&'static str> {
115     if let Some((value, _)) = constant(cx, cx.tables(), base) {
116         if F32(2.0) == value || F64(2.0) == value {
117             return Some("log2");
118         } else if F32(10.0) == value || F64(10.0) == value {
119             return Some("log10");
120         } else if F32(f32_consts::E) == value || F64(f64_consts::E) == value {
121             return Some("ln");
122         }
123     }
124
125     None
126 }
127
128 // Adds type suffixes and parenthesis to method receivers if necessary
129 fn prepare_receiver_sugg<'a>(cx: &LateContext<'_>, mut expr: &'a Expr<'a>) -> Sugg<'a> {
130     let mut suggestion = Sugg::hir(cx, expr, "..");
131
132     if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
133         expr = &inner_expr;
134     }
135
136     if_chain! {
137         // if the expression is a float literal and it is unsuffixed then
138         // add a suffix so the suggestion is valid and unambiguous
139         if let ty::Float(float_ty) = cx.tables().expr_ty(expr).kind;
140         if let ExprKind::Lit(lit) = &expr.kind;
141         if let ast::LitKind::Float(sym, ast::LitFloatType::Unsuffixed) = lit.node;
142         then {
143             let op = format!(
144                 "{}{}{}",
145                 suggestion,
146                 // Check for float literals without numbers following the decimal
147                 // separator such as `2.` and adds a trailing zero
148                 if sym.as_str().ends_with('.') {
149                     "0"
150                 } else {
151                     ""
152                 },
153                 float_ty.name_str()
154             ).into();
155
156             suggestion = match suggestion {
157                 Sugg::MaybeParen(_) => Sugg::MaybeParen(op),
158                 _ => Sugg::NonParen(op)
159             };
160         }
161     }
162
163     suggestion.maybe_par()
164 }
165
166 fn check_log_base(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
167     if let Some(method) = get_specialized_log_method(cx, &args[1]) {
168         span_lint_and_sugg(
169             cx,
170             SUBOPTIMAL_FLOPS,
171             expr.span,
172             "logarithm for bases 2, 10 and e can be computed more accurately",
173             "consider using",
174             format!("{}.{}()", Sugg::hir(cx, &args[0], ".."), method),
175             Applicability::MachineApplicable,
176         );
177     }
178 }
179
180 // TODO: Lint expressions of the form `(x + y).ln()` where y > 1 and
181 // suggest usage of `(x + (y - 1)).ln_1p()` instead
182 fn check_ln1p(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
183     if let ExprKind::Binary(
184         Spanned {
185             node: BinOpKind::Add, ..
186         },
187         lhs,
188         rhs,
189     ) = &args[0].kind
190     {
191         let recv = match (constant(cx, cx.tables(), lhs), constant(cx, cx.tables(), rhs)) {
192             (Some((value, _)), _) if F32(1.0) == value || F64(1.0) == value => rhs,
193             (_, Some((value, _))) if F32(1.0) == value || F64(1.0) == value => lhs,
194             _ => return,
195         };
196
197         span_lint_and_sugg(
198             cx,
199             IMPRECISE_FLOPS,
200             expr.span,
201             "ln(1 + x) can be computed more accurately",
202             "consider using",
203             format!("{}.ln_1p()", prepare_receiver_sugg(cx, recv)),
204             Applicability::MachineApplicable,
205         );
206     }
207 }
208
209 // Returns an integer if the float constant is a whole number and it can be
210 // converted to an integer without loss of precision. For now we only check
211 // ranges [-16777215, 16777216) for type f32 as whole number floats outside
212 // this range are lossy and ambiguous.
213 #[allow(clippy::cast_possible_truncation)]
214 fn get_integer_from_float_constant(value: &Constant) -> Option<i32> {
215     match value {
216         F32(num) if num.fract() == 0.0 => {
217             if (-16_777_215.0..16_777_216.0).contains(num) {
218                 Some(num.round() as i32)
219             } else {
220                 None
221             }
222         },
223         F64(num) if num.fract() == 0.0 => {
224             if (-2_147_483_648.0..2_147_483_648.0).contains(num) {
225                 Some(num.round() as i32)
226             } else {
227                 None
228             }
229         },
230         _ => None,
231     }
232 }
233
234 fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
235     // Check receiver
236     if let Some((value, _)) = constant(cx, cx.tables(), &args[0]) {
237         let method = if F32(f32_consts::E) == value || F64(f64_consts::E) == value {
238             "exp"
239         } else if F32(2.0) == value || F64(2.0) == value {
240             "exp2"
241         } else {
242             return;
243         };
244
245         span_lint_and_sugg(
246             cx,
247             SUBOPTIMAL_FLOPS,
248             expr.span,
249             "exponent for bases 2 and e can be computed more accurately",
250             "consider using",
251             format!("{}.{}()", prepare_receiver_sugg(cx, &args[1]), method),
252             Applicability::MachineApplicable,
253         );
254     }
255
256     // Check argument
257     if let Some((value, _)) = constant(cx, cx.tables(), &args[1]) {
258         let (lint, help, suggestion) = if F32(1.0 / 2.0) == value || F64(1.0 / 2.0) == value {
259             (
260                 SUBOPTIMAL_FLOPS,
261                 "square-root of a number can be computed more efficiently and accurately",
262                 format!("{}.sqrt()", Sugg::hir(cx, &args[0], "..")),
263             )
264         } else if F32(1.0 / 3.0) == value || F64(1.0 / 3.0) == value {
265             (
266                 IMPRECISE_FLOPS,
267                 "cube-root of a number can be computed more accurately",
268                 format!("{}.cbrt()", Sugg::hir(cx, &args[0], "..")),
269             )
270         } else if let Some(exponent) = get_integer_from_float_constant(&value) {
271             (
272                 SUBOPTIMAL_FLOPS,
273                 "exponentiation with integer powers can be computed more efficiently",
274                 format!(
275                     "{}.powi({})",
276                     Sugg::hir(cx, &args[0], ".."),
277                     numeric_literal::format(&exponent.to_string(), None, false)
278                 ),
279             )
280         } else {
281             return;
282         };
283
284         span_lint_and_sugg(
285             cx,
286             lint,
287             expr.span,
288             help,
289             "consider using",
290             suggestion,
291             Applicability::MachineApplicable,
292         );
293     }
294 }
295
296 fn check_powi(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
297     // Check argument
298     if let Some((value, _)) = constant(cx, cx.tables, &args[1]) {
299         let (lint, help, suggestion) = match value {
300             Int(2) => (
301                 IMPRECISE_FLOPS,
302                 "square can be computed more accurately",
303                 format!("{} * {}", Sugg::hir(cx, &args[0], ".."), Sugg::hir(cx, &args[0], "..")),
304             ),
305             _ => return,
306         };
307
308         span_lint_and_sugg(
309             cx,
310             lint,
311             expr.span,
312             help,
313             "consider using",
314             suggestion,
315             Applicability::MachineApplicable,
316         );
317     }
318 }
319
320 // TODO: Lint expressions of the form `x.exp() - y` where y > 1
321 // and suggest usage of `x.exp_m1() - (y - 1)` instead
322 fn check_expm1(cx: &LateContext<'_>, expr: &Expr<'_>) {
323     if_chain! {
324         if let ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, ref lhs, ref rhs) = expr.kind;
325         if cx.tables().expr_ty(lhs).is_floating_point();
326         if let Some((value, _)) = constant(cx, cx.tables(), rhs);
327         if F32(1.0) == value || F64(1.0) == value;
328         if let ExprKind::MethodCall(ref path, _, ref method_args, _) = lhs.kind;
329         if cx.tables().expr_ty(&method_args[0]).is_floating_point();
330         if path.ident.name.as_str() == "exp";
331         then {
332             span_lint_and_sugg(
333                 cx,
334                 IMPRECISE_FLOPS,
335                 expr.span,
336                 "(e.pow(x) - 1) can be computed more accurately",
337                 "consider using",
338                 format!(
339                     "{}.exp_m1()",
340                     Sugg::hir(cx, &method_args[0], "..")
341                 ),
342                 Applicability::MachineApplicable,
343             );
344         }
345     }
346 }
347
348 fn is_float_mul_expr<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
349     if_chain! {
350         if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, ref lhs, ref rhs) = &expr.kind;
351         if cx.tables().expr_ty(lhs).is_floating_point();
352         if cx.tables().expr_ty(rhs).is_floating_point();
353         then {
354             return Some((lhs, rhs));
355         }
356     }
357
358     None
359 }
360
361 // TODO: Fix rust-lang/rust-clippy#4735
362 fn check_mul_add(cx: &LateContext<'_>, expr: &Expr<'_>) {
363     if let ExprKind::Binary(
364         Spanned {
365             node: BinOpKind::Add, ..
366         },
367         lhs,
368         rhs,
369     ) = &expr.kind
370     {
371         let (recv, arg1, arg2) = if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, lhs) {
372             (inner_lhs, inner_rhs, rhs)
373         } else if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, rhs) {
374             (inner_lhs, inner_rhs, lhs)
375         } else {
376             return;
377         };
378
379         span_lint_and_sugg(
380             cx,
381             SUBOPTIMAL_FLOPS,
382             expr.span,
383             "multiply and add expressions can be calculated more efficiently and accurately",
384             "consider using",
385             format!(
386                 "{}.mul_add({}, {})",
387                 prepare_receiver_sugg(cx, recv),
388                 Sugg::hir(cx, arg1, ".."),
389                 Sugg::hir(cx, arg2, ".."),
390             ),
391             Applicability::MachineApplicable,
392         );
393     }
394 }
395
396 /// Returns true iff expr is an expression which tests whether or not
397 /// test is positive or an expression which tests whether or not test
398 /// is nonnegative.
399 /// Used for check-custom-abs function below
400 fn is_testing_positive(cx: &LateContext<'_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
401     if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
402         match op {
403             BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, right) && are_exprs_equal(cx, left, test),
404             BinOpKind::Lt | BinOpKind::Le => is_zero(cx, left) && are_exprs_equal(cx, right, test),
405             _ => false,
406         }
407     } else {
408         false
409     }
410 }
411
412 /// See [`is_testing_positive`]
413 fn is_testing_negative(cx: &LateContext<'_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
414     if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
415         match op {
416             BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, left) && are_exprs_equal(cx, right, test),
417             BinOpKind::Lt | BinOpKind::Le => is_zero(cx, right) && are_exprs_equal(cx, left, test),
418             _ => false,
419         }
420     } else {
421         false
422     }
423 }
424
425 fn are_exprs_equal(cx: &LateContext<'_>, expr1: &Expr<'_>, expr2: &Expr<'_>) -> bool {
426     SpanlessEq::new(cx).ignore_fn().eq_expr(expr1, expr2)
427 }
428
429 /// Returns true iff expr is some zero literal
430 fn is_zero(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
431     match constant_simple(cx, cx.tables(), expr) {
432         Some(Constant::Int(i)) => i == 0,
433         Some(Constant::F32(f)) => f == 0.0,
434         Some(Constant::F64(f)) => f == 0.0,
435         _ => false,
436     }
437 }
438
439 /// If the two expressions are negations of each other, then it returns
440 /// a tuple, in which the first element is true iff expr1 is the
441 /// positive expressions, and the second element is the positive
442 /// one of the two expressions
443 /// If the two expressions are not negations of each other, then it
444 /// returns None.
445 fn are_negated<'a>(cx: &LateContext<'_>, expr1: &'a Expr<'a>, expr2: &'a Expr<'a>) -> Option<(bool, &'a Expr<'a>)> {
446     if let ExprKind::Unary(UnOp::UnNeg, expr1_negated) = &expr1.kind {
447         if are_exprs_equal(cx, expr1_negated, expr2) {
448             return Some((false, expr2));
449         }
450     }
451     if let ExprKind::Unary(UnOp::UnNeg, expr2_negated) = &expr2.kind {
452         if are_exprs_equal(cx, expr1, expr2_negated) {
453             return Some((true, expr1));
454         }
455     }
456     None
457 }
458
459 fn check_custom_abs(cx: &LateContext<'_>, expr: &Expr<'_>) {
460     if_chain! {
461         if let Some((cond, body, Some(else_body))) = higher::if_block(&expr);
462         if let ExprKind::Block(block, _) = body.kind;
463         if block.stmts.is_empty();
464         if let Some(if_body_expr) = block.expr;
465         if let ExprKind::Block(else_block, _) = else_body.kind;
466         if else_block.stmts.is_empty();
467         if let Some(else_body_expr) = else_block.expr;
468         if let Some((if_expr_positive, body)) = are_negated(cx, if_body_expr, else_body_expr);
469         then {
470             let positive_abs_sugg = (
471                 "manual implementation of `abs` method",
472                 format!("{}.abs()", Sugg::hir(cx, body, "..")),
473             );
474             let negative_abs_sugg = (
475                 "manual implementation of negation of `abs` method",
476                 format!("-{}.abs()", Sugg::hir(cx, body, "..")),
477             );
478             let sugg = if is_testing_positive(cx, cond, body) {
479                 if if_expr_positive {
480                     positive_abs_sugg
481                 } else {
482                     negative_abs_sugg
483                 }
484             } else if is_testing_negative(cx, cond, body) {
485                 if if_expr_positive {
486                     negative_abs_sugg
487                 } else {
488                     positive_abs_sugg
489                 }
490             } else {
491                 return;
492             };
493             span_lint_and_sugg(
494                 cx,
495                 SUBOPTIMAL_FLOPS,
496                 expr.span,
497                 sugg.0,
498                 "try",
499                 sugg.1,
500                 Applicability::MachineApplicable,
501             );
502         }
503     }
504 }
505
506 impl<'tcx> LateLintPass<'tcx> for FloatingPointArithmetic {
507     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
508         if let ExprKind::MethodCall(ref path, _, args, _) = &expr.kind {
509             let recv_ty = cx.tables().expr_ty(&args[0]);
510
511             if recv_ty.is_floating_point() {
512                 match &*path.ident.name.as_str() {
513                     "ln" => check_ln1p(cx, expr, args),
514                     "log" => check_log_base(cx, expr, args),
515                     "powf" => check_powf(cx, expr, args),
516                     "powi" => check_powi(cx, expr, args),
517                     _ => {},
518                 }
519             }
520         } else {
521             check_expm1(cx, expr);
522             check_mul_add(cx, expr);
523             check_custom_abs(cx, expr);
524         }
525     }
526 }