2019-05-12 14:14:44 -05:00
|
|
|
//! lint on manually implemented checked conversions that could be transformed into `try_from`
|
2019-05-12 07:46:16 -05:00
|
|
|
|
|
|
|
use if_chain::if_chain;
|
2020-02-29 21:23:33 -06:00
|
|
|
use rustc_ast::ast::LitKind;
|
2019-05-14 13:05:27 -05:00
|
|
|
use rustc_errors::Applicability;
|
2020-02-21 02:39:38 -06:00
|
|
|
use rustc_hir::{BinOp, BinOpKind, Expr, ExprKind, QPath, TyKind};
|
2020-01-12 00:08:41 -06:00
|
|
|
use rustc_lint::{LateContext, LateLintPass, LintContext};
|
2020-03-30 04:02:14 -05:00
|
|
|
use rustc_middle::lint::in_external_macro;
|
2020-01-11 05:37:08 -06:00
|
|
|
use rustc_session::{declare_lint_pass, declare_tool_lint};
|
2019-05-14 14:39:12 -05:00
|
|
|
|
2019-05-18 03:54:03 -05:00
|
|
|
use crate::utils::{snippet_with_applicability, span_lint_and_sugg, SpanlessEq};
|
2019-05-12 07:46:16 -05:00
|
|
|
|
|
|
|
declare_clippy_lint! {
|
|
|
|
/// **What it does:** Checks for explicit bounds checking when casting.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** Reduces the readability of statements & is error prone.
|
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
/// ```rust
|
|
|
|
/// # let foo: u32 = 5;
|
|
|
|
/// # let _ =
|
2020-04-07 17:22:42 -05:00
|
|
|
/// foo <= i32::MAX as u32
|
2019-05-12 07:46:16 -05:00
|
|
|
/// # ;
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Could be written:
|
|
|
|
///
|
|
|
|
/// ```rust
|
2019-08-03 11:42:05 -05:00
|
|
|
/// # use std::convert::TryFrom;
|
|
|
|
/// # let foo = 1;
|
2019-05-12 07:46:16 -05:00
|
|
|
/// # let _ =
|
|
|
|
/// i32::try_from(foo).is_ok()
|
|
|
|
/// # ;
|
|
|
|
/// ```
|
|
|
|
pub CHECKED_CONVERSIONS,
|
|
|
|
pedantic,
|
|
|
|
"`try_from` could replace manual bounds checking when casting"
|
|
|
|
}
|
|
|
|
|
|
|
|
declare_lint_pass!(CheckedConversions => [CHECKED_CONVERSIONS]);
|
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
impl<'tcx> LateLintPass<'tcx> for CheckedConversions {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'_>, item: &Expr<'_>) {
|
2019-05-12 07:46:16 -05:00
|
|
|
let result = if_chain! {
|
|
|
|
if !in_external_macro(cx.sess(), item.span);
|
2019-09-27 10:16:06 -05:00
|
|
|
if let ExprKind::Binary(op, ref left, ref right) = &item.kind;
|
2019-05-12 07:46:16 -05:00
|
|
|
|
|
|
|
then {
|
|
|
|
match op.node {
|
|
|
|
BinOpKind::Ge | BinOpKind::Le => single_check(item),
|
|
|
|
BinOpKind::And => double_check(cx, left, right),
|
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-06-09 09:36:01 -05:00
|
|
|
if let Some(cv) = result {
|
|
|
|
if let Some(to_type) = cv.to_type {
|
2019-05-14 13:05:27 -05:00
|
|
|
let mut applicability = Applicability::MachineApplicable;
|
2020-06-09 09:36:01 -05:00
|
|
|
let snippet = snippet_with_applicability(cx, cv.expr_to_cast.span, "_", &mut applicability);
|
2019-05-14 13:05:27 -05:00
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
CHECKED_CONVERSIONS,
|
|
|
|
item.span,
|
|
|
|
"Checked cast can be simplified.",
|
|
|
|
"try",
|
2020-06-09 09:36:01 -05:00
|
|
|
format!("{}::try_from({}).is_ok()", to_type, snippet),
|
|
|
|
applicability,
|
2019-05-14 13:05:27 -05:00
|
|
|
);
|
|
|
|
}
|
2019-05-12 07:46:16 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Searches for a single check from unsigned to _ is done
|
|
|
|
/// todo: check for case signed -> larger unsigned == only x >= 0
|
2019-12-27 01:12:26 -06:00
|
|
|
fn single_check<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
|
2019-05-12 07:46:16 -05:00
|
|
|
check_upper_bound(expr).filter(|cv| cv.cvt == ConversionType::FromUnsigned)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Searches for a combination of upper & lower bound checks
|
2020-06-25 15:41:36 -05:00
|
|
|
fn double_check<'a>(cx: &LateContext<'_>, left: &'a Expr<'_>, right: &'a Expr<'_>) -> Option<Conversion<'a>> {
|
2019-05-12 07:46:16 -05:00
|
|
|
let upper_lower = |l, r| {
|
|
|
|
let upper = check_upper_bound(l);
|
|
|
|
let lower = check_lower_bound(r);
|
|
|
|
|
2020-06-12 20:27:14 -05:00
|
|
|
upper.zip(lower).and_then(|(l, r)| l.combine(r, cx))
|
2019-05-12 07:46:16 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
upper_lower(left, right).or_else(|| upper_lower(right, left))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Contains the result of a tried conversion check
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
struct Conversion<'a> {
|
|
|
|
cvt: ConversionType,
|
2019-12-27 01:12:26 -06:00
|
|
|
expr_to_cast: &'a Expr<'a>,
|
2019-05-18 03:54:03 -05:00
|
|
|
to_type: Option<&'a str>,
|
2019-05-12 07:46:16 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// The kind of conversion that is checked
|
|
|
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
|
|
|
enum ConversionType {
|
|
|
|
SignedToUnsigned,
|
|
|
|
SignedToSigned,
|
|
|
|
FromUnsigned,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Conversion<'a> {
|
|
|
|
/// Combine multiple conversions if the are compatible
|
2020-06-25 15:41:36 -05:00
|
|
|
pub fn combine(self, other: Self, cx: &LateContext<'_>) -> Option<Conversion<'a>> {
|
2019-05-12 07:46:16 -05:00
|
|
|
if self.is_compatible(&other, cx) {
|
|
|
|
// Prefer a Conversion that contains a type-constraint
|
|
|
|
Some(if self.to_type.is_some() { self } else { other })
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Checks if two conversions are compatible
|
|
|
|
/// same type of conversion, same 'castee' and same 'to type'
|
2020-06-25 15:41:36 -05:00
|
|
|
pub fn is_compatible(&self, other: &Self, cx: &LateContext<'_>) -> bool {
|
2019-05-12 07:46:16 -05:00
|
|
|
(self.cvt == other.cvt)
|
|
|
|
&& (SpanlessEq::new(cx).eq_expr(self.expr_to_cast, other.expr_to_cast))
|
|
|
|
&& (self.has_compatible_to_type(other))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Checks if the to-type is the same (if there is a type constraint)
|
|
|
|
fn has_compatible_to_type(&self, other: &Self) -> bool {
|
2020-06-12 20:27:14 -05:00
|
|
|
match (self.to_type, other.to_type) {
|
|
|
|
(Some(l), Some(r)) => l == r,
|
|
|
|
_ => true,
|
|
|
|
}
|
2019-05-12 07:46:16 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Try to construct a new conversion if the conversion type is valid
|
2019-12-27 01:12:26 -06:00
|
|
|
fn try_new(expr_to_cast: &'a Expr<'_>, from_type: &str, to_type: &'a str) -> Option<Conversion<'a>> {
|
2019-05-14 14:39:12 -05:00
|
|
|
ConversionType::try_new(from_type, to_type).map(|cvt| Conversion {
|
2019-05-12 07:46:16 -05:00
|
|
|
cvt,
|
|
|
|
expr_to_cast,
|
|
|
|
to_type: Some(to_type),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Construct a new conversion without type constraint
|
2019-12-27 01:12:26 -06:00
|
|
|
fn new_any(expr_to_cast: &'a Expr<'_>) -> Conversion<'a> {
|
2019-05-12 07:46:16 -05:00
|
|
|
Conversion {
|
|
|
|
cvt: ConversionType::SignedToUnsigned,
|
|
|
|
expr_to_cast,
|
|
|
|
to_type: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ConversionType {
|
|
|
|
/// Creates a conversion type if the type is allowed & conversion is valid
|
2019-09-18 01:37:41 -05:00
|
|
|
#[must_use]
|
2019-05-18 03:54:03 -05:00
|
|
|
fn try_new(from: &str, to: &str) -> Option<Self> {
|
2019-05-14 14:39:12 -05:00
|
|
|
if UINTS.contains(&from) {
|
2019-07-30 19:25:35 -05:00
|
|
|
Some(Self::FromUnsigned)
|
2019-05-14 14:39:12 -05:00
|
|
|
} else if SINTS.contains(&from) {
|
|
|
|
if UINTS.contains(&to) {
|
2019-07-30 19:25:35 -05:00
|
|
|
Some(Self::SignedToUnsigned)
|
2019-05-14 14:39:12 -05:00
|
|
|
} else if SINTS.contains(&to) {
|
2019-07-30 19:25:35 -05:00
|
|
|
Some(Self::SignedToSigned)
|
2019-05-12 07:46:16 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-07 17:22:42 -05:00
|
|
|
/// Check for `expr <= (to_type::MAX as from_type)`
|
2019-12-27 01:12:26 -06:00
|
|
|
fn check_upper_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
|
2019-05-12 07:46:16 -05:00
|
|
|
if_chain! {
|
2019-09-27 10:16:06 -05:00
|
|
|
if let ExprKind::Binary(ref op, ref left, ref right) = &expr.kind;
|
2019-05-12 07:46:16 -05:00
|
|
|
if let Some((candidate, check)) = normalize_le_ge(op, left, right);
|
2020-06-09 09:36:01 -05:00
|
|
|
if let Some((from, to)) = get_types_from_cast(check, INTS, "max_value", "MAX");
|
2019-05-12 07:46:16 -05:00
|
|
|
|
|
|
|
then {
|
2019-05-14 14:39:12 -05:00
|
|
|
Conversion::try_new(candidate, from, to)
|
2019-05-12 07:46:16 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-07 17:22:42 -05:00
|
|
|
/// Check for `expr >= 0|(to_type::MIN as from_type)`
|
2019-12-27 01:12:26 -06:00
|
|
|
fn check_lower_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
|
|
|
|
fn check_function<'a>(candidate: &'a Expr<'a>, check: &'a Expr<'a>) -> Option<Conversion<'a>> {
|
2019-05-12 07:46:16 -05:00
|
|
|
(check_lower_bound_zero(candidate, check)).or_else(|| (check_lower_bound_min(candidate, check)))
|
|
|
|
}
|
|
|
|
|
|
|
|
// First of we need a binary containing the expression & the cast
|
2019-09-27 10:16:06 -05:00
|
|
|
if let ExprKind::Binary(ref op, ref left, ref right) = &expr.kind {
|
2019-05-12 07:46:16 -05:00
|
|
|
normalize_le_ge(op, right, left).and_then(|(l, r)| check_function(l, r))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Check for `expr >= 0`
|
2019-12-27 01:12:26 -06:00
|
|
|
fn check_lower_bound_zero<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
|
2019-05-12 07:46:16 -05:00
|
|
|
if_chain! {
|
2019-09-27 10:16:06 -05:00
|
|
|
if let ExprKind::Lit(ref lit) = &check.kind;
|
2019-05-12 07:46:16 -05:00
|
|
|
if let LitKind::Int(0, _) = &lit.node;
|
|
|
|
|
|
|
|
then {
|
|
|
|
Some(Conversion::new_any(candidate))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-07 17:22:42 -05:00
|
|
|
/// Check for `expr >= (to_type::MIN as from_type)`
|
2019-12-27 01:12:26 -06:00
|
|
|
fn check_lower_bound_min<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
|
2020-06-09 09:36:01 -05:00
|
|
|
if let Some((from, to)) = get_types_from_cast(check, SINTS, "min_value", "MIN") {
|
2019-05-14 14:39:12 -05:00
|
|
|
Conversion::try_new(candidate, from, to)
|
2019-05-12 07:46:16 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Tries to extract the from- and to-type from a cast expression
|
2020-06-09 09:36:01 -05:00
|
|
|
fn get_types_from_cast<'a>(
|
|
|
|
expr: &'a Expr<'_>,
|
|
|
|
types: &'a [&str],
|
|
|
|
func: &'a str,
|
|
|
|
assoc_const: &'a str,
|
|
|
|
) -> Option<(&'a str, &'a str)> {
|
|
|
|
// `to_type::max_value() as from_type`
|
|
|
|
// or `to_type::MAX as from_type`
|
2019-12-27 01:12:26 -06:00
|
|
|
let call_from_cast: Option<(&Expr<'_>, &str)> = if_chain! {
|
2020-06-09 09:36:01 -05:00
|
|
|
// to_type::max_value(), from_type
|
2019-09-27 10:16:06 -05:00
|
|
|
if let ExprKind::Cast(ref limit, ref from_type) = &expr.kind;
|
|
|
|
if let TyKind::Path(ref from_type_path) = &from_type.kind;
|
2019-05-14 14:39:12 -05:00
|
|
|
if let Some(from_sym) = int_ty_to_sym(from_type_path);
|
2019-05-12 07:46:16 -05:00
|
|
|
|
|
|
|
then {
|
2019-05-14 14:39:12 -05:00
|
|
|
Some((limit, from_sym))
|
2019-05-12 07:46:16 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-06-09 09:36:01 -05:00
|
|
|
// `from_type::from(to_type::max_value())`
|
2019-12-27 01:12:26 -06:00
|
|
|
let limit_from: Option<(&Expr<'_>, &str)> = call_from_cast.or_else(|| {
|
2019-05-12 07:46:16 -05:00
|
|
|
if_chain! {
|
2020-06-09 09:36:01 -05:00
|
|
|
// `from_type::from, to_type::max_value()`
|
2019-09-27 10:16:06 -05:00
|
|
|
if let ExprKind::Call(ref from_func, ref args) = &expr.kind;
|
2020-06-09 09:36:01 -05:00
|
|
|
// `to_type::max_value()`
|
2019-05-12 07:46:16 -05:00
|
|
|
if args.len() == 1;
|
|
|
|
if let limit = &args[0];
|
|
|
|
// `from_type::from`
|
2019-09-27 10:16:06 -05:00
|
|
|
if let ExprKind::Path(ref path) = &from_func.kind;
|
2020-06-09 09:36:01 -05:00
|
|
|
if let Some(from_sym) = get_implementing_type(path, INTS, "from");
|
2019-05-12 07:46:16 -05:00
|
|
|
|
|
|
|
then {
|
2019-05-14 14:39:12 -05:00
|
|
|
Some((limit, from_sym))
|
2019-05-12 07:46:16 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if let Some((limit, from_type)) = limit_from {
|
2020-06-09 09:36:01 -05:00
|
|
|
match limit.kind {
|
|
|
|
// `from_type::from(_)`
|
|
|
|
ExprKind::Call(path, _) => {
|
|
|
|
if let ExprKind::Path(ref path) = path.kind {
|
|
|
|
// `to_type`
|
|
|
|
if let Some(to_type) = get_implementing_type(path, types, func) {
|
|
|
|
return Some((from_type, to_type));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
// `to_type::MAX`
|
|
|
|
ExprKind::Path(ref path) => {
|
|
|
|
if let Some(to_type) = get_implementing_type(path, types, assoc_const) {
|
|
|
|
return Some((from_type, to_type));
|
|
|
|
}
|
|
|
|
},
|
|
|
|
_ => {},
|
2019-05-12 07:46:16 -05:00
|
|
|
}
|
2020-06-09 09:36:01 -05:00
|
|
|
};
|
|
|
|
None
|
2019-05-12 07:46:16 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Gets the type which implements the called function
|
2019-12-29 22:02:10 -06:00
|
|
|
fn get_implementing_type<'a>(path: &QPath<'_>, candidates: &'a [&str], function: &str) -> Option<&'a str> {
|
2019-05-12 07:46:16 -05:00
|
|
|
if_chain! {
|
|
|
|
if let QPath::TypeRelative(ref ty, ref path) = &path;
|
2019-05-18 03:54:03 -05:00
|
|
|
if path.ident.name.as_str() == function;
|
2019-09-27 10:16:06 -05:00
|
|
|
if let TyKind::Path(QPath::Resolved(None, ref tp)) = &ty.kind;
|
2019-05-12 07:46:16 -05:00
|
|
|
if let [int] = &*tp.segments;
|
2019-05-18 03:54:03 -05:00
|
|
|
let name = &int.ident.name.as_str();
|
2019-05-12 07:46:16 -05:00
|
|
|
|
|
|
|
then {
|
2019-05-18 03:54:03 -05:00
|
|
|
candidates.iter().find(|c| name == *c).cloned()
|
2019-05-12 07:46:16 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Gets the type as a string, if it is a supported integer
|
2019-12-29 22:02:10 -06:00
|
|
|
fn int_ty_to_sym<'tcx>(path: &QPath<'_>) -> Option<&'tcx str> {
|
2019-05-12 07:46:16 -05:00
|
|
|
if_chain! {
|
|
|
|
if let QPath::Resolved(_, ref path) = *path;
|
|
|
|
if let [ty] = &*path.segments;
|
2019-05-18 03:54:03 -05:00
|
|
|
let name = &ty.ident.name.as_str();
|
2019-05-12 07:46:16 -05:00
|
|
|
|
|
|
|
then {
|
2019-05-18 03:54:03 -05:00
|
|
|
INTS.iter().find(|c| name == *c).cloned()
|
2019-05-12 07:46:16 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Will return the expressions as if they were expr1 <= expr2
|
2019-12-27 01:12:26 -06:00
|
|
|
fn normalize_le_ge<'a>(op: &BinOp, left: &'a Expr<'a>, right: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
|
2019-05-12 07:46:16 -05:00
|
|
|
match op.node {
|
|
|
|
BinOpKind::Le => Some((left, right)),
|
|
|
|
BinOpKind::Ge => Some((right, left)),
|
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-18 03:54:03 -05:00
|
|
|
// Constants
|
|
|
|
const UINTS: &[&str] = &["u8", "u16", "u32", "u64", "usize"];
|
|
|
|
const SINTS: &[&str] = &["i8", "i16", "i32", "i64", "isize"];
|
|
|
|
const INTS: &[&str] = &["u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize"];
|