3 use syntax::codemap::Spanned;
4 use utils::{span_lint_and_then, snippet};
6 /// **What it does:** Checks for operations where precedence may be unclear
7 /// and suggests 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?** Not everyone knows the precedence of those operators by
13 /// heart, so expressions like these may trip others trying to reason about the
16 /// **Known problems:** None.
19 /// * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7
20 /// * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1
24 "operations where precedence may be unclear"
28 pub struct Precedence;
30 impl LintPass for Precedence {
31 fn get_lints(&self) -> LintArray {
32 lint_array!(PRECEDENCE)
36 impl EarlyLintPass for Precedence {
37 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
38 if let ExprKind::Binary(Spanned { node: op, .. }, ref left, ref right) = expr.node {
41 span_lint_and_then(cx, PRECEDENCE, expr.span, "operator precedence can trip the unwary", |db| {
42 db.span_suggestion(expr.span, "consider parenthesizing your expression", sugg);
49 match (is_arith_expr(left), is_arith_expr(right)) {
51 let sugg = format!("({}) {} ({})",
52 snippet(cx, left.span, ".."),
54 snippet(cx, right.span, ".."));
55 span_sugg(expr, sugg);
58 let sugg = format!("({}) {} {}",
59 snippet(cx, left.span, ".."),
61 snippet(cx, right.span, ".."));
62 span_sugg(expr, sugg);
65 let sugg = format!("{} {} ({})",
66 snippet(cx, left.span, ".."),
68 snippet(cx, right.span, ".."));
69 span_sugg(expr, sugg);
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(..) => {
83 span_lint_and_then(cx,
86 "unary minus has lower precedence than method call",
88 db.span_suggestion(expr.span,
89 "consider adding parentheses to clarify your intent",
90 format!("-({})", snippet(cx, rhs.span, "..")));
102 fn is_arith_expr(expr: &Expr) -> bool {
104 ExprKind::Binary(Spanned { node: op, .. }, _, _) => is_arith_op(op),
109 fn is_bit_op(op: BinOpKind) -> bool {
110 use syntax::ast::BinOpKind::*;
112 BitXor | BitAnd | BitOr | Shl | Shr => true,
117 fn is_arith_op(op: BinOpKind) -> bool {
118 use syntax::ast::BinOpKind::*;
120 Add | Sub | Mul | Div | Rem => true,