1 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
2 use rustc::{declare_tool_lint, lint_array};
4 use syntax::source_map::Spanned;
5 use crate::utils::{in_macro, snippet, span_lint_and_sugg};
7 /// **What it does:** Checks for operations where precedence may be unclear
8 /// and suggests to add parentheses. Currently it catches the following:
9 /// * mixed usage of arithmetic and bit shifting/combining operators without
11 /// * a "negative" numeric literal (which is really a unary `-` followed by a
13 /// followed by a method call
15 /// **Why is this bad?** Not everyone knows the precedence of those operators by
16 /// heart, so expressions like these may trip others trying to reason about the
19 /// **Known problems:** None.
22 /// * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7
23 /// * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1
24 declare_clippy_lint! {
27 "operations where precedence may be unclear"
30 #[derive(Copy, Clone)]
31 pub struct Precedence;
33 impl LintPass for Precedence {
34 fn get_lints(&self) -> LintArray {
35 lint_array!(PRECEDENCE)
39 impl EarlyLintPass for Precedence {
40 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
41 if in_macro(expr.span) {
45 if let ExprKind::Binary(Spanned { node: op, .. }, ref left, ref right) = expr.node {
46 let span_sugg = |expr: &Expr, sugg| {
51 "operator precedence can trip the unwary",
52 "consider parenthesizing your expression",
60 match (is_arith_expr(left), is_arith_expr(right)) {
64 snippet(cx, left.span, ".."),
66 snippet(cx, right.span, "..")
68 span_sugg(expr, sugg);
73 snippet(cx, left.span, ".."),
75 snippet(cx, right.span, "..")
77 span_sugg(expr, sugg);
82 snippet(cx, left.span, ".."),
84 snippet(cx, right.span, "..")
86 span_sugg(expr, sugg);
92 if let ExprKind::Unary(UnOp::Neg, ref rhs) = expr.node {
93 if let ExprKind::MethodCall(_, ref args) = rhs.node {
94 if let Some(slf) = args.first() {
95 if let ExprKind::Lit(ref lit) = slf.node {
97 LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
102 "unary minus has lower precedence than method call",
103 "consider adding parentheses to clarify your intent",
104 format!("-({})", snippet(cx, rhs.span, "..")),
116 fn is_arith_expr(expr: &Expr) -> bool {
118 ExprKind::Binary(Spanned { node: op, .. }, _, _) => is_arith_op(op),
123 fn is_bit_op(op: BinOpKind) -> bool {
124 use syntax::ast::BinOpKind::*;
126 BitXor | BitAnd | BitOr | Shl | Shr => true,
131 fn is_arith_op(op: BinOpKind) -> bool {
132 use syntax::ast::BinOpKind::*;
134 Add | Sub | Mul | Div | Rem => true,