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