-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmanual_saturating_arithmetic.rs
153 lines (132 loc) · 4.06 KB
/
manual_saturating_arithmetic.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::{match_def_path, path_def_id};
use rustc_ast::ast;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::LateContext;
use rustc_middle::ty::layout::LayoutOf;
pub fn check(
cx: &LateContext<'_>,
expr: &hir::Expr<'_>,
arith_lhs: &hir::Expr<'_>,
arith_rhs: &hir::Expr<'_>,
unwrap_arg: &hir::Expr<'_>,
arith: &str,
) {
let ty = cx.typeck_results().expr_ty(arith_lhs);
if !ty.is_integral() {
return;
}
let Some(mm) = is_min_or_max(cx, unwrap_arg) else {
return;
};
if ty.is_signed() {
use self::MinMax::{Max, Min};
use self::Sign::{Neg, Pos};
let Some(sign) = lit_sign(arith_rhs) else {
return;
};
match (arith, sign, mm) {
("add", Pos, Max) | ("add", Neg, Min) | ("sub", Neg, Max) | ("sub", Pos, Min) => (),
// "mul" is omitted because lhs can be negative.
_ => return,
}
} else {
match (mm, arith) {
(MinMax::Max, "add" | "mul") | (MinMax::Min, "sub") => (),
_ => return,
}
}
let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
super::MANUAL_SATURATING_ARITHMETIC,
expr.span,
"manual saturating arithmetic",
format!("consider using `saturating_{arith}`"),
format!(
"{}.saturating_{arith}({})",
snippet_with_applicability(cx, arith_lhs.span, "..", &mut applicability),
snippet_with_applicability(cx, arith_rhs.span, "..", &mut applicability),
),
applicability,
);
}
#[derive(PartialEq, Eq)]
enum MinMax {
Min,
Max,
}
fn is_min_or_max(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<MinMax> {
// `T::max_value()` `T::min_value()` inherent methods
if let hir::ExprKind::Call(func, []) = &expr.kind
&& let hir::ExprKind::Path(hir::QPath::TypeRelative(_, segment)) = &func.kind
{
match segment.ident.as_str() {
"max_value" => return Some(MinMax::Max),
"min_value" => return Some(MinMax::Min),
_ => {},
}
}
let ty = cx.typeck_results().expr_ty(expr);
let ty_str = ty.to_string();
// `std::T::MAX` `std::T::MIN` constants
if let Some(id) = path_def_id(cx, expr) {
if match_def_path(cx, id, &["core", &ty_str, "MAX"]) {
return Some(MinMax::Max);
}
if match_def_path(cx, id, &["core", &ty_str, "MIN"]) {
return Some(MinMax::Min);
}
}
// Literals
let bits = cx.layout_of(ty).unwrap().size.bits();
let (minval, maxval): (u128, u128) = if ty.is_signed() {
let minval = 1 << (bits - 1);
let mut maxval = !(1 << (bits - 1));
if bits != 128 {
maxval &= (1 << bits) - 1;
}
(minval, maxval)
} else {
(0, if bits == 128 { !0 } else { (1 << bits) - 1 })
};
let check_lit = |expr: &hir::Expr<'_>, check_min: bool| {
if let hir::ExprKind::Lit(lit) = &expr.kind {
if let ast::LitKind::Int(value, _) = lit.node {
if value == maxval {
return Some(MinMax::Max);
}
if check_min && value == minval {
return Some(MinMax::Min);
}
}
}
None
};
if let r @ Some(_) = check_lit(expr, !ty.is_signed()) {
return r;
}
if ty.is_signed() {
if let hir::ExprKind::Unary(hir::UnOp::Neg, val) = &expr.kind {
return check_lit(val, true);
}
}
None
}
#[derive(PartialEq, Eq)]
enum Sign {
Pos,
Neg,
}
fn lit_sign(expr: &hir::Expr<'_>) -> Option<Sign> {
if let hir::ExprKind::Unary(hir::UnOp::Neg, inner) = &expr.kind {
if let hir::ExprKind::Lit(..) = &inner.kind {
return Some(Sign::Neg);
}
} else if let hir::ExprKind::Lit(..) = &expr.kind {
return Some(Sign::Pos);
}
None
}