Skip to content

Commit 891e1a8

Browse files
committed
Auto merge of rust-lang#5427 - pmk21:implicit-sat-sub, r=flip1995
Add lint named implicit_saturating_sub Fixes: rust-lang#5399 I've made a basic skeleton of the lint, would love more feedback on how to make it better. changelog: Add lint [`implicit_saturating_sub`]
2 parents 1c0e4e5 + 1c11035 commit 891e1a8

7 files changed

+739
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -1293,6 +1293,7 @@ Released 2018-09-13
12931293
[`ifs_same_cond`]: https://rust-lang.github.io/rust-clippy/master/index.html#ifs_same_cond
12941294
[`implicit_hasher`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_hasher
12951295
[`implicit_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_return
1296+
[`implicit_saturating_sub`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_saturating_sub
12961297
[`imprecise_flops`]: https://rust-lang.github.io/rust-clippy/master/index.html#imprecise_flops
12971298
[`inconsistent_digit_grouping`]: https://rust-lang.github.io/rust-clippy/master/index.html#inconsistent_digit_grouping
12981299
[`indexing_slicing`]: https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing
+173
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
use crate::utils::{higher, in_macro, match_qpath, span_lint_and_sugg, SpanlessEq};
2+
use if_chain::if_chain;
3+
use rustc_ast::ast::LitKind;
4+
use rustc_errors::Applicability;
5+
use rustc_hir::{BinOpKind, Expr, ExprKind, QPath, StmtKind};
6+
use rustc_lint::{LateContext, LateLintPass};
7+
use rustc_session::{declare_lint_pass, declare_tool_lint};
8+
9+
declare_clippy_lint! {
10+
/// **What it does:** Checks for implicit saturating subtraction.
11+
///
12+
/// **Why is this bad?** Simplicity and readability. Instead we can easily use an builtin function.
13+
///
14+
/// **Known problems:** None.
15+
///
16+
/// **Example:**
17+
///
18+
/// ```rust
19+
/// let end: u32 = 10;
20+
/// let start: u32 = 5;
21+
///
22+
/// let mut i: u32 = end - start;
23+
///
24+
/// // Bad
25+
/// if i != 0 {
26+
/// i -= 1;
27+
/// }
28+
/// ```
29+
/// Use instead:
30+
/// ```rust
31+
/// let end: u32 = 10;
32+
/// let start: u32 = 5;
33+
///
34+
/// let mut i: u32 = end - start;
35+
///
36+
/// // Good
37+
/// i = i.saturating_sub(1);
38+
/// ```
39+
pub IMPLICIT_SATURATING_SUB,
40+
pedantic,
41+
"Perform saturating subtraction instead of implicitly checking lower bound of data type"
42+
}
43+
44+
declare_lint_pass!(ImplicitSaturatingSub => [IMPLICIT_SATURATING_SUB]);
45+
46+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitSaturatingSub {
47+
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) {
48+
if in_macro(expr.span) {
49+
return;
50+
}
51+
if_chain! {
52+
if let Some((ref cond, ref then, None)) = higher::if_block(&expr);
53+
54+
// Check if the conditional expression is a binary operation
55+
if let ExprKind::Binary(ref cond_op, ref cond_left, ref cond_right) = cond.kind;
56+
57+
// Ensure that the binary operator is >, != and <
58+
if BinOpKind::Ne == cond_op.node || BinOpKind::Gt == cond_op.node || BinOpKind::Lt == cond_op.node;
59+
60+
// Check if the true condition block has only one statement
61+
if let ExprKind::Block(ref block, _) = then.kind;
62+
if block.stmts.len() == 1 && block.expr.is_none();
63+
64+
// Check if assign operation is done
65+
if let StmtKind::Semi(ref e) = block.stmts[0].kind;
66+
if let Some(target) = subtracts_one(cx, e);
67+
68+
// Extracting out the variable name
69+
if let ExprKind::Path(ref assign_path) = target.kind;
70+
if let QPath::Resolved(_, ref ares_path) = assign_path;
71+
72+
then {
73+
// Handle symmetric conditions in the if statement
74+
let (cond_var, cond_num_val) = if SpanlessEq::new(cx).eq_expr(cond_left, target) {
75+
if BinOpKind::Gt == cond_op.node || BinOpKind::Ne == cond_op.node {
76+
(cond_left, cond_right)
77+
} else {
78+
return;
79+
}
80+
} else if SpanlessEq::new(cx).eq_expr(cond_right, target) {
81+
if BinOpKind::Lt == cond_op.node || BinOpKind::Ne == cond_op.node {
82+
(cond_right, cond_left)
83+
} else {
84+
return;
85+
}
86+
} else {
87+
return;
88+
};
89+
90+
// Check if the variable in the condition statement is an integer
91+
if !cx.tables.expr_ty(cond_var).is_integral() {
92+
return;
93+
}
94+
95+
// Get the variable name
96+
let var_name = ares_path.segments[0].ident.name.as_str();
97+
const INT_TYPES: [&str; 5] = ["i8", "i16", "i32", "i64", "i128"];
98+
99+
match cond_num_val.kind {
100+
ExprKind::Lit(ref cond_lit) => {
101+
// Check if the constant is zero
102+
if let LitKind::Int(0, _) = cond_lit.node {
103+
if cx.tables.expr_ty(cond_left).is_signed() {
104+
} else {
105+
print_lint_and_sugg(cx, &var_name, expr);
106+
};
107+
}
108+
},
109+
ExprKind::Path(ref cond_num_path) => {
110+
if INT_TYPES.iter().any(|int_type| match_qpath(cond_num_path, &[int_type, "MIN"])) {
111+
print_lint_and_sugg(cx, &var_name, expr);
112+
};
113+
},
114+
ExprKind::Call(ref func, _) => {
115+
if let ExprKind::Path(ref cond_num_path) = func.kind {
116+
if INT_TYPES.iter().any(|int_type| match_qpath(cond_num_path, &[int_type, "min_value"])) {
117+
print_lint_and_sugg(cx, &var_name, expr);
118+
}
119+
};
120+
},
121+
_ => (),
122+
}
123+
}
124+
}
125+
}
126+
}
127+
128+
fn subtracts_one<'a>(cx: &LateContext<'_, '_>, expr: &Expr<'a>) -> Option<&'a Expr<'a>> {
129+
match expr.kind {
130+
ExprKind::AssignOp(ref op1, ref target, ref value) => {
131+
if_chain! {
132+
if BinOpKind::Sub == op1.node;
133+
// Check if literal being subtracted is one
134+
if let ExprKind::Lit(ref lit1) = value.kind;
135+
if let LitKind::Int(1, _) = lit1.node;
136+
then {
137+
Some(target)
138+
} else {
139+
None
140+
}
141+
}
142+
},
143+
ExprKind::Assign(ref target, ref value, _) => {
144+
if_chain! {
145+
if let ExprKind::Binary(ref op1, ref left1, ref right1) = value.kind;
146+
if BinOpKind::Sub == op1.node;
147+
148+
if SpanlessEq::new(cx).eq_expr(left1, target);
149+
150+
if let ExprKind::Lit(ref lit1) = right1.kind;
151+
if let LitKind::Int(1, _) = lit1.node;
152+
then {
153+
Some(target)
154+
} else {
155+
None
156+
}
157+
}
158+
},
159+
_ => None,
160+
}
161+
}
162+
163+
fn print_lint_and_sugg(cx: &LateContext<'_, '_>, var_name: &str, expr: &Expr<'_>) {
164+
span_lint_and_sugg(
165+
cx,
166+
IMPLICIT_SATURATING_SUB,
167+
expr.span,
168+
"Implicitly performing saturating subtraction",
169+
"try",
170+
format!("{} = {}.saturating_sub({});", var_name, var_name, 1.to_string()),
171+
Applicability::MachineApplicable,
172+
);
173+
}

