2 use syntax::codemap::Spanned;
5 use utils::{span_lint, snippet};
7 /// **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:
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) followed by a method call
11 /// **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 /// **Known problems:** None
16 /// * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7
17 /// * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1
18 declare_lint!(pub PRECEDENCE, Warn,
19 "catches operations where precedence may be unclear. See the wiki for a \
20 list of cases caught");
23 pub struct Precedence;
25 impl LintPass for Precedence {
26 fn get_lints(&self) -> LintArray {
27 lint_array!(PRECEDENCE)
31 impl EarlyLintPass for Precedence {
32 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
33 if let ExprBinary(Spanned { node: op, ..}, ref left, ref right) = expr.node {
34 if !is_bit_op(op) { return; }
35 match (is_arith_expr(left), is_arith_expr(right)) {
36 (true, true) => span_lint(cx, PRECEDENCE, expr.span,
37 &format!("operator precedence can trip the unwary. \
38 Consider parenthesizing your expression:\
39 `({}) {} ({})`", snippet(cx, left.span, ".."),
40 op.to_string(), snippet(cx, right.span, ".."))),
41 (true, false) => span_lint(cx, PRECEDENCE, expr.span,
42 &format!("operator precedence can trip the unwary. \
43 Consider parenthesizing your expression:\
44 `({}) {} {}`", snippet(cx, left.span, ".."),
45 op.to_string(), snippet(cx, right.span, ".."))),
46 (false, true) => span_lint(cx, PRECEDENCE, expr.span,
47 &format!("operator precedence can trip the unwary. \
48 Consider parenthesizing your expression:\
49 `{} {} ({})`", snippet(cx, left.span, ".."),
50 op.to_string(), snippet(cx, right.span, ".."))),
55 if let ExprUnary(UnNeg, ref rhs) = expr.node {
56 if let ExprMethodCall(_, _, ref args) = rhs.node {
57 if let Some(slf) = args.first() {
58 if let ExprLit(ref lit) = slf.node {
60 LitInt(..) | LitFloat(..) | LitFloatUnsuffixed(..) =>
61 span_lint(cx, PRECEDENCE, expr.span, &format!(
62 "unary minus has lower precedence than \
63 method call. Consider adding parentheses \
64 to clarify your intent: -({})",
65 snippet(cx, rhs.span, ".."))),
75 fn is_arith_expr(expr: &Expr) -> bool {
77 ExprBinary(Spanned { node: op, ..}, _, _) => is_arith_op(op),
82 fn is_bit_op(op: BinOp_) -> bool {
84 BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => true,
89 fn is_arith_op(op: BinOp_) -> bool {
91 BiAdd | BiSub | BiMul | BiDiv | BiRem => true,