|
| 1 | +use crate::utils::{span_help_and_lint, span_lint_and_sugg}; |
| 2 | +use if_chain::if_chain; |
| 3 | +use rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintPass}; |
| 4 | +use rustc::{declare_lint_pass, declare_tool_lint}; |
| 5 | +use rustc_errors::Applicability; |
| 6 | +use syntax::ast::{BinOpKind, Expr, ExprKind, LitKind}; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// **What it does:** Checks for use of `^` operator when exponentiation was intended. |
| 10 | + /// |
| 11 | + /// **Why is this bad?** This is most probably a typo. |
| 12 | + /// |
| 13 | + /// **Known problems:** None. |
| 14 | + /// |
| 15 | + /// **Example:** |
| 16 | + /// |
| 17 | + /// ```rust,ignore |
| 18 | + /// // Bad |
| 19 | + /// 2 ^ 16; |
| 20 | + /// |
| 21 | + /// // Good |
| 22 | + /// 1 << 16; |
| 23 | + /// 2i32.pow(16); |
| 24 | + /// ``` |
| 25 | + pub XOR_USED_AS_POW, |
| 26 | + correctness, |
| 27 | + "use of `^` operator when exponentiation was intended" |
| 28 | +} |
| 29 | + |
| 30 | +declare_lint_pass!(XorUsedAsPow => [XOR_USED_AS_POW]); |
| 31 | + |
| 32 | +impl EarlyLintPass for XorUsedAsPow { |
| 33 | + fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) { |
| 34 | + if_chain! { |
| 35 | + if !in_external_macro(cx.sess, expr.span); |
| 36 | + if let ExprKind::Binary(op, left, right) = &expr.node; |
| 37 | + if BinOpKind::BitXor == op.node; |
| 38 | + if let ExprKind::Lit(lit) = &left.node; |
| 39 | + if let LitKind::Int(lhs, _) = lit.node; |
| 40 | + if let ExprKind::Lit(lit) = &right.node; |
| 41 | + if let LitKind::Int(rhs, _) = lit.node; |
| 42 | + then { |
| 43 | + if lhs == 2 { |
| 44 | + if rhs == 8 || rhs == 16 || rhs == 32 || rhs == 64 { |
| 45 | + span_lint_and_sugg( |
| 46 | + cx, |
| 47 | + XOR_USED_AS_POW, |
| 48 | + expr.span, |
| 49 | + "it appears you are trying to get the maximum value of an integer, but `^` is not an exponentiation operator", |
| 50 | + "try", |
| 51 | + format!("std::u{}::MAX", rhs), |
| 52 | + Applicability::MaybeIncorrect, |
| 53 | + ) |
| 54 | + } else { |
| 55 | + span_lint_and_sugg( |
| 56 | + cx, |
| 57 | + XOR_USED_AS_POW, |
| 58 | + expr.span, |
| 59 | + "it appears you are trying to get a power of two, but `^` is not an exponentiation operator", |
| 60 | + "use a bitshift instead", |
| 61 | + format!("1 << {}", rhs), |
| 62 | + Applicability::MaybeIncorrect, |
| 63 | + ) |
| 64 | + } |
| 65 | + } else { |
| 66 | + span_help_and_lint( |
| 67 | + cx, |
| 68 | + XOR_USED_AS_POW, |
| 69 | + expr.span, |
| 70 | + "`^` is not an exponentiation operator but appears to have been used as one", |
| 71 | + "did you mean to use .pow()?" |
| 72 | + ) |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments