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