1 use rustc_hir::{Expr, ExprKind};
2 use rustc_lint::LateContext;
3 use rustc_middle::ty::{self, Ty};
5 use if_chain::if_chain;
7 use crate::consts::{constant, Constant};
8 use crate::utils::{method_chain_args, sext};
9 use clippy_utils::diagnostics::span_lint;
11 use super::CAST_SIGN_LOSS;
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) {
20 "casting `{}` to `{}` may lose the sign of the value",
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()) {
30 if !cast_from.is_signed() || cast_to.is_signed() {
34 // Don't lint for positive constants.
35 let const_val = constant(cx, &cx.typeck_results(), cast_op);
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;
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"];
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;
55 method_name = inner_path.ident.name.as_str();
59 if allowed_methods.iter().any(|&name| method_name == name) {
67 (false, true) => !cast_to.is_signed(),