3 use syntax::codemap::Spanned;
4 use utils::{span_lint, snippet};
6 /// **What it does:** This lint checks for operations where precedence may be unclear and suggests
7 /// to add parentheses. Currently it catches the following:
8 /// * mixed usage of arithmetic and bit shifting/combining operators without parentheses
9 /// * a "negative" numeric literal (which is really a unary `-` followed by a numeric literal)
10 /// followed by a method call
12 /// **Why is this bad?** Because not everyone knows the precedence of those operators by heart, so
13 /// expressions like these may trip others trying to reason about the code.
15 /// **Known problems:** None
18 /// * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7
19 /// * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1
22 "catches operations where precedence may be unclear"
26 pub struct Precedence;
28 impl LintPass for Precedence {
29 fn get_lints(&self) -> LintArray {
30 lint_array!(PRECEDENCE)
34 impl EarlyLintPass for Precedence {
35 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
36 if let ExprKind::Binary(Spanned { node: op, .. }, ref left, ref right) = expr.node {
40 match (is_arith_expr(left), is_arith_expr(right)) {
45 &format!("operator precedence can trip the unwary. Consider parenthesizing your \
46 expression:`({}) {} ({})`",
47 snippet(cx, left.span, ".."),
49 snippet(cx, right.span, "..")));
55 &format!("operator precedence can trip the unwary. Consider parenthesizing your \
56 expression:`({}) {} {}`",
57 snippet(cx, left.span, ".."),
59 snippet(cx, right.span, "..")));
65 &format!("operator precedence can trip the unwary. Consider parenthesizing your \
66 expression:`{} {} ({})`",
67 snippet(cx, left.span, ".."),
69 snippet(cx, right.span, "..")));
75 if let ExprKind::Unary(UnOp::Neg, ref rhs) = expr.node {
76 if let ExprKind::MethodCall(_, _, ref args) = rhs.node {
77 if let Some(slf) = args.first() {
78 if let ExprKind::Lit(ref lit) = slf.node {
82 LitKind::FloatUnsuffixed(..) => {
86 &format!("unary minus has lower precedence than method call. Consider \
87 adding parentheses to clarify your intent: -({})",
88 snippet(cx, rhs.span, "..")));
99 fn is_arith_expr(expr: &Expr) -> bool {
101 ExprKind::Binary(Spanned { node: op, .. }, _, _) => is_arith_op(op),
106 fn is_bit_op(op: BinOpKind) -> bool {
107 use syntax::ast::BinOpKind::*;
109 BitXor | BitAnd | BitOr | Shl | Shr => true,
114 fn is_arith_op(op: BinOpKind) -> bool {
115 use syntax::ast::BinOpKind::*;
117 Add | Sub | Mul | Div | Rem => true,