about summary refs log tree commit diff
diff options
context:
space:
mode:
authorpmk21 <prithvikrishna49@gmail.com>2020-04-06 23:37:57 +0530
committerpmk21 <prithvikrishna49@gmail.com>2020-04-18 11:39:54 +0530
commit7c52e51d79696ae99e4f8499bb51f81b464d5a1a (patch)
treed21f6d0d93bb08b99b4c1bdf374c8d131ad902fe
parent1c0e4e5b97f05d6f397bf941b16e1e826310a5ed (diff)
downloadrust-7c52e51d79696ae99e4f8499bb51f81b464d5a1a.tar.gz
rust-7c52e51d79696ae99e4f8499bb51f81b464d5a1a.zip
Added basic lint and tests
-rw-r--r--CHANGELOG.md1
-rw-r--r--clippy_lints/src/implicit_saturating_sub.rs90
-rw-r--r--clippy_lints/src/lib.rs4
-rw-r--r--src/lintlist/mod.rs7
-rw-r--r--tests/ui/implicit_saturating_sub.rs21
5 files changed, 123 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 60ad855d7f8..e513787a53a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1293,6 +1293,7 @@ Released 2018-09-13
 [`ifs_same_cond`]: https://rust-lang.github.io/rust-clippy/master/index.html#ifs_same_cond
 [`implicit_hasher`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_hasher
 [`implicit_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_return
+[`implicit_saturating_sub`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_saturating_sub
 [`imprecise_flops`]: https://rust-lang.github.io/rust-clippy/master/index.html#imprecise_flops
 [`inconsistent_digit_grouping`]: https://rust-lang.github.io/rust-clippy/master/index.html#inconsistent_digit_grouping
 [`indexing_slicing`]: https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing
diff --git a/clippy_lints/src/implicit_saturating_sub.rs b/clippy_lints/src/implicit_saturating_sub.rs
new file mode 100644
index 00000000000..e2dff92834d
--- /dev/null
+++ b/clippy_lints/src/implicit_saturating_sub.rs
@@ -0,0 +1,90 @@
+use crate::utils::{higher, in_macro, span_lint_and_sugg};
+use if_chain::if_chain;
+use rustc_ast::ast::LitKind;
+use rustc_errors::Applicability;
+use rustc_hir::{BinOpKind, Expr, ExprKind, QPath, StmtKind};
+use rustc_lint::{LateContext, LateLintPass};
+use rustc_session::{declare_lint_pass, declare_tool_lint};
+
+declare_clippy_lint! {
+    /// **What it does:** Checks for implicit saturating subtraction.
+    ///
+    /// **Why is this bad?** Simplicity and readability. Instead we can easily use an inbuilt function.
+    ///
+    /// **Known problems:** None.
+    ///
+    /// **Example:**
+    ///
+    /// ```rust
+    /// let end = 10;
+    /// let start = 5;
+    ///
+    /// let mut i = end - start;
+    ///
+    /// // Bad
+    /// if i != 0 {
+    ///     i -= 1;
+    /// }
+    /// ```
+    /// Use instead:
+    /// ```rust
+    /// let end = 10;
+    /// let start = 5;
+    ///
+    /// let mut i = end - start;
+    ///
+    /// // Good
+    /// i.saturating_sub(1);
+    /// ```
+    pub IMPLICIT_SATURATING_SUB,
+    pedantic,
+    "Perform saturating subtraction instead of implicitly checking lower bound of data type"
+}
+
+declare_lint_pass!(ImplicitSaturatingSub => [IMPLICIT_SATURATING_SUB]);
+
+impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitSaturatingSub {
+    fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) {
+        if in_macro(expr.span) {
+            return;
+        }
+        if_chain! {
+            if let Some((ref cond, ref then, None)) = higher::if_block(&expr);
+            // Check if the conditional expression is a binary operation
+            if let ExprKind::Binary(ref op, ref left, ref right) = cond.kind;
+            // Ensure that the binary operator is > or !=
+            if BinOpKind::Ne == op.node || BinOpKind::Gt == op.node;
+            if let ExprKind::Path(ref cond_path) = left.kind;
+            // Get the literal on the right hand side
+            if let ExprKind::Lit(ref lit) = right.kind;
+            if let LitKind::Int(0, _) = lit.node;
+            // Check if the true condition block has only one statement
+            if let ExprKind::Block(ref block, _) = then.kind;
+            if block.stmts.len() == 1;
+            // Check if assign operation is done
+            if let StmtKind::Semi(ref e) = block.stmts[0].kind;
+            if let ExprKind::AssignOp(ref op1, ref target, ref value) = e.kind;
+            if BinOpKind::Sub == op1.node;
+            if let ExprKind::Path(ref assign_path) = target.kind;
+            // Check if the variable in the condition and assignment statement are the same
+            if let (QPath::Resolved(_, ref cres_path), QPath::Resolved(_, ref ares_path)) = (cond_path, assign_path);
+            if cres_path.res == ares_path.res;
+            if let ExprKind::Lit(ref lit1) = value.kind;
+            if let LitKind::Int(assign_lit, _) = lit1.node;
+            then {
+                // Get the variable name
+                let var_name = ares_path.segments[0].ident.name.as_str();
+                let applicability = Applicability::MaybeIncorrect;
+                span_lint_and_sugg(
+                    cx,
+                    IMPLICIT_SATURATING_SUB,
+                    expr.span,
+                    "Implicitly performing saturating subtraction",
+                    "try",
+                    format!("{}.saturating_sub({});", var_name, assign_lit.to_string()),
+                    applicability
+                );
+            }
+        }
+    }
+}
diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs
index a5b55d2ab70..b8415fa3af1 100644
--- a/clippy_lints/src/lib.rs
+++ b/clippy_lints/src/lib.rs
@@ -225,6 +225,7 @@ mod identity_op;
 mod if_let_some_result;
 mod if_not_else;
 mod implicit_return;
+mod implicit_saturating_sub;
 mod indexing_slicing;
 mod infinite_iter;
 mod inherent_impl;
@@ -574,6 +575,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
         &if_let_some_result::IF_LET_SOME_RESULT,
         &if_not_else::IF_NOT_ELSE,
         &implicit_return::IMPLICIT_RETURN,
+        &implicit_saturating_sub::IMPLICIT_SATURATING_SUB,
         &indexing_slicing::INDEXING_SLICING,
         &indexing_slicing::OUT_OF_BOUNDS_INDEXING,
         &infinite_iter::INFINITE_ITER,
@@ -888,6 +890,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
     store.register_late_pass(|| box unicode::Unicode);
     store.register_late_pass(|| box strings::StringAdd);
     store.register_late_pass(|| box implicit_return::ImplicitReturn);
+    store.register_late_pass(|| box implicit_saturating_sub::ImplicitSaturatingSub);
     store.register_late_pass(|| box methods::Methods);
     store.register_late_pass(|| box map_clone::MapClone);
     store.register_late_pass(|| box shadow::Shadow);
@@ -1111,6 +1114,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
         LintId::of(&functions::MUST_USE_CANDIDATE),
         LintId::of(&functions::TOO_MANY_LINES),
         LintId::of(&if_not_else::IF_NOT_ELSE),
+        LintId::of(&implicit_saturating_sub::IMPLICIT_SATURATING_SUB),
         LintId::of(&infinite_iter::MAYBE_INFINITE_ITER),
         LintId::of(&items_after_statements::ITEMS_AFTER_STATEMENTS),
         LintId::of(&large_stack_arrays::LARGE_STACK_ARRAYS),
diff --git a/src/lintlist/mod.rs b/src/lintlist/mod.rs
index cf2537e6d66..213d054e403 100644
--- a/src/lintlist/mod.rs
+++ b/src/lintlist/mod.rs
@@ -774,6 +774,13 @@ pub static ref ALL_LINTS: Vec<Lint> = vec![
         module: "implicit_return",
     },
     Lint {
+        name: "implicit_saturating_sub",
+        group: "pedantic",
+        desc: "Perform saturating subtraction instead of implicitly checking lower bound of data type",
+        deprecation: None,
+        module: "implicit_saturating_sub",
+    },
+    Lint {
         name: "imprecise_flops",
         group: "nursery",
         desc: "usage of imprecise floating point operations",
diff --git a/tests/ui/implicit_saturating_sub.rs b/tests/ui/implicit_saturating_sub.rs
new file mode 100644
index 00000000000..c1cc00bb685
--- /dev/null
+++ b/tests/ui/implicit_saturating_sub.rs
@@ -0,0 +1,21 @@
+#![warn(clippy::implicit_saturating_sub)]
+
+fn main() {
+    let mut end = 10;
+    let mut start = 5;
+    let mut i: u32 = end - start;
+
+    if i > 0 {
+        i -= 1;
+    }
+
+    match end {
+        10 => {
+            if i > 0 {
+                i -= 1;
+            }
+        },
+        11 => i += 1,
+        _ => i = 0,
+    }
+}