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