]> git.lizzy.rs Git - rust.git/blob - src/precedence.rs
Merge pull request #494 from sanxiyn/suggestion-2
[rust.git] / src / precedence.rs
1 use rustc::lint::*;
2 use syntax::codemap::Spanned;
3 use syntax::ast::*;
4 use syntax::ast_util::binop_to_string;
5
6 use utils::{span_lint, snippet};
7
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
11 ///
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.
13 ///
14 /// **Known problems:** None
15 ///
16 /// **Examples:**
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");
22
23 #[derive(Copy,Clone)]
24 pub struct Precedence;
25
26 impl LintPass for Precedence {
27     fn get_lints(&self) -> LintArray {
28         lint_array!(PRECEDENCE)
29     }
30 }
31
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, ".."))),
52                 _ => (),
53             }
54         }
55
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 {
60                         match lit.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, ".."))),
67                             _ => ()
68                         }
69                     }
70                 }
71             }
72         }
73     }
74 }
75
76 fn is_arith_expr(expr: &Expr) -> bool {
77     match expr.node {
78         ExprBinary(Spanned { node: op, ..}, _, _) => is_arith_op(op),
79         _ => false
80     }
81 }
82
83 fn is_bit_op(op: BinOp_) -> bool {
84     match op {
85         BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => true,
86         _ => false
87     }
88 }
89
90 fn is_arith_op(op: BinOp_) -> bool {
91     match op {
92         BiAdd | BiSub | BiMul | BiDiv | BiRem => true,
93         _ => false
94     }
95 }