Skip to content

Commit e8043b5

Browse files
committed
Auto merge of #4088 - pJunger:check1, r=oli-obk
Added lint for TryFrom for checked integer conversion. works towards #3947 Added lint for try_from for checked integer conversion. Should recognize simple & straight-forward checked integer conversions.
2 parents 11194e3 + e85211c commit e8043b5

9 files changed

+626
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,7 @@ All notable changes to this project will be documented in this file.
846846
[`char_lit_as_u8`]: https://rust-lang.github.io/rust-clippy/master/index.html#char_lit_as_u8
847847
[`chars_last_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#chars_last_cmp
848848
[`chars_next_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#chars_next_cmp
849+
[`checked_conversions`]: https://rust-lang.github.io/rust-clippy/master/index.html#checked_conversions
849850
[`clone_double_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#clone_double_ref
850851
[`clone_on_copy`]: https://rust-lang.github.io/rust-clippy/master/index.html#clone_on_copy
851852
[`clone_on_ref_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#clone_on_ref_ptr
Lines changed: 354 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,354 @@
1+
//! lint on manually implemented checked conversions that could be transformed into `try_from`
2+
3+
use if_chain::if_chain;
4+
use lazy_static::lazy_static;
5+
use rustc::hir::*;
6+
use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
7+
use rustc::{declare_lint_pass, declare_tool_lint};
8+
use rustc_errors::Applicability;
9+
use syntax::ast::LitKind;
10+
use syntax::symbol::Symbol;
11+
12+
use crate::utils::{snippet_with_applicability, span_lint_and_sugg, sym, SpanlessEq};
13+
14+
declare_clippy_lint! {
15+
/// **What it does:** Checks for explicit bounds checking when casting.
16+
///
17+
/// **Why is this bad?** Reduces the readability of statements & is error prone.
18+
///
19+
/// **Known problems:** None.
20+
///
21+
/// **Example:**
22+
/// ```rust
23+
/// # let foo: u32 = 5;
24+
/// # let _ =
25+
/// foo <= i32::max_value() as u32
26+
/// # ;
27+
/// ```
28+
///
29+
/// Could be written:
30+
///
31+
/// ```rust
32+
/// # let _ =
33+
/// i32::try_from(foo).is_ok()
34+
/// # ;
35+
/// ```
36+
pub CHECKED_CONVERSIONS,
37+
pedantic,
38+
"`try_from` could replace manual bounds checking when casting"
39+
}
40+
41+
declare_lint_pass!(CheckedConversions => [CHECKED_CONVERSIONS]);
42+
43+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CheckedConversions {
44+
fn check_expr(&mut self, cx: &LateContext<'_, '_>, item: &Expr) {
45+
let result = if_chain! {
46+
if !in_external_macro(cx.sess(), item.span);
47+
if let ExprKind::Binary(op, ref left, ref right) = &item.node;
48+
49+
then {
50+
match op.node {
51+
BinOpKind::Ge | BinOpKind::Le => single_check(item),
52+
BinOpKind::And => double_check(cx, left, right),
53+
_ => None,
54+
}
55+
} else {
56+
None
57+
}
58+
};
59+
60+
if_chain! {
61+
if let Some(cv) = result;
62+
if let Some(to_type) = cv.to_type;
63+
64+
then {
65+
let mut applicability = Applicability::MachineApplicable;
66+
let snippet = snippet_with_applicability(cx, cv.expr_to_cast.span, "_", &mut
67+
applicability);
68+
span_lint_and_sugg(
69+
cx,
70+
CHECKED_CONVERSIONS,
71+
item.span,
72+
"Checked cast can be simplified.",
73+
"try",
74+
format!("{}::try_from({}).is_ok()",
75+
to_type,
76+
snippet),
77+
applicability
78+
);
79+
}
80+
}
81+
}
82+
}
83+
84+
/// Searches for a single check from unsigned to _ is done
85+
/// todo: check for case signed -> larger unsigned == only x >= 0
86+
fn single_check(expr: &Expr) -> Option<Conversion<'_>> {
87+
check_upper_bound(expr).filter(|cv| cv.cvt == ConversionType::FromUnsigned)
88+
}
89+
90+
/// Searches for a combination of upper & lower bound checks
91+
fn double_check<'a>(cx: &LateContext<'_, '_>, left: &'a Expr, right: &'a Expr) -> Option<Conversion<'a>> {
92+
let upper_lower = |l, r| {
93+
let upper = check_upper_bound(l);
94+
let lower = check_lower_bound(r);
95+
96+
transpose(upper, lower).and_then(|(l, r)| l.combine(r, cx))
97+
};
98+
99+
upper_lower(left, right).or_else(|| upper_lower(right, left))
100+
}
101+
102+
/// Contains the result of a tried conversion check
103+
#[derive(Clone, Debug)]
104+
struct Conversion<'a> {
105+
cvt: ConversionType,
106+
expr_to_cast: &'a Expr,
107+
to_type: Option<Symbol>,
108+
}
109+
110+
/// The kind of conversion that is checked
111+
#[derive(Copy, Clone, Debug, PartialEq)]
112+
enum ConversionType {
113+
SignedToUnsigned,
114+
SignedToSigned,
115+
FromUnsigned,
116+
}
117+
118+
impl<'a> Conversion<'a> {
119+
/// Combine multiple conversions if the are compatible
120+
pub fn combine(self, other: Self, cx: &LateContext<'_, '_>) -> Option<Conversion<'a>> {
121+
if self.is_compatible(&other, cx) {
122+
// Prefer a Conversion that contains a type-constraint
123+
Some(if self.to_type.is_some() { self } else { other })
124+
} else {
125+
None
126+
}
127+
}
128+
129+
/// Checks if two conversions are compatible
130+
/// same type of conversion, same 'castee' and same 'to type'
131+
pub fn is_compatible(&self, other: &Self, cx: &LateContext<'_, '_>) -> bool {
132+
(self.cvt == other.cvt)
133+
&& (SpanlessEq::new(cx).eq_expr(self.expr_to_cast, other.expr_to_cast))
134+
&& (self.has_compatible_to_type(other))
135+
}
136+
137+
/// Checks if the to-type is the same (if there is a type constraint)
138+
fn has_compatible_to_type(&self, other: &Self) -> bool {
139+
transpose(self.to_type.as_ref(), other.to_type.as_ref()).map_or(true, |(l, r)| l == r)
140+
}
141+
142+
/// Try to construct a new conversion if the conversion type is valid
143+
fn try_new(expr_to_cast: &'a Expr, from_type: Symbol, to_type: Symbol) -> Option<Conversion<'a>> {
144+
ConversionType::try_new(from_type, to_type).map(|cvt| Conversion {
145+
cvt,
146+
expr_to_cast,
147+
to_type: Some(to_type),
148+
})
149+
}
150+
151+
/// Construct a new conversion without type constraint
152+
fn new_any(expr_to_cast: &'a Expr) -> Conversion<'a> {
153+
Conversion {
154+
cvt: ConversionType::SignedToUnsigned,
155+
expr_to_cast,
156+
to_type: None,
157+
}
158+
}
159+
}
160+
161+
impl ConversionType {
162+
/// Creates a conversion type if the type is allowed & conversion is valid
163+
fn try_new(from: Symbol, to: Symbol) -> Option<Self> {
164+
if UINTS.contains(&from) {
165+
Some(ConversionType::FromUnsigned)
166+
} else if SINTS.contains(&from) {
167+
if UINTS.contains(&to) {
168+
Some(ConversionType::SignedToUnsigned)
169+
} else if SINTS.contains(&to) {
170+
Some(ConversionType::SignedToSigned)
171+
} else {
172+
None
173+
}
174+
} else {
175+
None
176+
}
177+
}
178+
}
179+
180+
/// Check for `expr <= (to_type::max_value() as from_type)`
181+
fn check_upper_bound(expr: &Expr) -> Option<Conversion<'_>> {
182+
if_chain! {
183+
if let ExprKind::Binary(ref op, ref left, ref right) = &expr.node;
184+
if let Some((candidate, check)) = normalize_le_ge(op, left, right);
185+
if let Some((from, to)) = get_types_from_cast(check, *sym::max_value, &*INTS);
186+
187+
then {
188+
Conversion::try_new(candidate, from, to)
189+
} else {
190+
None
191+
}
192+
}
193+
}
194+
195+
/// Check for `expr >= 0|(to_type::min_value() as from_type)`
196+
fn check_lower_bound(expr: &Expr) -> Option<Conversion<'_>> {
197+
fn check_function<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Conversion<'a>> {
198+
(check_lower_bound_zero(candidate, check)).or_else(|| (check_lower_bound_min(candidate, check)))
199+
}
200+
201+
// First of we need a binary containing the expression & the cast
202+
if let ExprKind::Binary(ref op, ref left, ref right) = &expr.node {
203+
normalize_le_ge(op, right, left).and_then(|(l, r)| check_function(l, r))
204+
} else {
205+
None
206+
}
207+
}
208+
209+
/// Check for `expr >= 0`
210+
fn check_lower_bound_zero<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Conversion<'a>> {
211+
if_chain! {
212+
if let ExprKind::Lit(ref lit) = &check.node;
213+
if let LitKind::Int(0, _) = &lit.node;
214+
215+
then {
216+
Some(Conversion::new_any(candidate))
217+
} else {
218+
None
219+
}
220+
}
221+
}
222+
223+
/// Check for `expr >= (to_type::min_value() as from_type)`
224+
fn check_lower_bound_min<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Conversion<'a>> {
225+
if let Some((from, to)) = get_types_from_cast(check, *sym::min_value, &*SINTS) {
226+
Conversion::try_new(candidate, from, to)
227+
} else {
228+
None
229+
}
230+
}
231+
232+
/// Tries to extract the from- and to-type from a cast expression
233+
fn get_types_from_cast(expr: &Expr, func: Symbol, types: &[Symbol]) -> Option<(Symbol, Symbol)> {
234+
// `to_type::maxmin_value() as from_type`
235+
let call_from_cast: Option<(&Expr, Symbol)> = if_chain! {
236+
// to_type::maxmin_value(), from_type
237+
if let ExprKind::Cast(ref limit, ref from_type) = &expr.node;
238+
if let TyKind::Path(ref from_type_path) = &from_type.node;
239+
if let Some(from_sym) = int_ty_to_sym(from_type_path);
240+
241+
then {
242+
Some((limit, from_sym))
243+
} else {
244+
None
245+
}
246+
};
247+
248+
// `from_type::from(to_type::maxmin_value())`
249+
let limit_from: Option<(&Expr, Symbol)> = call_from_cast.or_else(|| {
250+
if_chain! {
251+
// `from_type::from, to_type::maxmin_value()`
252+
if let ExprKind::Call(ref from_func, ref args) = &expr.node;
253+
// `to_type::maxmin_value()`
254+
if args.len() == 1;
255+
if let limit = &args[0];
256+
// `from_type::from`
257+
if let ExprKind::Path(ref path) = &from_func.node;
258+
if let Some(from_sym) = get_implementing_type(path, &*INTS, *sym::from);
259+
260+
then {
261+
Some((limit, from_sym))
262+
} else {
263+
None
264+
}
265+
}
266+
});
267+
268+
if let Some((limit, from_type)) = limit_from {
269+
if_chain! {
270+
if let ExprKind::Call(ref fun_name, _) = &limit.node;
271+
// `to_type, maxmin_value`
272+
if let ExprKind::Path(ref path) = &fun_name.node;
273+
// `to_type`
274+
if let Some(to_type) = get_implementing_type(path, types, func);
275+
276+
then {
277+
Some((from_type, to_type))
278+
} else {
279+
None
280+
}
281+
}
282+
} else {
283+
None
284+
}
285+
}
286+
287+
/// Gets the type which implements the called function
288+
fn get_implementing_type(path: &QPath, candidates: &[Symbol], function: Symbol) -> Option<Symbol> {
289+
if_chain! {
290+
if let QPath::TypeRelative(ref ty, ref path) = &path;
291+
if path.ident.name == function;
292+
if let TyKind::Path(QPath::Resolved(None, ref tp)) = &ty.node;
293+
if let [int] = &*tp.segments;
294+
let name = int.ident.name;
295+
if candidates.contains(&name);
296+
297+
then {
298+
Some(name)
299+
} else {
300+
None
301+
}
302+
}
303+
}
304+
305+
/// Gets the type as a string, if it is a supported integer
306+
fn int_ty_to_sym(path: &QPath) -> Option<Symbol> {
307+
if_chain! {
308+
if let QPath::Resolved(_, ref path) = *path;
309+
if let [ty] = &*path.segments;
310+
311+
then {
312+
INTS
313+
.iter()
314+
.find(|c| ty.ident.name == **c)
315+
.cloned()
316+
} else {
317+
None
318+
}
319+
}
320+
}
321+
322+
/// (Option<T>, Option<U>) -> Option<(T, U)>
323+
fn transpose<T, U>(lhs: Option<T>, rhs: Option<U>) -> Option<(T, U)> {
324+
match (lhs, rhs) {
325+
(Some(l), Some(r)) => Some((l, r)),
326+
_ => None,
327+
}
328+
}
329+
330+
/// Will return the expressions as if they were expr1 <= expr2
331+
fn normalize_le_ge<'a>(op: &'a BinOp, left: &'a Expr, right: &'a Expr) -> Option<(&'a Expr, &'a Expr)> {
332+
match op.node {
333+
BinOpKind::Le => Some((left, right)),
334+
BinOpKind::Ge => Some((right, left)),
335+
_ => None,
336+
}
337+
}
338+
339+
lazy_static! {
340+
static ref UINTS: [Symbol; 5] = [*sym::u8, *sym::u16, *sym::u32, *sym::u64, *sym::usize];
341+
static ref SINTS: [Symbol; 5] = [*sym::i8, *sym::i16, *sym::i32, *sym::i64, *sym::isize];
342+
static ref INTS: [Symbol; 10] = [
343+
*sym::u8,
344+
*sym::u16,
345+
*sym::u32,
346+
*sym::u64,
347+
*sym::usize,
348+
*sym::i8,
349+
*sym::i16,
350+
*sym::i32,
351+
*sym::i64,
352+
*sym::isize
353+
];
354+
}

clippy_lints/src/enum_clike.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use rustc::ty;
1010
use rustc::ty::subst::InternalSubsts;
1111
use rustc::ty::util::IntTypeExt;
1212
use rustc::{declare_lint_pass, declare_tool_lint};
13+
use std::convert::TryFrom;
1314
use syntax::ast::{IntTy, UintTy};
1415

1516
declare_clippy_lint! {
@@ -65,7 +66,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
6566
match ty.sty {
6667
ty::Int(IntTy::Isize) => {
6768
let val = ((val as i128) << 64) >> 64;
68-
if val <= i128::from(i32::max_value()) && val >= i128::from(i32::min_value()) {
69+
if i32::try_from(val).is_ok() {
6970
continue;
7071
}
7172
},

0 commit comments

Comments
 (0)