1 //! lint on manually implemented checked conversions that could be transformed into `try_from`
3 use if_chain::if_chain;
5 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use syntax::ast::LitKind;
9 use crate::utils::{span_lint, SpanlessEq};
11 declare_clippy_lint! {
12 /// **What it does:** Checks for explicit bounds checking when casting.
14 /// **Why is this bad?** Reduces the readability of statements & is error prone.
16 /// **Known problems:** None.
20 /// # let foo: u32 = 5;
22 /// foo <= i32::max_value() as u32
30 /// i32::try_from(foo).is_ok()
33 pub CHECKED_CONVERSIONS,
35 "`try_from` could replace manual bounds checking when casting"
38 declare_lint_pass!(CheckedConversions => [CHECKED_CONVERSIONS]);
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CheckedConversions {
41 fn check_expr(&mut self, cx: &LateContext<'_, '_>, item: &Expr) {
42 let result = if_chain! {
43 if !in_external_macro(cx.sess(), item.span);
44 if let ExprKind::Binary(op, ref left, ref right) = &item.node;
48 BinOpKind::Ge | BinOpKind::Le => single_check(item),
49 BinOpKind::And => double_check(cx, left, right),
57 if let Some(cv) = result {
63 "Checked cast can be simplified: `{}::try_from`",
64 cv.to_type.unwrap_or_else(|| "IntegerType".to_string()),
71 /// Searches for a single check from unsigned to _ is done
72 /// todo: check for case signed -> larger unsigned == only x >= 0
73 fn single_check(expr: &Expr) -> Option<Conversion<'_>> {
74 check_upper_bound(expr).filter(|cv| cv.cvt == ConversionType::FromUnsigned)
77 /// Searches for a combination of upper & lower bound checks
78 fn double_check<'a>(cx: &LateContext<'_, '_>, left: &'a Expr, right: &'a Expr) -> Option<Conversion<'a>> {
79 let upper_lower = |l, r| {
80 let upper = check_upper_bound(l);
81 let lower = check_lower_bound(r);
83 transpose(upper, lower).and_then(|(l, r)| l.combine(r, cx))
86 upper_lower(left, right).or_else(|| upper_lower(right, left))
89 /// Contains the result of a tried conversion check
90 #[derive(Clone, Debug)]
91 struct Conversion<'a> {
93 expr_to_cast: &'a Expr,
94 to_type: Option<String>,
97 /// The kind of conversion that is checked
98 #[derive(Copy, Clone, Debug, PartialEq)]
105 impl<'a> Conversion<'a> {
106 /// Combine multiple conversions if the are compatible
107 pub fn combine(self, other: Self, cx: &LateContext<'_, '_>) -> Option<Conversion<'a>> {
108 if self.is_compatible(&other, cx) {
109 // Prefer a Conversion that contains a type-constraint
110 Some(if self.to_type.is_some() { self } else { other })
116 /// Checks if two conversions are compatible
117 /// same type of conversion, same 'castee' and same 'to type'
118 pub fn is_compatible(&self, other: &Self, cx: &LateContext<'_, '_>) -> bool {
119 (self.cvt == other.cvt)
120 && (SpanlessEq::new(cx).eq_expr(self.expr_to_cast, other.expr_to_cast))
121 && (self.has_compatible_to_type(other))
124 /// Checks if the to-type is the same (if there is a type constraint)
125 fn has_compatible_to_type(&self, other: &Self) -> bool {
126 transpose(self.to_type.as_ref(), other.to_type.as_ref()).map_or(true, |(l, r)| l == r)
129 /// Try to construct a new conversion if the conversion type is valid
130 fn try_new<'b>(expr_to_cast: &'a Expr, from_type: &'b str, to_type: String) -> Option<Conversion<'a>> {
131 ConversionType::try_new(from_type, &to_type).map(|cvt| Conversion {
134 to_type: Some(to_type),
138 /// Construct a new conversion without type constraint
139 fn new_any(expr_to_cast: &'a Expr) -> Conversion<'a> {
141 cvt: ConversionType::SignedToUnsigned,
148 impl ConversionType {
149 /// Creates a conversion type if the type is allowed & conversion is valid
150 fn try_new(from: &str, to: &str) -> Option<Self> {
151 if UNSIGNED_TYPES.contains(&from) {
152 Some(ConversionType::FromUnsigned)
153 } else if SIGNED_TYPES.contains(&from) {
154 if UNSIGNED_TYPES.contains(&to) {
155 Some(ConversionType::SignedToUnsigned)
156 } else if SIGNED_TYPES.contains(&to) {
157 Some(ConversionType::SignedToSigned)
167 /// Check for `expr <= (to_type::max_value() as from_type)`
168 fn check_upper_bound(expr: &Expr) -> Option<Conversion<'_>> {
170 if let ExprKind::Binary(ref op, ref left, ref right) = &expr.node;
171 if let Some((candidate, check)) = normalize_le_ge(op, left, right);
172 if let Some((from, to)) = get_types_from_cast(check, "max_value", INT_TYPES);
175 Conversion::try_new(candidate, &from, to)
182 /// Check for `expr >= 0|(to_type::min_value() as from_type)`
183 fn check_lower_bound(expr: &Expr) -> Option<Conversion<'_>> {
184 fn check_function<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Conversion<'a>> {
185 (check_lower_bound_zero(candidate, check)).or_else(|| (check_lower_bound_min(candidate, check)))
188 // First of we need a binary containing the expression & the cast
189 if let ExprKind::Binary(ref op, ref left, ref right) = &expr.node {
190 normalize_le_ge(op, right, left).and_then(|(l, r)| check_function(l, r))
196 /// Check for `expr >= 0`
197 fn check_lower_bound_zero<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Conversion<'a>> {
199 if let ExprKind::Lit(ref lit) = &check.node;
200 if let LitKind::Int(0, _) = &lit.node;
203 Some(Conversion::new_any(candidate))
210 /// Check for `expr >= (to_type::min_value() as from_type)`
211 fn check_lower_bound_min<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Conversion<'a>> {
212 if let Some((from, to)) = get_types_from_cast(check, "min_value", SIGNED_TYPES) {
213 Conversion::try_new(candidate, &from, to)
219 /// Tries to extract the from- and to-type from a cast expression
220 fn get_types_from_cast(expr: &Expr, func: &str, types: &[&str]) -> Option<(String, String)> {
221 // `to_type::maxmin_value() as from_type`
222 let call_from_cast: Option<(&Expr, String)> = if_chain! {
223 // to_type::maxmin_value(), from_type
224 if let ExprKind::Cast(ref limit, ref from_type) = &expr.node;
225 if let TyKind::Path(ref from_type_path) = &from_type.node;
226 if let Some(from_type_str) = int_ty_to_str(from_type_path);
229 Some((limit, from_type_str.to_string()))
235 // `from_type::from(to_type::maxmin_value())`
236 let limit_from: Option<(&Expr, String)> = call_from_cast.or_else(|| {
238 // `from_type::from, to_type::maxmin_value()`
239 if let ExprKind::Call(ref from_func, ref args) = &expr.node;
240 // `to_type::maxmin_value()`
242 if let limit = &args[0];
244 if let ExprKind::Path(ref path) = &from_func.node;
245 if let Some(from_type) = get_implementing_type(path, INT_TYPES, "from");
248 Some((limit, from_type))
255 if let Some((limit, from_type)) = limit_from {
257 if let ExprKind::Call(ref fun_name, _) = &limit.node;
258 // `to_type, maxmin_value`
259 if let ExprKind::Path(ref path) = &fun_name.node;
261 if let Some(to_type) = get_implementing_type(path, types, func);
264 Some((from_type, to_type))
274 /// Gets the type which implements the called function
275 fn get_implementing_type(path: &QPath, candidates: &[&str], function: &str) -> Option<String> {
277 if let QPath::TypeRelative(ref ty, ref path) = &path;
278 if path.ident.name == function;
279 if let TyKind::Path(QPath::Resolved(None, ref tp)) = &ty.node;
280 if let [int] = &*tp.segments;
281 let name = int.ident.as_str().get();
282 if candidates.contains(&name);
285 Some(name.to_string())
292 /// Gets the type as a string, if it is a supported integer
293 fn int_ty_to_str(path: &QPath) -> Option<&str> {
295 if let QPath::Resolved(_, ref path) = *path;
296 if let [ty] = &*path.segments;
301 .find(|c| (&ty.ident.name) == *c)
309 /// (Option<T>, Option<U>) -> Option<(T, U)>
310 fn transpose<T, U>(lhs: Option<T>, rhs: Option<U>) -> Option<(T, U)> {
312 (Some(l), Some(r)) => Some((l, r)),
317 /// Will return the expressions as if they were expr1 <= expr2
318 fn normalize_le_ge<'a>(op: &'a BinOp, left: &'a Expr, right: &'a Expr) -> Option<(&'a Expr, &'a Expr)> {
320 BinOpKind::Le => Some((left, right)),
321 BinOpKind::Ge => Some((right, left)),
326 const UNSIGNED_TYPES: &[&str] = &["u8", "u16", "u32", "u64", "u128", "usize"];
327 const SIGNED_TYPES: &[&str] = &["i8", "i16", "i32", "i64", "i128", "isize"];
328 const INT_TYPES: &[&str] = &[
329 "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize",