]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/casts/cast_sign_loss.rs
Don't re-export clippy_utils::diagnostics::*
[rust.git] / clippy_lints / src / casts / cast_sign_loss.rs
1 use rustc_hir::{Expr, ExprKind};
2 use rustc_lint::LateContext;
3 use rustc_middle::ty::{self, Ty};
4
5 use if_chain::if_chain;
6
7 use crate::consts::{constant, Constant};
8 use crate::utils::{method_chain_args, sext};
9 use clippy_utils::diagnostics::span_lint;
10
11 use super::CAST_SIGN_LOSS;
12
13 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
14     if should_lint(cx, cast_op, cast_from, cast_to) {
15         span_lint(
16             cx,
17             CAST_SIGN_LOSS,
18             expr.span,
19             &format!(
20                 "casting `{}` to `{}` may lose the sign of the value",
21                 cast_from, cast_to
22             ),
23         );
24     }
25 }
26
27 fn should_lint(cx: &LateContext<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) -> bool {
28     match (cast_from.is_integral(), cast_to.is_integral()) {
29         (true, true) => {
30             if !cast_from.is_signed() || cast_to.is_signed() {
31                 return false;
32             }
33
34             // Don't lint for positive constants.
35             let const_val = constant(cx, &cx.typeck_results(), cast_op);
36             if_chain! {
37                 if let Some((Constant::Int(n), _)) = const_val;
38                 if let ty::Int(ity) = *cast_from.kind();
39                 if sext(cx.tcx, n, ity) >= 0;
40                 then {
41                     return false;
42                 }
43             }
44
45             // Don't lint for the result of methods that always return non-negative values.
46             if let ExprKind::MethodCall(ref path, _, _, _) = cast_op.kind {
47                 let mut method_name = path.ident.name.as_str();
48                 let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
49
50                 if_chain! {
51                     if method_name == "unwrap";
52                     if let Some(arglist) = method_chain_args(cast_op, &["unwrap"]);
53                     if let ExprKind::MethodCall(ref inner_path, _, _, _) = &arglist[0][0].kind;
54                     then {
55                         method_name = inner_path.ident.name.as_str();
56                     }
57                 }
58
59                 if allowed_methods.iter().any(|&name| method_name == name) {
60                     return false;
61                 }
62             }
63
64             true
65         },
66
67         (false, true) => !cast_to.is_signed(),
68
69         (_, _) => false,
70     }
71 }