Skip to content

Commit 71b6776

Browse files
committed
New lint: manual_midpoint
1 parent 0aa03e1 commit 71b6776

15 files changed

+309
-27
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -5761,6 +5761,7 @@ Released 2018-09-13
57615761
[`manual_main_separator_str`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_main_separator_str
57625762
[`manual_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_map
57635763
[`manual_memcpy`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_memcpy
5764+
[`manual_midpoint`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_midpoint
57645765
[`manual_next_back`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_next_back
57655766
[`manual_non_exhaustive`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_non_exhaustive
57665767
[`manual_ok_err`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_ok_err

book/src/lint_configuration.md

+1
Original file line numberDiff line numberDiff line change
@@ -746,6 +746,7 @@ The minimum rust version that the project supports. Defaults to the `rust-versio
746746
* [`manual_hash_one`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_hash_one)
747747
* [`manual_is_ascii_check`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_is_ascii_check)
748748
* [`manual_let_else`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_let_else)
749+
* [`manual_midpoint`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_midpoint)
749750
* [`manual_non_exhaustive`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_non_exhaustive)
750751
* [`manual_pattern_char_comparison`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_pattern_char_comparison)
751752
* [`manual_range_contains`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_range_contains)

clippy_config/src/conf.rs

+1
Original file line numberDiff line numberDiff line change
@@ -615,6 +615,7 @@ define_Conf! {
615615
manual_hash_one,
616616
manual_is_ascii_check,
617617
manual_let_else,
618+
manual_midpoint,
618619
manual_non_exhaustive,
619620
manual_pattern_char_comparison,
620621
manual_range_contains,

clippy_lints/src/declared_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -602,6 +602,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
602602
crate::operators::IMPOSSIBLE_COMPARISONS_INFO,
603603
crate::operators::INEFFECTIVE_BIT_MASK_INFO,
604604
crate::operators::INTEGER_DIVISION_INFO,
605+
crate::operators::MANUAL_MIDPOINT_INFO,
605606
crate::operators::MISREFACTORED_ASSIGN_OP_INFO,
606607
crate::operators::MODULO_ARITHMETIC_INFO,
607608
crate::operators::MODULO_ONE_INFO,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::msrvs::{self, Msrv};
3+
use clippy_utils::sugg::Sugg;
4+
use clippy_utils::{is_float_literal, is_integer_literal};
5+
use rustc_ast::BinOpKind;
6+
use rustc_errors::Applicability;
7+
use rustc_hir::{Expr, ExprKind};
8+
use rustc_lint::LateContext;
9+
use rustc_middle::ty;
10+
11+
use super::MANUAL_MIDPOINT;
12+
13+
pub(super) fn check<'tcx>(
14+
cx: &LateContext<'tcx>,
15+
expr: &'tcx Expr<'_>,
16+
op: BinOpKind,
17+
left: &'tcx Expr<'_>,
18+
right: &'tcx Expr<'_>,
19+
msrv: &Msrv,
20+
) {
21+
if msrv.meets(msrvs::UINT_FLOAT_MIDPOINT)
22+
&& !left.span.from_expansion()
23+
&& !right.span.from_expansion()
24+
&& op == BinOpKind::Div
25+
&& (is_integer_literal(right, 2) || is_float_literal(right, 2.0))
26+
&& let Some((ll_expr, lr_expr)) = add_operands(left)
27+
&& add_operands(ll_expr).is_none() && add_operands(lr_expr).is_none()
28+
&& let left_ty = cx.typeck_results().expr_ty_adjusted(ll_expr)
29+
&& let right_ty = cx.typeck_results().expr_ty_adjusted(lr_expr)
30+
&& left_ty == right_ty
31+
// Do not lint on `(_+1)/2` and `(1+_)/2`, it is likely a `div_ceil()` operation
32+
&& !is_integer_literal(ll_expr, 1) && !is_integer_literal(lr_expr, 1)
33+
// FIXME: Also lint on signed integers when rust-lang/rust#134340 is merged
34+
&& matches!(left_ty.kind(), ty::Uint(_) | ty::Float(_))
35+
{
36+
let mut app = Applicability::MachineApplicable;
37+
let left_sugg = Sugg::hir_with_context(cx, ll_expr, expr.span.ctxt(), "..", &mut app);
38+
let right_sugg = Sugg::hir_with_context(cx, lr_expr, expr.span.ctxt(), "..", &mut app);
39+
let sugg = format!("{left_ty}::midpoint({left_sugg}, {right_sugg})");
40+
span_lint_and_sugg(
41+
cx,
42+
MANUAL_MIDPOINT,
43+
expr.span,
44+
"manual implementation of `midpoint` which can overflow",
45+
format!("use `{left_ty}::midpoint` instead"),
46+
sugg,
47+
app,
48+
);
49+
}
50+
}
51+
52+
/// Return the left and right operands if `expr` represents an addition
53+
fn add_operands<'e, 'tcx>(expr: &'e Expr<'tcx>) -> Option<(&'e Expr<'tcx>, &'e Expr<'tcx>)> {
54+
match expr.kind {
55+
ExprKind::Binary(op, left, right) if op.node == BinOpKind::Add => Some((left, right)),
56+
_ => None,
57+
}
58+
}

clippy_lints/src/operators/mod.rs

+32
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ mod float_cmp;
1111
mod float_equality_without_abs;
1212
mod identity_op;
1313
mod integer_division;
14+
mod manual_midpoint;
1415
mod misrefactored_assign_op;
1516
mod modulo_arithmetic;
1617
mod modulo_one;
@@ -24,6 +25,7 @@ mod verbose_bit_mask;
2425
pub(crate) mod arithmetic_side_effects;
2526

2627
use clippy_config::Conf;
28+
use clippy_utils::msrvs::Msrv;
2729
use rustc_hir::{Body, Expr, ExprKind, UnOp};
2830
use rustc_lint::{LateContext, LateLintPass};
2931
use rustc_session::impl_lint_pass;
@@ -834,17 +836,43 @@ declare_clippy_lint! {
834836
"explicit self-assignment"
835837
}
836838

839+
declare_clippy_lint! {
840+
/// ### What it does
841+
/// Checks for manual implementation of `midpoint`.
842+
///
843+
/// ### Why is this bad?
844+
/// Using `(x + y) / 2` might cause an overflow on the intermediate
845+
/// addition result.
846+
///
847+
/// ### Example
848+
/// ```no_run
849+
/// # let a: u32 = 0;
850+
/// let c = (a + 10) / 2;
851+
/// ```
852+
/// Use instead:
853+
/// ```no_run
854+
/// # let a: u32 = 0;
855+
/// let c = u32::midpoint(a, 10);
856+
/// ```
857+
#[clippy::version = "1.86.0"]
858+
pub MANUAL_MIDPOINT,
859+
correctness,
860+
"manual implementation of `midpoint` which can overflow"
861+
}
862+
837863
pub struct Operators {
838864
arithmetic_context: numeric_arithmetic::Context,
839865
verbose_bit_mask_threshold: u64,
840866
modulo_arithmetic_allow_comparison_to_zero: bool,
867+
msrv: Msrv,
841868
}
842869
impl Operators {
843870
pub fn new(conf: &'static Conf) -> Self {
844871
Self {
845872
arithmetic_context: numeric_arithmetic::Context::default(),
846873
verbose_bit_mask_threshold: conf.verbose_bit_mask_threshold,
847874
modulo_arithmetic_allow_comparison_to_zero: conf.allow_comparison_to_zero,
875+
msrv: conf.msrv.clone(),
848876
}
849877
}
850878
}
@@ -876,6 +904,7 @@ impl_lint_pass!(Operators => [
876904
NEEDLESS_BITWISE_BOOL,
877905
PTR_EQ,
878906
SELF_ASSIGNMENT,
907+
MANUAL_MIDPOINT,
879908
]);
880909

881910
impl<'tcx> LateLintPass<'tcx> for Operators {
@@ -893,6 +922,7 @@ impl<'tcx> LateLintPass<'tcx> for Operators {
893922
identity_op::check(cx, e, op.node, lhs, rhs);
894923
needless_bitwise_bool::check(cx, e, op.node, lhs, rhs);
895924
ptr_eq::check(cx, e, op.node, lhs, rhs);
925+
manual_midpoint::check(cx, e, op.node, lhs, rhs, &self.msrv);
896926
}
897927
self.arithmetic_context.check_binary(cx, e, op.node, lhs, rhs);
898928
bit_mask::check(cx, e, op.node, lhs, rhs);
@@ -943,6 +973,8 @@ impl<'tcx> LateLintPass<'tcx> for Operators {
943973
fn check_body_post(&mut self, cx: &LateContext<'tcx>, b: &Body<'_>) {
944974
self.arithmetic_context.body_post(cx, b);
945975
}
976+
977+
extract_msrv_attr!(LateContext);
946978
}
947979

948980
fn macro_with_not_op(e: &Expr<'_>) -> bool {

clippy_utils/src/msrvs.rs

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ macro_rules! msrv_aliases {
1919

2020
// names may refer to stabilized feature flags or library items
2121
msrv_aliases! {
22+
1,85,0 { UINT_FLOAT_MIDPOINT }
2223
1,84,0 { CONST_OPTION_AS_SLICE }
2324
1,83,0 { CONST_EXTERN_FN, CONST_FLOAT_BITS_CONV, CONST_FLOAT_CLASSIFY, CONST_MUT_REFS, CONST_UNWRAP }
2425
1,82,0 { IS_NONE_OR, REPEAT_N, RAW_REF_OP }

tests/ui/manual_midpoint.fixed

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#![warn(clippy::manual_midpoint)]
2+
3+
macro_rules! mac {
4+
($a: expr, $b: expr) => {
5+
($a + $b) / 2
6+
};
7+
}
8+
9+
macro_rules! add {
10+
($a: expr, $b: expr) => {
11+
($a + $b)
12+
};
13+
}
14+
15+
macro_rules! two {
16+
() => {
17+
2
18+
};
19+
}
20+
21+
#[clippy::msrv = "1.84"]
22+
fn older_msrv() {
23+
let a: u32 = 10;
24+
let _ = (a + 5) / 2;
25+
}
26+
27+
#[clippy::msrv = "1.85"]
28+
fn main() {
29+
let a: u32 = 10;
30+
let _ = u32::midpoint(a, 5); //~ ERROR: manual implementation of `midpoint`
31+
32+
let f: f32 = 10.0;
33+
let _ = f32::midpoint(f, 5.0); //~ ERROR: manual implementation of `midpoint`
34+
35+
let _: u32 = 5 + u32::midpoint(8, 8) + 2; //~ ERROR: manual implementation of `midpoint`
36+
let _: u32 = const { u32::midpoint(8, 8) }; //~ ERROR: manual implementation of `midpoint`
37+
let _: f64 = const { f64::midpoint(8.0f64, 8.) }; //~ ERROR: manual implementation of `midpoint`
38+
let _: u32 = u32::midpoint(u32::default(), u32::default()); //~ ERROR: manual implementation of `midpoint`
39+
let _: u32 = u32::midpoint(two!(), two!()); //~ ERROR: manual implementation of `midpoint`
40+
41+
// Do not lint in presence of an addition with more than 2 operands
42+
let _: u32 = (10 + 20 + 30) / 2;
43+
44+
// Do not lint if whole or part is coming from a macro
45+
let _ = mac!(10, 20);
46+
let _: u32 = add!(10u32, 20u32) / 2;
47+
let _: u32 = (10 + 20) / two!();
48+
49+
// Do not lint if a literal is not present
50+
let _ = (f + 5.0) / (1.0 + 1.0);
51+
52+
// Do not lint on signed integer types
53+
let i: i32 = 10;
54+
let _ = (i + 5) / 2;
55+
56+
// Do not lint on (x+1)/2 or (1+x)/2 as this looks more like a `div_ceil()` operation
57+
let _ = (i + 1) / 2;
58+
let _ = (1 + i) / 2;
59+
60+
// But if we see (x+1.0)/2.0 or (x+1.0)/2.0, it is probably a midpoint operation
61+
let _ = f32::midpoint(f, 1.0); //~ ERROR: manual implementation of `midpoint`
62+
let _ = f32::midpoint(1.0, f); //~ ERROR: manual implementation of `midpoint`
63+
}

tests/ui/manual_midpoint.rs

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#![warn(clippy::manual_midpoint)]
2+
3+
macro_rules! mac {
4+
($a: expr, $b: expr) => {
5+
($a + $b) / 2
6+
};
7+
}
8+
9+
macro_rules! add {
10+
($a: expr, $b: expr) => {
11+
($a + $b)
12+
};
13+
}
14+
15+
macro_rules! two {
16+
() => {
17+
2
18+
};
19+
}
20+
21+
#[clippy::msrv = "1.84"]
22+
fn older_msrv() {
23+
let a: u32 = 10;
24+
let _ = (a + 5) / 2;
25+
}
26+
27+
#[clippy::msrv = "1.85"]
28+
fn main() {
29+
let a: u32 = 10;
30+
let _ = (a + 5) / 2; //~ ERROR: manual implementation of `midpoint`
31+
32+
let f: f32 = 10.0;
33+
let _ = (f + 5.0) / 2.0; //~ ERROR: manual implementation of `midpoint`
34+
35+
let _: u32 = 5 + (8 + 8) / 2 + 2; //~ ERROR: manual implementation of `midpoint`
36+
let _: u32 = const { (8 + 8) / 2 }; //~ ERROR: manual implementation of `midpoint`
37+
let _: f64 = const { (8.0f64 + 8.) / 2. }; //~ ERROR: manual implementation of `midpoint`
38+
let _: u32 = (u32::default() + u32::default()) / 2; //~ ERROR: manual implementation of `midpoint`
39+
let _: u32 = (two!() + two!()) / 2; //~ ERROR: manual implementation of `midpoint`
40+
41+
// Do not lint in presence of an addition with more than 2 operands
42+
let _: u32 = (10 + 20 + 30) / 2;
43+
44+
// Do not lint if whole or part is coming from a macro
45+
let _ = mac!(10, 20);
46+
let _: u32 = add!(10u32, 20u32) / 2;
47+
let _: u32 = (10 + 20) / two!();
48+
49+
// Do not lint if a literal is not present
50+
let _ = (f + 5.0) / (1.0 + 1.0);
51+
52+
// Do not lint on signed integer types
53+
let i: i32 = 10;
54+
let _ = (i + 5) / 2;
55+
56+
// Do not lint on (x+1)/2 or (1+x)/2 as this looks more like a `div_ceil()` operation
57+
let _ = (i + 1) / 2;
58+
let _ = (1 + i) / 2;
59+
60+
// But if we see (x+1.0)/2.0 or (x+1.0)/2.0, it is probably a midpoint operation
61+
let _ = (f + 1.0) / 2.0; //~ ERROR: manual implementation of `midpoint`
62+
let _ = (1.0 + f) / 2.0; //~ ERROR: manual implementation of `midpoint`
63+
}

tests/ui/manual_midpoint.stderr

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
error: manual implementation of `midpoint` which can overflow
2+
--> tests/ui/manual_midpoint.rs:30:13
3+
|
4+
LL | let _ = (a + 5) / 2;
5+
| ^^^^^^^^^^^ help: use `u32::midpoint` instead: `u32::midpoint(a, 5)`
6+
|
7+
= note: `-D clippy::manual-midpoint` implied by `-D warnings`
8+
= help: to override `-D warnings` add `#[allow(clippy::manual_midpoint)]`
9+
10+
error: manual implementation of `midpoint` which can overflow
11+
--> tests/ui/manual_midpoint.rs:33:13
12+
|
13+
LL | let _ = (f + 5.0) / 2.0;
14+
| ^^^^^^^^^^^^^^^ help: use `f32::midpoint` instead: `f32::midpoint(f, 5.0)`
15+
16+
error: manual implementation of `midpoint` which can overflow
17+
--> tests/ui/manual_midpoint.rs:35:22
18+
|
19+
LL | let _: u32 = 5 + (8 + 8) / 2 + 2;
20+
| ^^^^^^^^^^^ help: use `u32::midpoint` instead: `u32::midpoint(8, 8)`
21+
22+
error: manual implementation of `midpoint` which can overflow
23+
--> tests/ui/manual_midpoint.rs:36:26
24+
|
25+
LL | let _: u32 = const { (8 + 8) / 2 };
26+
| ^^^^^^^^^^^ help: use `u32::midpoint` instead: `u32::midpoint(8, 8)`
27+
28+
error: manual implementation of `midpoint` which can overflow
29+
--> tests/ui/manual_midpoint.rs:37:26
30+
|
31+
LL | let _: f64 = const { (8.0f64 + 8.) / 2. };
32+
| ^^^^^^^^^^^^^^^^^^ help: use `f64::midpoint` instead: `f64::midpoint(8.0f64, 8.)`
33+
34+
error: manual implementation of `midpoint` which can overflow
35+
--> tests/ui/manual_midpoint.rs:38:18
36+
|
37+
LL | let _: u32 = (u32::default() + u32::default()) / 2;
38+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `u32::midpoint` instead: `u32::midpoint(u32::default(), u32::default())`
39+
40+
error: manual implementation of `midpoint` which can overflow
41+
--> tests/ui/manual_midpoint.rs:39:18
42+
|
43+
LL | let _: u32 = (two!() + two!()) / 2;
44+
| ^^^^^^^^^^^^^^^^^^^^^ help: use `u32::midpoint` instead: `u32::midpoint(two!(), two!())`
45+
46+
error: manual implementation of `midpoint` which can overflow
47+
--> tests/ui/manual_midpoint.rs:61:13
48+
|
49+
LL | let _ = (f + 1.0) / 2.0;
50+
| ^^^^^^^^^^^^^^^ help: use `f32::midpoint` instead: `f32::midpoint(f, 1.0)`
51+
52+
error: manual implementation of `midpoint` which can overflow
53+
--> tests/ui/manual_midpoint.rs:62:13
54+
|
55+
LL | let _ = (1.0 + f) / 2.0;
56+
| ^^^^^^^^^^^^^^^ help: use `f32::midpoint` instead: `f32::midpoint(1.0, f)`
57+
58+
error: aborting due to 9 previous errors
59+

tests/ui/option_if_let_else.fixed

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
clippy::equatable_if_let,
55
clippy::let_unit_value,
66
clippy::redundant_locals,
7+
clippy::manual_midpoint,
78
clippy::manual_unwrap_or_default,
89
clippy::manual_unwrap_or
910
)]

tests/ui/option_if_let_else.rs

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
clippy::equatable_if_let,
55
clippy::let_unit_value,
66
clippy::redundant_locals,
7+
clippy::manual_midpoint,
78
clippy::manual_unwrap_or_default,
89
clippy::manual_unwrap_or
910
)]

0 commit comments

Comments
 (0)