about summary refs log tree commit diff
path: root/clippy_lints
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2022-06-24 17:49:53 +0000
committerbors <bors@rust-lang.org>2022-06-24 17:49:53 +0000
commite17864e2ffd4244906a689705d8e2ce7ffac6d6b (patch)
treeb35fd2090c23b610fbc9e1a262be186fdfccd771 /clippy_lints
parent1d1ae10876d3eaa5c982dd3daa083b7c2fc363b9 (diff)
parentdf26c3f551fec5854e3acd140782b8f8c98e987b (diff)
downloadrust-e17864e2ffd4244906a689705d8e2ce7ffac6d6b.tar.gz
rust-e17864e2ffd4244906a689705d8e2ce7ffac6d6b.zip
Auto merge of #9031 - evantypanski:manual_rem_euclid, r=Jarcho
Add [`manual_rem_euclid`] lint

Closes #8883

Adds a lint for checking manual use of `rem_euclid(n)`

changelog: Add [`manual_rem_euclid`] lint
Diffstat (limited to 'clippy_lints')
-rw-r--r--clippy_lints/src/lib.register_all.rs1
-rw-r--r--clippy_lints/src/lib.register_complexity.rs1
-rw-r--r--clippy_lints/src/lib.register_lints.rs1
-rw-r--r--clippy_lints/src/lib.rs2
-rw-r--r--clippy_lints/src/manual_rem_euclid.rs123
5 files changed, 128 insertions, 0 deletions
diff --git a/clippy_lints/src/lib.register_all.rs b/clippy_lints/src/lib.register_all.rs
index 7876f21f6e6..a1565255b0b 100644
--- a/clippy_lints/src/lib.register_all.rs
+++ b/clippy_lints/src/lib.register_all.rs
@@ -135,6 +135,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
     LintId::of(manual_async_fn::MANUAL_ASYNC_FN),
     LintId::of(manual_bits::MANUAL_BITS),
     LintId::of(manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE),
+    LintId::of(manual_rem_euclid::MANUAL_REM_EUCLID),
     LintId::of(manual_strip::MANUAL_STRIP),
     LintId::of(map_clone::MAP_CLONE),
     LintId::of(map_unit_fn::OPTION_MAP_UNIT_FN),
