3 use syntax::codemap::Spanned;
4 use utils::{snippet, span_lint_and_sugg};
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
10 /// * a "negative" numeric literal (which is really a unary `-` followed by a
12 /// followed by a method call
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
18 /// **Known problems:** None.
21 /// * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7
22 /// * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1
26 "operations where precedence may be unclear"
29 #[derive(Copy, Clone)]
30 pub struct Precedence;
32 impl LintPass for Precedence {
33 fn get_lints(&self) -> LintArray {
34 lint_array!(PRECEDENCE)
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| {
46 "operator precedence can trip the unwary",
47 "consider parenthesizing your expression",
55 match (is_arith_expr(left), is_arith_expr(right)) {
59 snippet(cx, left.span, ".."),
61 snippet(cx, right.span, "..")
63 span_sugg(expr, sugg);
68 snippet(cx, left.span, ".."),
70 snippet(cx, right.span, "..")
72 span_sugg(expr, sugg);
77 snippet(cx, left.span, ".."),
79 snippet(cx, right.span, "..")
81 span_sugg(expr, sugg);
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 {
92 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
97 "unary minus has lower precedence than method call",
98 "consider adding parentheses to clarify your intent",
99 format!("-({})", snippet(cx, rhs.span, "..")),
111 fn is_arith_expr(expr: &Expr) -> bool {
113 ExprKind::Binary(Spanned { node: op, .. }, _, _) => is_arith_op(op),
118 fn is_bit_op(op: BinOpKind) -> bool {
119 use syntax::ast::BinOpKind::*;
121 BitXor | BitAnd | BitOr | Shl | Shr => true,
126 fn is_arith_op(op: BinOpKind) -> bool {
127 use syntax::ast::BinOpKind::*;
129 Add | Sub | Mul | Div | Rem => true,