1 //! lint on manually implemented checked conversions that could be transformed into `try_from`
3 use clippy_utils::diagnostics::span_lint_and_sugg;
4 use clippy_utils::source::snippet_with_applicability;
5 use if_chain::if_chain;
6 use rustc_ast::ast::LitKind;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOp, BinOpKind, Expr, ExprKind, QPath, TyKind};
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
11 use rustc_semver::RustcVersion;
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 use crate::utils::{meets_msrv, SpanlessEq};
16 const CHECKED_CONVERSIONS_MSRV: RustcVersion = RustcVersion::new(1, 34, 0);
18 declare_clippy_lint! {
19 /// **What it does:** Checks for explicit bounds checking when casting.
21 /// **Why is this bad?** Reduces the readability of statements & is error prone.
23 /// **Known problems:** None.
27 /// # let foo: u32 = 5;
29 /// foo <= i32::MAX as u32
36 /// # use std::convert::TryFrom;
39 /// i32::try_from(foo).is_ok()
42 pub CHECKED_CONVERSIONS,
44 "`try_from` could replace manual bounds checking when casting"
47 pub struct CheckedConversions {
48 msrv: Option<RustcVersion>,
51 impl CheckedConversions {
53 pub fn new(msrv: Option<RustcVersion>) -> Self {
58 impl_lint_pass!(CheckedConversions => [CHECKED_CONVERSIONS]);
60 impl<'tcx> LateLintPass<'tcx> for CheckedConversions {
61 fn check_expr(&mut self, cx: &LateContext<'_>, item: &Expr<'_>) {
62 if !meets_msrv(self.msrv.as_ref(), &CHECKED_CONVERSIONS_MSRV) {
66 let result = if_chain! {
67 if !in_external_macro(cx.sess(), item.span);
68 if let ExprKind::Binary(op, ref left, ref right) = &item.kind;
72 BinOpKind::Ge | BinOpKind::Le => single_check(item),
73 BinOpKind::And => double_check(cx, left, right),
81 if let Some(cv) = result {
82 if let Some(to_type) = cv.to_type {
83 let mut applicability = Applicability::MachineApplicable;
84 let snippet = snippet_with_applicability(cx, cv.expr_to_cast.span, "_", &mut applicability);
89 "checked cast can be simplified",
91 format!("{}::try_from({}).is_ok()", to_type, snippet),
98 extract_msrv_attr!(LateContext);
101 /// Searches for a single check from unsigned to _ is done
102 /// todo: check for case signed -> larger unsigned == only x >= 0
103 fn single_check<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
104 check_upper_bound(expr).filter(|cv| cv.cvt == ConversionType::FromUnsigned)
107 /// Searches for a combination of upper & lower bound checks
108 fn double_check<'a>(cx: &LateContext<'_>, left: &'a Expr<'_>, right: &'a Expr<'_>) -> Option<Conversion<'a>> {
109 let upper_lower = |l, r| {
110 let upper = check_upper_bound(l);
111 let lower = check_lower_bound(r);
113 upper.zip(lower).and_then(|(l, r)| l.combine(r, cx))
116 upper_lower(left, right).or_else(|| upper_lower(right, left))
119 /// Contains the result of a tried conversion check
120 #[derive(Clone, Debug)]
121 struct Conversion<'a> {
123 expr_to_cast: &'a Expr<'a>,
124 to_type: Option<&'a str>,
127 /// The kind of conversion that is checked
128 #[derive(Copy, Clone, Debug, PartialEq)]
129 enum ConversionType {
135 impl<'a> Conversion<'a> {
136 /// Combine multiple conversions if the are compatible
137 pub fn combine(self, other: Self, cx: &LateContext<'_>) -> Option<Conversion<'a>> {
138 if self.is_compatible(&other, cx) {
139 // Prefer a Conversion that contains a type-constraint
140 Some(if self.to_type.is_some() { self } else { other })
146 /// Checks if two conversions are compatible
147 /// same type of conversion, same 'castee' and same 'to type'
148 pub fn is_compatible(&self, other: &Self, cx: &LateContext<'_>) -> bool {
149 (self.cvt == other.cvt)
150 && (SpanlessEq::new(cx).eq_expr(self.expr_to_cast, other.expr_to_cast))
151 && (self.has_compatible_to_type(other))
154 /// Checks if the to-type is the same (if there is a type constraint)
155 fn has_compatible_to_type(&self, other: &Self) -> bool {
156 match (self.to_type, other.to_type) {
157 (Some(l), Some(r)) => l == r,
162 /// Try to construct a new conversion if the conversion type is valid
163 fn try_new(expr_to_cast: &'a Expr<'_>, from_type: &str, to_type: &'a str) -> Option<Conversion<'a>> {
164 ConversionType::try_new(from_type, to_type).map(|cvt| Conversion {
167 to_type: Some(to_type),
171 /// Construct a new conversion without type constraint
172 fn new_any(expr_to_cast: &'a Expr<'_>) -> Conversion<'a> {
174 cvt: ConversionType::SignedToUnsigned,
181 impl ConversionType {
182 /// Creates a conversion type if the type is allowed & conversion is valid
184 fn try_new(from: &str, to: &str) -> Option<Self> {
185 if UINTS.contains(&from) {
186 Some(Self::FromUnsigned)
187 } else if SINTS.contains(&from) {
188 if UINTS.contains(&to) {
189 Some(Self::SignedToUnsigned)
190 } else if SINTS.contains(&to) {
191 Some(Self::SignedToSigned)
201 /// Check for `expr <= (to_type::MAX as from_type)`
202 fn check_upper_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
204 if let ExprKind::Binary(ref op, ref left, ref right) = &expr.kind;
205 if let Some((candidate, check)) = normalize_le_ge(op, left, right);
206 if let Some((from, to)) = get_types_from_cast(check, INTS, "max_value", "MAX");
209 Conversion::try_new(candidate, from, to)
216 /// Check for `expr >= 0|(to_type::MIN as from_type)`
217 fn check_lower_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
218 fn check_function<'a>(candidate: &'a Expr<'a>, check: &'a Expr<'a>) -> Option<Conversion<'a>> {
219 (check_lower_bound_zero(candidate, check)).or_else(|| (check_lower_bound_min(candidate, check)))
222 // First of we need a binary containing the expression & the cast
223 if let ExprKind::Binary(ref op, ref left, ref right) = &expr.kind {
224 normalize_le_ge(op, right, left).and_then(|(l, r)| check_function(l, r))
230 /// Check for `expr >= 0`
231 fn check_lower_bound_zero<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
233 if let ExprKind::Lit(ref lit) = &check.kind;
234 if let LitKind::Int(0, _) = &lit.node;
237 Some(Conversion::new_any(candidate))
244 /// Check for `expr >= (to_type::MIN as from_type)`
245 fn check_lower_bound_min<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
246 if let Some((from, to)) = get_types_from_cast(check, SINTS, "min_value", "MIN") {
247 Conversion::try_new(candidate, from, to)
253 /// Tries to extract the from- and to-type from a cast expression
254 fn get_types_from_cast<'a>(
258 assoc_const: &'a str,
259 ) -> Option<(&'a str, &'a str)> {
260 // `to_type::max_value() as from_type`
261 // or `to_type::MAX as from_type`
262 let call_from_cast: Option<(&Expr<'_>, &str)> = if_chain! {
263 // to_type::max_value(), from_type
264 if let ExprKind::Cast(ref limit, ref from_type) = &expr.kind;
265 if let TyKind::Path(ref from_type_path) = &from_type.kind;
266 if let Some(from_sym) = int_ty_to_sym(from_type_path);
269 Some((limit, from_sym))
275 // `from_type::from(to_type::max_value())`
276 let limit_from: Option<(&Expr<'_>, &str)> = call_from_cast.or_else(|| {
278 // `from_type::from, to_type::max_value()`
279 if let ExprKind::Call(ref from_func, ref args) = &expr.kind;
280 // `to_type::max_value()`
282 if let limit = &args[0];
284 if let ExprKind::Path(ref path) = &from_func.kind;
285 if let Some(from_sym) = get_implementing_type(path, INTS, "from");
288 Some((limit, from_sym))
295 if let Some((limit, from_type)) = limit_from {
297 // `from_type::from(_)`
298 ExprKind::Call(path, _) => {
299 if let ExprKind::Path(ref path) = path.kind {
301 if let Some(to_type) = get_implementing_type(path, types, func) {
302 return Some((from_type, to_type));
307 ExprKind::Path(ref path) => {
308 if let Some(to_type) = get_implementing_type(path, types, assoc_const) {
309 return Some((from_type, to_type));
318 /// Gets the type which implements the called function
319 fn get_implementing_type<'a>(path: &QPath<'_>, candidates: &'a [&str], function: &str) -> Option<&'a str> {
321 if let QPath::TypeRelative(ref ty, ref path) = &path;
322 if path.ident.name.as_str() == function;
323 if let TyKind::Path(QPath::Resolved(None, ref tp)) = &ty.kind;
324 if let [int] = &*tp.segments;
325 let name = &int.ident.name.as_str();
328 candidates.iter().find(|c| name == *c).cloned()
335 /// Gets the type as a string, if it is a supported integer
336 fn int_ty_to_sym<'tcx>(path: &QPath<'_>) -> Option<&'tcx str> {
338 if let QPath::Resolved(_, ref path) = *path;
339 if let [ty] = &*path.segments;
340 let name = &ty.ident.name.as_str();
343 INTS.iter().find(|c| name == *c).cloned()
350 /// Will return the expressions as if they were expr1 <= expr2
351 fn normalize_le_ge<'a>(op: &BinOp, left: &'a Expr<'a>, right: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
353 BinOpKind::Le => Some((left, right)),
354 BinOpKind::Ge => Some((right, left)),
360 const UINTS: &[&str] = &["u8", "u16", "u32", "u64", "usize"];
361 const SINTS: &[&str] = &["i8", "i16", "i32", "i64", "isize"];
362 const INTS: &[&str] = &["u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize"];