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 clippy_utils::{in_constant, is_integer_literal, meets_msrv, msrvs, SpanlessEq};
6 use if_chain::if_chain;
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 declare_clippy_lint! {
16 /// Checks for explicit bounds checking when casting.
18 /// ### Why is this bad?
19 /// Reduces the readability of statements & is error prone.
23 /// # let foo: u32 = 5;
24 /// foo <= i32::MAX as u32;
30 /// # #[allow(unused)]
31 /// i32::try_from(foo).is_ok();
33 #[clippy::version = "1.37.0"]
34 pub CHECKED_CONVERSIONS,
36 "`try_from` could replace manual bounds checking when casting"
39 pub struct CheckedConversions {
40 msrv: Option<RustcVersion>,
43 impl CheckedConversions {
45 pub fn new(msrv: Option<RustcVersion>) -> Self {
50 impl_lint_pass!(CheckedConversions => [CHECKED_CONVERSIONS]);
52 impl<'tcx> LateLintPass<'tcx> for CheckedConversions {
53 fn check_expr(&mut self, cx: &LateContext<'_>, item: &Expr<'_>) {
54 if !meets_msrv(self.msrv, msrvs::TRY_FROM) {
58 let result = if_chain! {
59 if !in_constant(cx, item.hir_id);
60 if !in_external_macro(cx.sess(), item.span);
61 if let ExprKind::Binary(op, left, right) = &item.kind;
65 BinOpKind::Ge | BinOpKind::Le => single_check(item),
66 BinOpKind::And => double_check(cx, left, right),
74 if let Some(cv) = result {
75 if let Some(to_type) = cv.to_type {
76 let mut applicability = Applicability::MachineApplicable;
77 let snippet = snippet_with_applicability(cx, cv.expr_to_cast.span, "_", &mut applicability);
82 "checked cast can be simplified",
84 format!("{to_type}::try_from({snippet}).is_ok()"),
91 extract_msrv_attr!(LateContext);
94 /// Searches for a single check from unsigned to _ is done
95 /// todo: check for case signed -> larger unsigned == only x >= 0
96 fn single_check<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
97 check_upper_bound(expr).filter(|cv| cv.cvt == ConversionType::FromUnsigned)
100 /// Searches for a combination of upper & lower bound checks
101 fn double_check<'a>(cx: &LateContext<'_>, left: &'a Expr<'_>, right: &'a Expr<'_>) -> Option<Conversion<'a>> {
102 let upper_lower = |l, r| {
103 let upper = check_upper_bound(l);
104 let lower = check_lower_bound(r);
106 upper.zip(lower).and_then(|(l, r)| l.combine(r, cx))
109 upper_lower(left, right).or_else(|| upper_lower(right, left))
112 /// Contains the result of a tried conversion check
113 #[derive(Clone, Debug)]
114 struct Conversion<'a> {
116 expr_to_cast: &'a Expr<'a>,
117 to_type: Option<&'a str>,
120 /// The kind of conversion that is checked
121 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
122 enum ConversionType {
128 impl<'a> Conversion<'a> {
129 /// Combine multiple conversions if the are compatible
130 pub fn combine(self, other: Self, cx: &LateContext<'_>) -> Option<Conversion<'a>> {
131 if self.is_compatible(&other, cx) {
132 // Prefer a Conversion that contains a type-constraint
133 Some(if self.to_type.is_some() { self } else { other })
139 /// Checks if two conversions are compatible
140 /// same type of conversion, same 'castee' and same 'to type'
141 pub fn is_compatible(&self, other: &Self, cx: &LateContext<'_>) -> bool {
142 (self.cvt == other.cvt)
143 && (SpanlessEq::new(cx).eq_expr(self.expr_to_cast, other.expr_to_cast))
144 && (self.has_compatible_to_type(other))
147 /// Checks if the to-type is the same (if there is a type constraint)
148 fn has_compatible_to_type(&self, other: &Self) -> bool {
149 match (self.to_type, other.to_type) {
150 (Some(l), Some(r)) => l == r,
155 /// Try to construct a new conversion if the conversion type is valid
156 fn try_new(expr_to_cast: &'a Expr<'_>, from_type: &str, to_type: &'a str) -> Option<Conversion<'a>> {
157 ConversionType::try_new(from_type, to_type).map(|cvt| Conversion {
160 to_type: Some(to_type),
164 /// Construct a new conversion without type constraint
165 fn new_any(expr_to_cast: &'a Expr<'_>) -> Conversion<'a> {
167 cvt: ConversionType::SignedToUnsigned,
174 impl ConversionType {
175 /// Creates a conversion type if the type is allowed & conversion is valid
177 fn try_new(from: &str, to: &str) -> Option<Self> {
178 if UINTS.contains(&from) {
179 Some(Self::FromUnsigned)
180 } else if SINTS.contains(&from) {
181 if UINTS.contains(&to) {
182 Some(Self::SignedToUnsigned)
183 } else if SINTS.contains(&to) {
184 Some(Self::SignedToSigned)
194 /// Check for `expr <= (to_type::MAX as from_type)`
195 fn check_upper_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
197 if let ExprKind::Binary(ref op, left, right) = &expr.kind;
198 if let Some((candidate, check)) = normalize_le_ge(op, left, right);
199 if let Some((from, to)) = get_types_from_cast(check, INTS, "max_value", "MAX");
202 Conversion::try_new(candidate, from, to)
209 /// Check for `expr >= 0|(to_type::MIN as from_type)`
210 fn check_lower_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
211 fn check_function<'a>(candidate: &'a Expr<'a>, check: &'a Expr<'a>) -> Option<Conversion<'a>> {
212 (check_lower_bound_zero(candidate, check)).or_else(|| (check_lower_bound_min(candidate, check)))
215 // First of we need a binary containing the expression & the cast
216 if let ExprKind::Binary(ref op, left, right) = &expr.kind {
217 normalize_le_ge(op, right, left).and_then(|(l, r)| check_function(l, r))
223 /// Check for `expr >= 0`
224 fn check_lower_bound_zero<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
225 is_integer_literal(check, 0).then(|| Conversion::new_any(candidate))
228 /// Check for `expr >= (to_type::MIN as from_type)`
229 fn check_lower_bound_min<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
230 if let Some((from, to)) = get_types_from_cast(check, SINTS, "min_value", "MIN") {
231 Conversion::try_new(candidate, from, to)
237 /// Tries to extract the from- and to-type from a cast expression
238 fn get_types_from_cast<'a>(
242 assoc_const: &'a str,
243 ) -> Option<(&'a str, &'a str)> {
244 // `to_type::max_value() as from_type`
245 // or `to_type::MAX as from_type`
246 let call_from_cast: Option<(&Expr<'_>, &str)> = if_chain! {
247 // to_type::max_value(), from_type
248 if let ExprKind::Cast(limit, from_type) = &expr.kind;
249 if let TyKind::Path(ref from_type_path) = &from_type.kind;
250 if let Some(from_sym) = int_ty_to_sym(from_type_path);
253 Some((limit, from_sym))
259 // `from_type::from(to_type::max_value())`
260 let limit_from: Option<(&Expr<'_>, &str)> = call_from_cast.or_else(|| {
262 // `from_type::from, to_type::max_value()`
263 if let ExprKind::Call(from_func, [limit]) = &expr.kind;
265 if let ExprKind::Path(ref path) = &from_func.kind;
266 if let Some(from_sym) = get_implementing_type(path, INTS, "from");
269 Some((limit, from_sym))
276 if let Some((limit, from_type)) = limit_from {
278 // `from_type::from(_)`
279 ExprKind::Call(path, _) => {
280 if let ExprKind::Path(ref path) = path.kind {
282 if let Some(to_type) = get_implementing_type(path, types, func) {
283 return Some((from_type, to_type));
288 ExprKind::Path(ref path) => {
289 if let Some(to_type) = get_implementing_type(path, types, assoc_const) {
290 return Some((from_type, to_type));
299 /// Gets the type which implements the called function
300 fn get_implementing_type<'a>(path: &QPath<'_>, candidates: &'a [&str], function: &str) -> Option<&'a str> {
302 if let QPath::TypeRelative(ty, path) = &path;
303 if path.ident.name.as_str() == function;
304 if let TyKind::Path(QPath::Resolved(None, tp)) = &ty.kind;
305 if let [int] = tp.segments;
307 let name = int.ident.name.as_str();
308 candidates.iter().find(|c| &name == *c).copied()
315 /// Gets the type as a string, if it is a supported integer
316 fn int_ty_to_sym<'tcx>(path: &QPath<'_>) -> Option<&'tcx str> {
318 if let QPath::Resolved(_, path) = *path;
319 if let [ty] = path.segments;
321 let name = ty.ident.name.as_str();
322 INTS.iter().find(|c| &name == *c).copied()
329 /// Will return the expressions as if they were expr1 <= expr2
330 fn normalize_le_ge<'a>(op: &BinOp, left: &'a Expr<'a>, right: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
332 BinOpKind::Le => Some((left, right)),
333 BinOpKind::Ge => Some((right, left)),
339 const UINTS: &[&str] = &["u8", "u16", "u32", "u64", "usize"];
340 const SINTS: &[&str] = &["i8", "i16", "i32", "i64", "isize"];
341 const INTS: &[&str] = &["u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize"];