]> git.proxmox.com Git - rustc.git/blobdiff - src/tools/clippy/clippy_lints/src/casts/cast_sign_loss.rs
Merge tag 'debian/1.52.1+dfsg1-1_exp2' into proxmox/buster
[rustc.git] / src / tools / clippy / clippy_lints / src / casts / cast_sign_loss.rs
diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_sign_loss.rs b/src/tools/clippy/clippy_lints/src/casts/cast_sign_loss.rs
new file mode 100644 (file)
index 0000000..9656fbe
--- /dev/null
@@ -0,0 +1,70 @@
+use rustc_hir::{Expr, ExprKind};
+use rustc_lint::LateContext;
+use rustc_middle::ty::{self, Ty};
+
+use if_chain::if_chain;
+
+use crate::consts::{constant, Constant};
+use crate::utils::{method_chain_args, sext, span_lint};
+
+use super::CAST_SIGN_LOSS;
+
+pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
+    if should_lint(cx, cast_op, cast_from, cast_to) {
+        span_lint(
+            cx,
+            CAST_SIGN_LOSS,
+            expr.span,
+            &format!(
+                "casting `{}` to `{}` may lose the sign of the value",
+                cast_from, cast_to
+            ),
+        );
+    }
+}
+
+fn should_lint(cx: &LateContext<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) -> bool {
+    match (cast_from.is_integral(), cast_to.is_integral()) {
+        (true, true) => {
+            if !cast_from.is_signed() || cast_to.is_signed() {
+                return false;
+            }
+
+            // Don't lint for positive constants.
+            let const_val = constant(cx, &cx.typeck_results(), cast_op);
+            if_chain! {
+                if let Some((Constant::Int(n), _)) = const_val;
+                if let ty::Int(ity) = *cast_from.kind();
+                if sext(cx.tcx, n, ity) >= 0;
+                then {
+                    return false;
+                }
+            }
+
+            // Don't lint for the result of methods that always return non-negative values.
+            if let ExprKind::MethodCall(ref path, _, _, _) = cast_op.kind {
+                let mut method_name = path.ident.name.as_str();
+                let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
+
+                if_chain! {
+                    if method_name == "unwrap";
+                    if let Some(arglist) = method_chain_args(cast_op, &["unwrap"]);
+                    if let ExprKind::MethodCall(ref inner_path, _, _, _) = &arglist[0][0].kind;
+                    then {
+                        method_name = inner_path.ident.name.as_str();
+                    }
+                }
+
+                if allowed_methods.iter().any(|&name| method_name == name) {
+                    return false;
+                }
+            }
+
+            true
+        },
+
+        (false, true) => !cast_to.is_signed(),
+
+        (_, _) => false,
+    }
+}