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 to add parentheses. Currently it catches the following:
7 /// * mixed usage of arithmetic and bit shifting/combining operators without parentheses
8 /// * a "negative" numeric literal (which is really a unary `-` followed by a numeric literal) followed by a method call
10 /// **Why is this bad?** Because not everyone knows the precedence of those operators by heart, so expressions like these may trip others trying to reason about the code.
12 /// **Known problems:** None
15 /// * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7
16 /// * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1
19 "catches operations where precedence may be unclear. See the wiki for a \
24 pub struct Precedence;
26 impl LintPass for Precedence {
27 fn get_lints(&self) -> LintArray {
28 lint_array!(PRECEDENCE)
32 impl EarlyLintPass for Precedence {
33 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
34 if let ExprKind::Binary(Spanned { node: op, .. }, ref left, ref right) = expr.node {
38 match (is_arith_expr(left), is_arith_expr(right)) {
43 &format!("operator precedence can trip the unwary. Consider parenthesizing your \
44 expression:`({}) {} ({})`",
45 snippet(cx, left.span, ".."),
47 snippet(cx, right.span, "..")));
53 &format!("operator precedence can trip the unwary. Consider parenthesizing your \
54 expression:`({}) {} {}`",
55 snippet(cx, left.span, ".."),
57 snippet(cx, right.span, "..")));
63 &format!("operator precedence can trip the unwary. Consider parenthesizing your \
64 expression:`{} {} ({})`",
65 snippet(cx, left.span, ".."),
67 snippet(cx, right.span, "..")));
73 if let ExprKind::Unary(UnOp::Neg, ref rhs) = expr.node {
74 if let ExprKind::MethodCall(_, _, ref args) = rhs.node {
75 if let Some(slf) = args.first() {
76 if let ExprKind::Lit(ref lit) = slf.node {
80 LitKind::FloatUnsuffixed(..) => {
84 &format!("unary minus has lower precedence than method call. Consider \
85 adding parentheses to clarify your intent: -({})",
86 snippet(cx, rhs.span, "..")));
97 fn is_arith_expr(expr: &Expr) -> bool {
99 ExprKind::Binary(Spanned { node: op, .. }, _, _) => is_arith_op(op),
104 fn is_bit_op(op: BinOpKind) -> bool {
105 use syntax::ast::BinOpKind::*;
107 BitXor | BitAnd | BitOr | Shl | Shr => true,
112 fn is_arith_op(op: BinOpKind) -> bool {
113 use syntax::ast::BinOpKind::*;
115 Add | Sub | Mul | Div | Rem => true,