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, span_lint};
10 use super::CAST_SIGN_LOSS;
12 pub(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) {
19 "casting `{}` to `{}` may lose the sign of the value",
26 fn should_lint(cx: &LateContext<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) -> bool {
27 match (cast_from.is_integral(), cast_to.is_integral()) {
29 if !cast_from.is_signed() || cast_to.is_signed() {
33 // Don't lint for positive constants.
34 let const_val = constant(cx, &cx.typeck_results(), cast_op);
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;
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"];
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;
54 method_name = inner_path.ident.name.as_str();
58 if allowed_methods.iter().any(|&name| method_name == name) {
66 (false, true) => !cast_to.is_signed(),