Skip to content

Commit 16fd2a8

Browse files
authored
Fix integer_division false negative for NonZero denominators (#14664)
Close #14652 changelog: [`integer_division`]: fix false negative for NonZero denominators
2 parents a67ee90 + 1fbfbb5 commit 16fd2a8

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

clippy_lints/src/operators/integer_division.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use clippy_utils::diagnostics::span_lint_and_then;
2+
use clippy_utils::ty::is_type_diagnostic_item;
23
use rustc_hir as hir;
34
use rustc_lint::LateContext;
5+
use rustc_span::symbol::sym;
46

57
use super::INTEGER_DIVISION;
68

@@ -13,7 +15,8 @@ pub(crate) fn check<'tcx>(
1315
) {
1416
if op == hir::BinOpKind::Div
1517
&& cx.typeck_results().expr_ty(left).is_integral()
16-
&& cx.typeck_results().expr_ty(right).is_integral()
18+
&& let right_ty = cx.typeck_results().expr_ty(right)
19+
&& (right_ty.is_integral() || is_type_diagnostic_item(cx, right_ty, sym::NonZero))
1720
{
1821
#[expect(clippy::collapsible_span_lint_calls, reason = "rust-clippy#7797")]
1922
span_lint_and_then(cx, INTEGER_DIVISION, expr.span, "integer division", |diag| {

tests/ui/integer_division.rs

+8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
#![warn(clippy::integer_division)]
22

3+
use std::num::NonZeroU32;
4+
5+
const TWO: NonZeroU32 = NonZeroU32::new(2).unwrap();
6+
37
fn main() {
48
let two = 2;
59
let n = 1 / 2;
@@ -12,4 +16,8 @@ fn main() {
1216
//~^ integer_division
1317

1418
let x = 1. / 2.0;
19+
20+
let a = 1;
21+
let s = a / TWO;
22+
//~^ integer_division
1523
}

tests/ui/integer_division.stderr

+12-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: integer division
2-
--> tests/ui/integer_division.rs:5:13
2+
--> tests/ui/integer_division.rs:9:13
33
|
44
LL | let n = 1 / 2;
55
| ^^^^^
@@ -9,20 +9,28 @@ LL | let n = 1 / 2;
99
= help: to override `-D warnings` add `#[allow(clippy::integer_division)]`
1010

1111
error: integer division
12-
--> tests/ui/integer_division.rs:8:13
12+
--> tests/ui/integer_division.rs:12:13
1313
|
1414
LL | let o = 1 / two;
1515
| ^^^^^^^
1616
|
1717
= help: division of integers may cause loss of precision. consider using floats
1818

1919
error: integer division
20-
--> tests/ui/integer_division.rs:11:13
20+
--> tests/ui/integer_division.rs:15:13
2121
|
2222
LL | let p = two / 4;
2323
| ^^^^^^^
2424
|
2525
= help: division of integers may cause loss of precision. consider using floats
2626

27-
error: aborting due to 3 previous errors
27+
error: integer division
28+
--> tests/ui/integer_division.rs:21:13
29+
|
30+
LL | let s = a / TWO;
31+
| ^^^^^^^
32+
|
33+
= help: division of integers may cause loss of precision. consider using floats
34+
35+
error: aborting due to 4 previous errors
2836

0 commit comments

Comments
 (0)