1 use crate::utils::span_lint;
4 use rustc::{declare_lint, lint_array};
5 use syntax::codemap::Span;
7 /// **What it does:** Checks for plain integer arithmetic.
9 /// **Why is this bad?** This is only checked against overflow in debug builds.
10 /// In some applications one wants explicitly checked, wrapping or saturating
13 /// **Known problems:** None.
19 declare_clippy_lint! {
20 pub INTEGER_ARITHMETIC,
22 "any integer arithmetic statement"
25 /// **What it does:** Checks for float arithmetic.
27 /// **Why is this bad?** For some embedded systems or kernel development, it
28 /// can be useful to rule out floating-point numbers.
30 /// **Known problems:** None.
36 declare_clippy_lint! {
39 "any floating-point arithmetic statement"
42 #[derive(Copy, Clone, Default)]
43 pub struct Arithmetic {
47 impl LintPass for Arithmetic {
48 fn get_lints(&self) -> LintArray {
49 lint_array!(INTEGER_ARITHMETIC, FLOAT_ARITHMETIC)
53 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Arithmetic {
54 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
55 if self.span.is_some() {
59 hir::ExprKind::Binary(ref op, ref l, ref r) => {
63 | hir::BinOpKind::BitAnd
64 | hir::BinOpKind::BitOr
65 | hir::BinOpKind::BitXor
73 | hir::BinOpKind::Gt => return,
76 let (l_ty, r_ty) = (cx.tables.expr_ty(l), cx.tables.expr_ty(r));
77 if l_ty.is_integral() && r_ty.is_integral() {
78 span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected");
79 self.span = Some(expr.span);
80 } else if l_ty.is_floating_point() && r_ty.is_floating_point() {
81 span_lint(cx, FLOAT_ARITHMETIC, expr.span, "floating-point arithmetic detected");
82 self.span = Some(expr.span);
85 hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
86 let ty = cx.tables.expr_ty(arg);
88 span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected");
89 self.span = Some(expr.span);
90 } else if ty.is_floating_point() {
91 span_lint(cx, FLOAT_ARITHMETIC, expr.span, "floating-point arithmetic detected");
92 self.span = Some(expr.span);
99 fn check_expr_post(&mut self, _: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
100 if Some(expr.span) == self.span {