clippy_lints/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ mod identity_op;
225225
mod if_let_some_result;
226226
mod if_not_else;
227227
mod implicit_return;
228+
mod implicit_saturating_sub;
228229
mod indexing_slicing;
229230
mod infinite_iter;
230231
mod inherent_impl;
@@ -574,6 +575,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
574575
&if_let_some_result::IF_LET_SOME_RESULT,
575576
&if_not_else::IF_NOT_ELSE,
576577
&implicit_return::IMPLICIT_RETURN,
578+
&implicit_saturating_sub::IMPLICIT_SATURATING_SUB,
577579
&indexing_slicing::INDEXING_SLICING,
578580
&indexing_slicing::OUT_OF_BOUNDS_INDEXING,
579581
&infinite_iter::INFINITE_ITER,
@@ -888,6 +890,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
888890
store.register_late_pass(|| box unicode::Unicode);
889891
store.register_late_pass(|| box strings::StringAdd);
890892
store.register_late_pass(|| box implicit_return::ImplicitReturn);
893+
store.register_late_pass(|| box implicit_saturating_sub::ImplicitSaturatingSub);
891894
store.register_late_pass(|| box methods::Methods);
892895
store.register_late_pass(|| box map_clone::MapClone);
893896
store.register_late_pass(|| box shadow::Shadow);
@@ -1111,6 +1114,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
11111114
LintId::of(&functions::MUST_USE_CANDIDATE),
11121115
LintId::of(&functions::TOO_MANY_LINES),
11131116
LintId::of(&if_not_else::IF_NOT_ELSE),
1117+
LintId::of(&implicit_saturating_sub::IMPLICIT_SATURATING_SUB),
11141118
LintId::of(&infinite_iter::MAYBE_INFINITE_ITER),
11151119
LintId::of(&items_after_statements::ITEMS_AFTER_STATEMENTS),
11161120
LintId::of(&large_stack_arrays::LARGE_STACK_ARRAYS),