diff --git a/clippy_lints/src/lib.register_complexity.rs b/clippy_lints/src/lib.register_complexity.rs
index 4f1c3673f85..6370264a12a 100644
--- a/clippy_lints/src/lib.register_complexity.rs
+++ b/clippy_lints/src/lib.register_complexity.rs
@@ -24,6 +24,7 @@ store.register_group(true, "clippy::complexity", Some("clippy_complexity"), vec!
     LintId::of(loops::MANUAL_FLATTEN),
     LintId::of(loops::SINGLE_ELEMENT_LOOP),
     LintId::of(loops::WHILE_LET_LOOP),
+    LintId::of(manual_rem_euclid::MANUAL_REM_EUCLID),
     LintId::of(manual_strip::MANUAL_STRIP),
     LintId::of(map_unit_fn::OPTION_MAP_UNIT_FN),
     LintId::of(map_unit_fn::RESULT_MAP_UNIT_FN),
diff --git a/clippy_lints/src/lib.register_lints.rs b/clippy_lints/src/lib.register_lints.rs
index de22f50cf94..f706ba0620f 100644
--- a/clippy_lints/src/lib.register_lints.rs
+++ b/clippy_lints/src/lib.register_lints.rs
@@ -254,6 +254,7 @@ store.register_lints(&[
     manual_bits::MANUAL_BITS,
     manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE,
     manual_ok_or::MANUAL_OK_OR,
+    manual_rem_euclid::MANUAL_REM_EUCLID,
     manual_strip::MANUAL_STRIP,
     map_clone::MAP_CLONE,
     map_err_ignore::MAP_ERR_IGNORE,
diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs
index dcee11cc28c..70cf6be8b7c 100644
--- a/clippy_lints/src/lib.rs
+++ b/clippy_lints/src/lib.rs
@@ -282,6 +282,7 @@ mod manual_async_fn;
 mod manual_bits;
 mod manual_non_exhaustive;
 mod manual_ok_or;
+mod manual_rem_euclid;
 mod manual_strip;
 mod map_clone;
 mod map_err_ignore;
@@ -912,6 +913,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
     store.register_late_pass(|| Box::new(as_underscore::AsUnderscore));
     store.register_late_pass(|| Box::new(read_zero_byte_vec::ReadZeroByteVec));
     store.register_late_pass(|| Box::new(default_instead_of_iter_empty::DefaultIterEmpty));
+    store.register_late_pass(move || Box::new(manual_rem_euclid::ManualRemEuclid::new(msrv)));
     // add lints here, do not remove this comment, it's used in `new_lint`
 }
 
diff --git a/clippy_lints/src/manual_rem_euclid.rs b/clippy_lints/src/manual_rem_euclid.rs
new file mode 100644
index 00000000000..b5698965fc3
--- /dev/null
+++ b/clippy_lints/src/manual_rem_euclid.rs
@@ -0,0 +1,123 @@
+use clippy_utils::consts::{constant_full_int, FullInt};
+use clippy_utils::diagnostics::span_lint_and_sugg;
+use clippy_utils::source::snippet_with_applicability;
+use clippy_utils::{in_constant, meets_msrv, msrvs, path_to_local};
+use rustc_errors::Applicability;
+use rustc_hir::{BinOpKind, Expr, ExprKind, Node, TyKind};
+use rustc_lint::{LateContext, LateLintPass, LintContext};
+use rustc_middle::lint::in_external_macro;
+use rustc_semver::RustcVersion;
+use rustc_session::{declare_tool_lint, impl_lint_pass};
+
+declare_clippy_lint! {
+    /// ### What it does
+    /// Checks for an expression like `((x % 4) + 4) % 4` which is a common manual reimplementation
+    /// of `x.rem_euclid(4)`.
+    ///
+    /// ### Why is this bad?
+    /// It's simpler and more readable.
+    ///
+    /// ### Example
+    /// ```rust
+    /// let x: i32 = 24;
+    /// let rem = ((x % 4) + 4) % 4;
+    /// ```
+    /// Use instead:
+    /// ```rust
+    /// let x: i32 = 24;
+    /// let rem = x.rem_euclid(4);
+    /// ```
+    #[clippy::version = "1.63.0"]
+    pub MANUAL_REM_EUCLID,
+    complexity,
+    "manually reimplementing `rem_euclid`"
+}
+
+pub struct ManualRemEuclid {
+    msrv: Option<RustcVersion>,
+}
+
+impl ManualRemEuclid {
+    #[must_use]
+    pub fn new(msrv: Option<RustcVersion>) -> Self {
+        Self { msrv }
+    }
+}
+
+impl_lint_pass!(ManualRemEuclid => [MANUAL_REM_EUCLID]);
+
+impl<'tcx> LateLintPass<'tcx> for ManualRemEuclid {
+    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
+        if !meets_msrv(self.msrv, msrvs::REM_EUCLID) {
+            return;
+        }
+
+        if in_constant(cx, expr.hir_id) && !meets_msrv(self.msrv, msrvs::REM_EUCLID_CONST) {
+            return;
+        }
+
+        if in_external_macro(cx.sess(), expr.span) {
+            return;
+        }
+
+        if let ExprKind::Binary(op1, expr1, right) = expr.kind
+            && op1.node == BinOpKind::Rem
+            && let Some(const1) = check_for_unsigned_int_constant(cx, right)
+            && let ExprKind::Binary(op2, left, right) = expr1.kind
+            && op2.node == BinOpKind::Add
+            && let Some((const2, expr2)) = check_for_either_unsigned_int_constant(cx, left, right)
+            && let ExprKind::Binary(op3, expr3, right) = expr2.kind
+            && op3.node == BinOpKind::Rem
+            && let Some(const3) = check_for_unsigned_int_constant(cx, right)
+            // Also ensures the const is nonzero since zero can't be a divisor
+            && const1 == const2 && const2 == const3
+            && let Some(hir_id) = path_to_local(expr3)
+            && let Some(Node::Binding(_)) = cx.tcx.hir().find(hir_id) {
+                // Apply only to params or locals with annotated types
+                match cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
+                    Some(Node::Param(..)) => (),
+                    Some(Node::Local(local)) => {
+                        let Some(ty) = local.ty else { return };
+                        if matches!(ty.kind, TyKind::Infer) {
+                            return;
+                        }
+                    }
+                    _ => return,
+                };
+
+                let mut app = Applicability::MachineApplicable;
+                let rem_of = snippet_with_applicability(cx, expr3.span, "_", &mut app);
+                span_lint_and_sugg(
+                    cx,
+                    MANUAL_REM_EUCLID,
+                    expr.span,
+                    "manual `rem_euclid` implementation",
+                    "consider using",
+                    format!("{rem_of}.rem_euclid({const1})"),
+                    app,
+                );
+        }
+    }
+
+    extract_msrv_attr!(LateContext);
+}
+
+// Checks if either the left or right expressions can be an unsigned int constant and returns that
+// constant along with the other expression unchanged if so
+fn check_for_either_unsigned_int_constant<'a>(
+    cx: &'a LateContext<'_>,
+    left: &'a Expr<'_>,
+    right: &'a Expr<'_>,
+) -> Option<(u128, &'a Expr<'a>)> {
+    check_for_unsigned_int_constant(cx, left)
+        .map(|int_const| (int_const, right))
+        .or_else(|| check_for_unsigned_int_constant(cx, right).map(|int_const| (int_const, left)))
+}
+
+fn check_for_unsigned_int_constant<'a>(cx: &'a LateContext<'_>, expr: &'a Expr<'_>) -> Option<u128> {
+    let Some(int_const) = constant_full_int(cx, cx.typeck_results(), expr) else { return None };
+    match int_const {
+        FullInt::S(s) => s.try_into().ok(),
+        FullInt::U(u) => Some(u),
+    }
+}