]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/precedence.rs
Fix lines that exceed max width manually
[rust.git] / clippy_lints / src / precedence.rs
1 use rustc::lint::*;
2 use syntax::ast::*;
3 use syntax::codemap::Spanned;
4 use utils::{snippet, span_lint_and_sugg};
5
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
9 /// parentheses
10 /// * a "negative" numeric literal (which is really a unary `-` followed by a
11 /// numeric literal)
12 ///   followed by a method call
13 ///
14 /// **Why is this bad?** Not everyone knows the precedence of those operators by
15 /// heart, so expressions like these may trip others trying to reason about the
16 /// code.
17 ///
18 /// **Known problems:** None.
19 ///
20 /// **Example:**
21 /// * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7
22 /// * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1
23 declare_lint! {
24     pub PRECEDENCE,
25     Warn,
26     "operations where precedence may be unclear"
27 }
28
29 #[derive(Copy, Clone)]
30 pub struct Precedence;
31
32 impl LintPass for Precedence {
33     fn get_lints(&self) -> LintArray {
34         lint_array!(PRECEDENCE)
35     }
36 }
37
38 impl EarlyLintPass for Precedence {
39     fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
40         if let ExprKind::Binary(Spanned { node: op, .. }, ref left, ref right) = expr.node {
41             let span_sugg = |expr: &Expr, sugg| {
42                 span_lint_and_sugg(
43                     cx,
44                     PRECEDENCE,
45                     expr.span,
46                     "operator precedence can trip the unwary",
47                     "consider parenthesizing your expression",
48                     sugg,
49                 );
50             };
51
52             if !is_bit_op(op) {
53                 return;
54             }
55             match (is_arith_expr(left), is_arith_expr(right)) {
56                 (true, true) => {
57                     let sugg = format!(
58                         "({}) {} ({})",
59                         snippet(cx, left.span, ".."),
60                         op.to_string(),
61                         snippet(cx, right.span, "..")
62                     );
63                     span_sugg(expr, sugg);
64                 },
65                 (true, false) => {
66                     let sugg = format!(
67                         "({}) {} {}",
68                         snippet(cx, left.span, ".."),
69                         op.to_string(),
70                         snippet(cx, right.span, "..")
71                     );
72                     span_sugg(expr, sugg);
73                 },
74                 (false, true) => {
75                     let sugg = format!(
76                         "{} {} ({})",
77                         snippet(cx, left.span, ".."),
78                         op.to_string(),
79                         snippet(cx, right.span, "..")
80                     );
81                     span_sugg(expr, sugg);
82                 },
83                 (false, false) => (),
84             }
85         }
86
87         if let ExprKind::Unary(UnOp::Neg, ref rhs) = expr.node {
88             if let ExprKind::MethodCall(_, ref args) = rhs.node {
89                 if let Some(slf) = args.first() {
90                     if let ExprKind::Lit(ref lit) = slf.node {
91                         match lit.node {
92                             LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
93                                 span_lint_and_sugg(
94                                     cx,
95                                     PRECEDENCE,
96                                     expr.span,
97                                     "unary minus has lower precedence than method call",
98                                     "consider adding parentheses to clarify your intent",
99                                     format!("-({})", snippet(cx, rhs.span, "..")),
100                                 );
101                             },
102                             _ => (),
103                         }
104                     }
105                 }
106             }
107         }
108     }
109 }
110
111 fn is_arith_expr(expr: &Expr) -> bool {
112     match expr.node {
113         ExprKind::Binary(Spanned { node: op, .. }, _, _) => is_arith_op(op),
114         _ => false,
115     }
116 }
117
118 fn is_bit_op(op: BinOpKind) -> bool {
119     use syntax::ast::BinOpKind::*;
120     match op {
121         BitXor | BitAnd | BitOr | Shl | Shr => true,
122         _ => false,
123     }
124 }
125
126 fn is_arith_op(op: BinOpKind) -> bool {
127     use syntax::ast::BinOpKind::*;
128     match op {
129         Add | Sub | Mul | Div | Rem => true,
130         _ => false,
131     }
132 }