src/lintlist/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -773,6 +773,13 @@ pub static ref ALL_LINTS: Vec<Lint> = vec![
773773
deprecation: None,
774774
module: "implicit_return",
775775
},
776+
Lint {
777+
name: "implicit_saturating_sub",
778+
group: "pedantic",
779+
desc: "Perform saturating subtraction instead of implicitly checking lower bound of data type",
780+
deprecation: None,
781+
module: "implicit_saturating_sub",
782+
},
776783
Lint {
777784
name: "imprecise_flops",
778785
group: "nursery",
+160
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
// run-rustfix
2+
#![allow(unused_assignments, unused_mut, clippy::assign_op_pattern)]
3+
#![warn(clippy::implicit_saturating_sub)]
4+
5+
fn main() {
6+
// Tests for unsigned integers
7+
8+
let end_8: u8 = 10;
9+
let start_8: u8 = 5;
10+
let mut u_8: u8 = end_8 - start_8;
11+
12+
// Lint
13+
u_8 = u_8.saturating_sub(1);
14+
15+
match end_8 {
16+
10 => {
17+
// Lint
18+
u_8 = u_8.saturating_sub(1);
19+
},
20+
11 => u_8 += 1,
21+
_ => u_8 = 0,
22+
}
23+
24+
let end_16: u16 = 35;
25+
let start_16: u16 = 40;
26+
27+
let mut u_16: u16 = end_16 - start_16;
28+
29+
// Lint
30+
u_16 = u_16.saturating_sub(1);
31+
32+
let mut end_32: u32 = 7000;
33+
let mut start_32: u32 = 7010;
34+
35+
let mut u_32: u32 = end_32 - start_32;
36+
37+
// Lint
38+
u_32 = u_32.saturating_sub(1);
39+
40+
// No Lint
41+
if u_32 > 0 {
42+
u_16 += 1;
43+
}
44+
45+
// No Lint
46+
if u_32 != 0 {
47+
end_32 -= 1;
48+
start_32 += 1;
49+
}
50+
51+
let mut end_64: u64 = 75001;
52+
let mut start_64: u64 = 75000;
53+
54+
let mut u_64: u64 = end_64 - start_64;
55+
56+
// Lint
57+
u_64 = u_64.saturating_sub(1);
58+
59+
// Lint
60+
u_64 = u_64.saturating_sub(1);
61+
62+
// Lint
63+
u_64 = u_64.saturating_sub(1);
64+
65+
// No Lint
66+
if u_64 >= 1 {
67+
u_64 -= 1;
68+
}
69+
70+
// No Lint
71+
if u_64 > 0 {
72+
end_64 -= 1;
73+
}
74+
75+
// Tests for usize
76+
let end_usize: usize = 8054;
77+
let start_usize: usize = 8050;
78+
79+
let mut u_usize: usize = end_usize - start_usize;
80+
81+
// Lint
82+
u_usize = u_usize.saturating_sub(1);
83+
84+
// Tests for signed integers
85+
86+
let endi_8: i8 = 10;
87+
let starti_8: i8 = 50;
88+
89+
let mut i_8: i8 = endi_8 - starti_8;
90+
91+
// Lint
92+
i_8 = i_8.saturating_sub(1);
93+
94+
// Lint
95+
i_8 = i_8.saturating_sub(1);
96+
97+
// Lint
98+
i_8 = i_8.saturating_sub(1);
99+
100+
// Lint
101+
i_8 = i_8.saturating_sub(1);
102+
103+
let endi_16: i16 = 45;
104+
let starti_16: i16 = 44;
105+
106+
let mut i_16: i16 = endi_16 - starti_16;
107+
108+
// Lint
109+
i_16 = i_16.saturating_sub(1);
110+
111+
// Lint
112+
i_16 = i_16.saturating_sub(1);
113+
114+
// Lint
115+
i_16 = i_16.saturating_sub(1);
116+
117+
// Lint
118+
i_16 = i_16.saturating_sub(1);
119+
120+
let endi_32: i32 = 45;
121+
let starti_32: i32 = 44;
122+
123+
let mut i_32: i32 = endi_32 - starti_32;
124+
125+
// Lint
126+
i_32 = i_32.saturating_sub(1);
127+
128+
// Lint
129+
i_32 = i_32.saturating_sub(1);
130+
131+
// Lint
132+
i_32 = i_32.saturating_sub(1);
133+
134+
// Lint
135+
i_32 = i_32.saturating_sub(1);
136+
137+
let endi_64: i64 = 45;
138+
let starti_64: i64 = 44;
139+
140+
let mut i_64: i64 = endi_64 - starti_64;
141+
142+
// Lint
143+
i_64 = i_64.saturating_sub(1);
144+
145+
// Lint
146+
i_64 = i_64.saturating_sub(1);
147+
148+
// Lint
149+
i_64 = i_64.saturating_sub(1);
150+
151+
// No Lint
152+
if i_64 > 0 {
153+
i_64 -= 1;
154+
}
155+
156+
// No Lint
157+
if i_64 != 0 {
158+
i_64 -= 1;
159+
}
160+
}

0 commit comments

Comments
 (0)