1 mod absurd_extreme_comparisons;
11 mod float_equality_without_abs;
14 mod misrefactored_assign_op;
15 mod modulo_arithmetic;
17 mod needless_bitwise_bool;
18 mod numeric_arithmetic;
24 pub(crate) mod arithmetic_side_effects;
26 use rustc_hir::{Body, Expr, ExprKind, UnOp};
27 use rustc_lint::{LateContext, LateLintPass};
28 use rustc_session::{declare_tool_lint, impl_lint_pass};
30 declare_clippy_lint! {
32 /// Checks for comparisons where one side of the relation is
33 /// either the minimum or maximum value for its type and warns if it involves a
34 /// case that is always true or always false. Only integer and boolean types are
37 /// ### Why is this bad?
38 /// An expression like `min <= x` may misleadingly imply
39 /// that it is possible for `x` to be less than the minimum. Expressions like
40 /// `max < x` are probably mistakes.
42 /// ### Known problems
43 /// For `usize` the size of the current compile target will
44 /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
45 /// a comparison to detect target pointer width will trigger this lint. One can
46 /// use `mem::sizeof` and compare its value or conditional compilation
48 /// like `#[cfg(target_pointer_width = "64")] ..` instead.
52 /// let vec: Vec<isize> = Vec::new();
53 /// if vec.len() <= 0 {}
54 /// if 100 > i32::MAX {}
56 #[clippy::version = "pre 1.29.0"]
57 pub ABSURD_EXTREME_COMPARISONS,
59 "a comparison with a maximum or minimum value that is always true or false"
62 declare_clippy_lint! {
64 /// Checks any kind of arithmetic operation of any type.
66 /// Operators like `+`, `-`, `*` or `<<` are usually capable of overflowing according to the [Rust
67 /// Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow),
68 /// or can panic (`/`, `%`).
70 /// Known safe built-in types like `Wrapping` or `Saturating`, floats, operations in constant
71 /// environments, allowed types and non-constant operations that won't overflow are ignored.
73 /// ### Why is this bad?
74 /// For integers, overflow will trigger a panic in debug builds or wrap the result in
75 /// release mode; division by zero will cause a panic in either mode. As a result, it is
76 /// desirable to explicitly call checked, wrapping or saturating arithmetic methods.
80 /// // `n` can be any number, including `i32::MAX`.
81 /// fn foo(n: i32) -> i32 {
86 /// Third-party types can also overflow or present unwanted side-effects.
90 /// use rust_decimal::Decimal;
91 /// let _n = Decimal::MAX + Decimal::MAX;
93 #[clippy::version = "1.64.0"]
94 pub ARITHMETIC_SIDE_EFFECTS,
96 "any arithmetic expression that can cause side effects like overflows or panics"
99 declare_clippy_lint! {
101 /// Checks for integer arithmetic operations which could overflow or panic.
103 /// Specifically, checks for any operators (`+`, `-`, `*`, `<<`, etc) which are capable
104 /// of overflowing according to the [Rust
105 /// Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow),
106 /// or which can panic (`/`, `%`). No bounds analysis or sophisticated reasoning is
109 /// ### Why is this bad?
110 /// Integer overflow will trigger a panic in debug builds or will wrap in
111 /// release mode. Division by zero will cause a panic in either mode. In some applications one
112 /// wants explicitly checked, wrapping or saturating arithmetic.
119 #[clippy::version = "pre 1.29.0"]
120 pub INTEGER_ARITHMETIC,
122 "any integer arithmetic expression which could overflow or panic"
125 declare_clippy_lint! {
127 /// Checks for float arithmetic.
129 /// ### Why is this bad?
130 /// For some embedded systems or kernel development, it
131 /// can be useful to rule out floating-point numbers.
138 #[clippy::version = "pre 1.29.0"]
139 pub FLOAT_ARITHMETIC,
141 "any floating-point arithmetic statement"
144 declare_clippy_lint! {
146 /// Checks for `a = a op b` or `a = b commutative_op a`
149 /// ### Why is this bad?
150 /// These can be written as the shorter `a op= b`.
152 /// ### Known problems
153 /// While forbidden by the spec, `OpAssign` traits may have
154 /// implementations that differ from the regular `Op` impl.
173 #[clippy::version = "pre 1.29.0"]
174 pub ASSIGN_OP_PATTERN,
176 "assigning the result of an operation on a variable to that same variable"
179 declare_clippy_lint! {
181 /// Checks for `a op= a op b` or `a op= b op a` patterns.
183 /// ### Why is this bad?
184 /// Most likely these are bugs where one meant to write `a
187 /// ### Known problems
188 /// Clippy cannot know for sure if `a op= a op b` should have
189 /// been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore, it suggests both.
190 /// If `a op= a op b` is really the correct behavior it should be
191 /// written as `a = a op a op b` as it's less confusing.
200 #[clippy::version = "pre 1.29.0"]
201 pub MISREFACTORED_ASSIGN_OP,
203 "having a variable on both sides of an assign op"
206 declare_clippy_lint! {
208 /// Checks for incompatible bit masks in comparisons.
210 /// The formula for detecting if an expression of the type `_ <bit_op> m
211 /// <cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of
212 /// {`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following
215 /// |Comparison |Bit Op|Example |is always|Formula |
216 /// |------------|------|-------------|---------|----------------------|
217 /// |`==` or `!=`| `&` |`x & 2 == 3` |`false` |`c & m != c` |
218 /// |`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` |
219 /// |`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` |
220 /// |`==` or `!=`| `\|` |`x \| 1 == 0`|`false` |`c \| m != c` |
221 /// |`<` or `>=`| `\|` |`x \| 1 < 1` |`false` |`m >= c` |
222 /// |`<=` or `>` | `\|` |`x \| 1 > 0` |`true` |`m > c` |
224 /// ### Why is this bad?
225 /// If the bits that the comparison cares about are always
226 /// set to zero or one by the bit mask, the comparison is constant `true` or
227 /// `false` (depending on mask, compared value, and operators).
229 /// So the code is actively misleading, and the only reason someone would write
230 /// this intentionally is to win an underhanded Rust contest or create a
231 /// test-case for this lint.
236 /// if (x & 1 == 2) { }
238 #[clippy::version = "pre 1.29.0"]
241 "expressions of the form `_ & mask == select` that will only ever return `true` or `false`"
244 declare_clippy_lint! {
246 /// Checks for bit masks in comparisons which can be removed
247 /// without changing the outcome. The basic structure can be seen in the
250 /// |Comparison| Bit Op |Example |equals |
251 /// |----------|----------|------------|-------|
252 /// |`>` / `<=`|`\|` / `^`|`x \| 2 > 3`|`x > 3`|
253 /// |`<` / `>=`|`\|` / `^`|`x ^ 1 < 4` |`x < 4`|
255 /// ### Why is this bad?
256 /// Not equally evil as [`bad_bit_mask`](#bad_bit_mask),
257 /// but still a bit misleading, because the bit mask is ineffective.
259 /// ### Known problems
260 /// False negatives: This lint will only match instances
261 /// where we have figured out the math (which is for a power-of-two compared
262 /// value). This means things like `x | 1 >= 7` (which would be better written
263 /// as `x >= 6`) will not be reported (but bit masks like this are fairly
269 /// if (x | 1 > 3) { }
271 #[clippy::version = "pre 1.29.0"]
272 pub INEFFECTIVE_BIT_MASK,
274 "expressions where a bit mask will be rendered useless by a comparison, e.g., `(x | 1) > 2`"
277 declare_clippy_lint! {
279 /// Checks for bit masks that can be replaced by a call
280 /// to `trailing_zeros`
282 /// ### Why is this bad?
283 /// `x.trailing_zeros() > 4` is much clearer than `x & 15
286 /// ### Known problems
287 /// llvm generates better code for `x & 15 == 0` on x86
292 /// if x & 0b1111 == 0 { }
294 #[clippy::version = "pre 1.29.0"]
295 pub VERBOSE_BIT_MASK,
297 "expressions where a bit mask is less readable than the corresponding method call"
300 declare_clippy_lint! {
302 /// Checks for double comparisons that could be simplified to a single expression.
305 /// ### Why is this bad?
312 /// if x == y || x < y {}
322 #[clippy::version = "pre 1.29.0"]
323 pub DOUBLE_COMPARISONS,
325 "unnecessary double comparisons that can be simplified"
328 declare_clippy_lint! {
330 /// Checks for calculation of subsecond microseconds or milliseconds
331 /// from other `Duration` methods.
333 /// ### Why is this bad?
334 /// It's more concise to call `Duration::subsec_micros()` or
335 /// `Duration::subsec_millis()` than to calculate them.
339 /// # use std::time::Duration;
340 /// # let duration = Duration::new(5, 0);
341 /// let micros = duration.subsec_nanos() / 1_000;
342 /// let millis = duration.subsec_nanos() / 1_000_000;
347 /// # use std::time::Duration;
348 /// # let duration = Duration::new(5, 0);
349 /// let micros = duration.subsec_micros();
350 /// let millis = duration.subsec_millis();
352 #[clippy::version = "pre 1.29.0"]
355 "checks for calculation of subsecond microseconds or milliseconds"
358 declare_clippy_lint! {
360 /// Checks for equal operands to comparison, logical and
361 /// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,
362 /// `||`, `&`, `|`, `^`, `-` and `/`).
364 /// ### Why is this bad?
365 /// This is usually just a typo or a copy and paste error.
367 /// ### Known problems
368 /// False negatives: We had some false positives regarding
369 /// calls (notably [racer](https://github.com/phildawes/racer) had one instance
370 /// of `x.pop() && x.pop()`), so we removed matching any function or method
371 /// calls. We may introduce a list of known pure functions in the future.
376 /// if x + 1 == x + 1 {}
382 /// assert_eq!(a, a);
384 #[clippy::version = "pre 1.29.0"]
387 "equal operands on both sides of a comparison or bitwise combination (e.g., `x == x`)"
390 declare_clippy_lint! {
392 /// Checks for arguments to `==` which have their address
393 /// taken to satisfy a bound
394 /// and suggests to dereference the other argument instead
396 /// ### Why is this bad?
397 /// It is more idiomatic to dereference the other argument.
408 #[clippy::version = "pre 1.29.0"]
411 "taking a reference to satisfy the type constraints on `==`"
414 declare_clippy_lint! {
416 /// Checks for erasing operations, e.g., `x * 0`.
418 /// ### Why is this bad?
419 /// The whole expression can be replaced by zero.
420 /// This is most likely not the intended outcome and should probably be
430 #[clippy::version = "pre 1.29.0"]
433 "using erasing operations, e.g., `x * 0` or `y & 0`"
436 declare_clippy_lint! {
438 /// Checks for statements of the form `(a - b) < f32::EPSILON` or
439 /// `(a - b) < f64::EPSILON`. Notes the missing `.abs()`.
441 /// ### Why is this bad?
442 /// The code without `.abs()` is more likely to have a bug.
444 /// ### Known problems
445 /// If the user can ensure that b is larger than a, the `.abs()` is
446 /// technically unnecessary. However, it will make the code more robust and doesn't have any
447 /// large performance implications. If the abs call was deliberately left out for performance
448 /// reasons, it is probably better to state this explicitly in the code, which then can be done
453 /// pub fn is_roughly_equal(a: f32, b: f32) -> bool {
454 /// (a - b) < f32::EPSILON
459 /// pub fn is_roughly_equal(a: f32, b: f32) -> bool {
460 /// (a - b).abs() < f32::EPSILON
463 #[clippy::version = "1.48.0"]
464 pub FLOAT_EQUALITY_WITHOUT_ABS,
466 "float equality check without `.abs()`"
469 declare_clippy_lint! {
471 /// Checks for identity operations, e.g., `x + 0`.
473 /// ### Why is this bad?
474 /// This code can be removed without changing the
475 /// meaning. So it just obscures what's going on. Delete it mercilessly.
480 /// x / 1 + 0 * 1 - 0 | 0;
482 #[clippy::version = "pre 1.29.0"]
485 "using identity operations, e.g., `x + 0` or `y / 1`"
488 declare_clippy_lint! {
490 /// Checks for division of integers
492 /// ### Why is this bad?
493 /// When outside of some very specific algorithms,
494 /// integer division is very often a mistake because it discards the
500 /// println!("{}", x);
505 /// let x = 3f32 / 2f32;
506 /// println!("{}", x);
508 #[clippy::version = "1.37.0"]
509 pub INTEGER_DIVISION,
511 "integer division may cause loss of precision"
514 declare_clippy_lint! {
516 /// Checks for comparisons to NaN.
518 /// ### Why is this bad?
519 /// NaN does not compare meaningfully to anything – not
520 /// even itself – so those comparisons are simply wrong.
525 /// if x == f32::NAN { }
530 /// # let x = 1.0f32;
531 /// if x.is_nan() { }
533 #[clippy::version = "pre 1.29.0"]
536 "comparisons to `NAN`, which will always return false, probably not intended"
539 declare_clippy_lint! {
541 /// Checks for conversions to owned values just for the sake
544 /// ### Why is this bad?
545 /// The comparison can operate on a reference, so creating
546 /// an owned value effectively throws it away directly afterwards, which is
547 /// needlessly consuming code and heap space.
552 /// # let y = String::from("foo");
553 /// if x.to_owned() == y {}
559 /// # let y = String::from("foo");
562 #[clippy::version = "pre 1.29.0"]
565 "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`"
568 declare_clippy_lint! {
570 /// Checks for (in-)equality comparisons on floating-point
571 /// values (apart from zero), except in functions called `*eq*` (which probably
572 /// implement equality for a type involving floats).
574 /// ### Why is this bad?
575 /// Floating point calculations are usually imprecise, so
576 /// asking if two values are *exactly* equal is asking for trouble. For a good
577 /// guide on what to do, see [the floating point
578 /// guide](http://www.floating-point-gui.de/errors/comparison).
582 /// let x = 1.2331f64;
583 /// let y = 1.2332f64;
585 /// if y == 1.23f64 { }
586 /// if y != x {} // where both are floats
591 /// # let x = 1.2331f64;
592 /// # let y = 1.2332f64;
593 /// let error_margin = f64::EPSILON; // Use an epsilon for comparison
594 /// // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.
595 /// // let error_margin = std::f64::EPSILON;
596 /// if (y - 1.23f64).abs() < error_margin { }
597 /// if (y - x).abs() > error_margin { }
599 #[clippy::version = "pre 1.29.0"]
602 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
605 declare_clippy_lint! {
607 /// Checks for (in-)equality comparisons on floating-point
608 /// value and constant, except in functions called `*eq*` (which probably
609 /// implement equality for a type involving floats).
611 /// ### Why is this bad?
612 /// Floating point calculations are usually imprecise, so
613 /// asking if two values are *exactly* equal is asking for trouble. For a good
614 /// guide on what to do, see [the floating point
615 /// guide](http://www.floating-point-gui.de/errors/comparison).
619 /// let x: f64 = 1.0;
620 /// const ONE: f64 = 1.00;
622 /// if x == ONE { } // where both are floats
627 /// # let x: f64 = 1.0;
628 /// # const ONE: f64 = 1.00;
629 /// let error_margin = f64::EPSILON; // Use an epsilon for comparison
630 /// // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.
631 /// // let error_margin = std::f64::EPSILON;
632 /// if (x - ONE).abs() < error_margin { }
634 #[clippy::version = "pre 1.29.0"]
637 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
640 declare_clippy_lint! {
642 /// Checks for getting the remainder of a division by one or minus
645 /// ### Why is this bad?
646 /// The result for a divisor of one can only ever be zero; for
647 /// minus one it can cause panic/overflow (if the left operand is the minimal value of
648 /// the respective integer type) or results in zero. No one will write such code
649 /// deliberately, unless trying to win an Underhanded Rust Contest. Even for that
650 /// contest, it's probably a bad idea. Use something more underhanded.
658 #[clippy::version = "pre 1.29.0"]
661 "taking a number modulo +/-1, which can either panic/overflow or always returns 0"
664 declare_clippy_lint! {
666 /// Checks for modulo arithmetic.
668 /// ### Why is this bad?
669 /// The results of modulo (%) operation might differ
670 /// depending on the language, when negative numbers are involved.
671 /// If you interop with different languages it might be beneficial
672 /// to double check all places that use modulo arithmetic.
674 /// For example, in Rust `17 % -3 = 2`, but in Python `17 % -3 = -1`.
680 #[clippy::version = "1.42.0"]
681 pub MODULO_ARITHMETIC,
683 "any modulo arithmetic statement"
686 declare_clippy_lint! {
688 /// Checks for uses of bitwise and/or operators between booleans, where performance may be improved by using
691 /// ### Why is this bad?
692 /// The bitwise operators do not support short-circuiting, so it may hinder code performance.
693 /// Additionally, boolean logic "masked" as bitwise logic is not caught by lints like `unnecessary_fold`
695 /// ### Known problems
696 /// This lint evaluates only when the right side is determined to have no side effects. At this time, that
697 /// determination is quite conservative.
701 /// let (x,y) = (true, false);
702 /// if x & !y {} // where both x and y are booleans
706 /// let (x,y) = (true, false);
709 #[clippy::version = "1.54.0"]
710 pub NEEDLESS_BITWISE_BOOL,
712 "Boolean expressions that use bitwise rather than lazy operators"
715 declare_clippy_lint! {
717 /// Use `std::ptr::eq` when applicable
719 /// ### Why is this bad?
720 /// `ptr::eq` can be used to compare `&T` references
721 /// (which coerce to `*const T` implicitly) by their address rather than
722 /// comparing the values they point to.
726 /// let a = &[1, 2, 3];
727 /// let b = &[1, 2, 3];
729 /// assert!(a as *const _ as usize == b as *const _ as usize);
733 /// let a = &[1, 2, 3];
734 /// let b = &[1, 2, 3];
736 /// assert!(std::ptr::eq(a, b));
738 #[clippy::version = "1.49.0"]
741 "use `std::ptr::eq` when comparing raw pointers"
744 declare_clippy_lint! {
746 /// Checks for explicit self-assignments.
748 /// ### Why is this bad?
749 /// Self-assignments are redundant and unlikely to be
752 /// ### Known problems
753 /// If expression contains any deref coercions or
754 /// indexing operations they are assumed not to have any side effects.
762 /// fn copy_position(a: &mut Event, b: &Event) {
773 /// fn copy_position(a: &mut Event, b: &Event) {
777 #[clippy::version = "1.48.0"]
780 "explicit self-assignment"
783 pub struct Operators {
784 arithmetic_context: numeric_arithmetic::Context,
785 verbose_bit_mask_threshold: u64,
787 impl_lint_pass!(Operators => [
788 ABSURD_EXTREME_COMPARISONS,
789 ARITHMETIC_SIDE_EFFECTS,
793 MISREFACTORED_ASSIGN_OP,
795 INEFFECTIVE_BIT_MASK,
802 FLOAT_EQUALITY_WITHOUT_ABS,
811 NEEDLESS_BITWISE_BOOL,
816 pub fn new(verbose_bit_mask_threshold: u64) -> Self {
818 arithmetic_context: numeric_arithmetic::Context::default(),
819 verbose_bit_mask_threshold,
823 impl<'tcx> LateLintPass<'tcx> for Operators {
824 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
825 eq_op::check_assert(cx, e);
827 ExprKind::Binary(op, lhs, rhs) => {
828 if !e.span.from_expansion() {
829 absurd_extreme_comparisons::check(cx, e, op.node, lhs, rhs);
830 if !(macro_with_not_op(lhs) || macro_with_not_op(rhs)) {
831 eq_op::check(cx, e, op.node, lhs, rhs);
832 op_ref::check(cx, e, op.node, lhs, rhs);
834 erasing_op::check(cx, e, op.node, lhs, rhs);
835 identity_op::check(cx, e, op.node, lhs, rhs);
836 needless_bitwise_bool::check(cx, e, op.node, lhs, rhs);
837 ptr_eq::check(cx, e, op.node, lhs, rhs);
839 self.arithmetic_context.check_binary(cx, e, op.node, lhs, rhs);
840 bit_mask::check(cx, e, op.node, lhs, rhs);
841 verbose_bit_mask::check(cx, e, op.node, lhs, rhs, self.verbose_bit_mask_threshold);
842 double_comparison::check(cx, op.node, lhs, rhs, e.span);
843 duration_subsec::check(cx, e, op.node, lhs, rhs);
844 float_equality_without_abs::check(cx, e, op.node, lhs, rhs);
845 integer_division::check(cx, e, op.node, lhs, rhs);
846 cmp_nan::check(cx, e, op.node, lhs, rhs);
847 cmp_owned::check(cx, op.node, lhs, rhs);
848 float_cmp::check(cx, e, op.node, lhs, rhs);
849 modulo_one::check(cx, e, op.node, rhs);
850 modulo_arithmetic::check(cx, e, op.node, lhs, rhs);
852 ExprKind::AssignOp(op, lhs, rhs) => {
853 self.arithmetic_context.check_binary(cx, e, op.node, lhs, rhs);
854 misrefactored_assign_op::check(cx, e, op.node, lhs, rhs);
855 modulo_arithmetic::check(cx, e, op.node, lhs, rhs);
857 ExprKind::Assign(lhs, rhs, _) => {
858 assign_op_pattern::check(cx, e, lhs, rhs);
859 self_assignment::check(cx, e, lhs, rhs);
861 ExprKind::Unary(op, arg) => {
863 self.arithmetic_context.check_negate(cx, e, arg);
870 fn check_expr_post(&mut self, _: &LateContext<'_>, e: &Expr<'_>) {
871 self.arithmetic_context.expr_post(e.hir_id);
874 fn check_body(&mut self, cx: &LateContext<'tcx>, b: &'tcx Body<'_>) {
875 self.arithmetic_context.enter_body(cx, b);
878 fn check_body_post(&mut self, cx: &LateContext<'tcx>, b: &'tcx Body<'_>) {
879 self.arithmetic_context.body_post(cx, b);
883 fn macro_with_not_op(e: &Expr<'_>) -> bool {
884 if let ExprKind::Unary(_, e) = e.kind {
885 e.span.from_expansion()