2 use syntax::codemap::Spanned;
4 use syntax::ast_util::binop_to_string;
6 use utils::{span_lint, snippet};
8 /// **What it does:** This lint checks for operations where precedence may be unclear and `Warn`'s about them by default, suggesting to add parentheses. Currently it catches the following:
9 /// * mixed usage of arithmetic and bit shifting/combining operators without parentheses
10 /// * a "negative" numeric literal (which is really a unary `-` followed by a numeric literal) followed by a method call
12 /// **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.
14 /// **Known problems:** None
17 /// * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7
18 /// * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1
19 declare_lint!(pub PRECEDENCE, Warn,
20 "catches operations where precedence may be unclear. See the wiki for a \
21 list of cases caught");
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 ExprBinary(Spanned { node: op, ..}, ref left, ref right) = expr.node {
35 if !is_bit_op(op) { return; }
36 match (is_arith_expr(left), is_arith_expr(right)) {
37 (true, true) => span_lint(cx, PRECEDENCE, expr.span,
38 &format!("operator precedence can trip the unwary. \
39 Consider parenthesizing your expression:\
40 `({}) {} ({})`", snippet(cx, left.span, ".."),
41 binop_to_string(op), snippet(cx, right.span, ".."))),
42 (true, false) => span_lint(cx, PRECEDENCE, expr.span,
43 &format!("operator precedence can trip the unwary. \
44 Consider parenthesizing your expression:\
45 `({}) {} {}`", snippet(cx, left.span, ".."),
46 binop_to_string(op), snippet(cx, right.span, ".."))),
47 (false, true) => span_lint(cx, PRECEDENCE, expr.span,
48 &format!("operator precedence can trip the unwary. \
49 Consider parenthesizing your expression:\
50 `{} {} ({})`", snippet(cx, left.span, ".."),
51 binop_to_string(op), snippet(cx, right.span, ".."))),
56 if let ExprUnary(UnNeg, ref rhs) = expr.node {
57 if let ExprMethodCall(_, _, ref args) = rhs.node {
58 if let Some(slf) = args.first() {
59 if let ExprLit(ref lit) = slf.node {
61 LitInt(..) | LitFloat(..) | LitFloatUnsuffixed(..) =>
62 span_lint(cx, PRECEDENCE, expr.span, &format!(
63 "unary minus has lower precedence than \
64 method call. Consider adding parentheses \
65 to clarify your intent: -({})",
66 snippet(cx, rhs.span, ".."))),
76 fn is_arith_expr(expr: &Expr) -> bool {
78 ExprBinary(Spanned { node: op, ..}, _, _) => is_arith_op(op),
83 fn is_bit_op(op: BinOp_) -> bool {
85 BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => true,
90 fn is_arith_op(op: BinOp_) -> bool {
92 BiAdd | BiSub | BiMul | BiDiv | BiRem => true,