1 use crate::utils::{snippet_with_applicability, span_lint_and_sugg};
2 use rustc::declare_lint_pass;
3 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
4 use rustc_errors::Applicability;
5 use rustc_session::declare_tool_lint;
7 use syntax::source_map::Spanned;
10 /// **What it does:** Checks for operations where precedence may be unclear
11 /// and suggests to add parentheses. Currently it catches the following:
12 /// * mixed usage of arithmetic and bit shifting/combining operators without
14 /// * a "negative" numeric literal (which is really a unary `-` followed by a
16 /// followed by a method call
18 /// **Why is this bad?** Not everyone knows the precedence of those operators by
19 /// heart, so expressions like these may trip others trying to reason about the
22 /// **Known problems:** None.
25 /// * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7
26 /// * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1
29 "operations where precedence may be unclear"
32 declare_lint_pass!(Precedence => [PRECEDENCE]);
34 impl EarlyLintPass for Precedence {
35 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
36 if expr.span.from_expansion() {
40 if let ExprKind::Binary(Spanned { node: op, .. }, ref left, ref right) = expr.kind {
41 let span_sugg = |expr: &Expr, sugg, appl| {
46 "operator precedence can trip the unwary",
47 "consider parenthesizing your expression",
56 let mut applicability = Applicability::MachineApplicable;
57 match (is_arith_expr(left), is_arith_expr(right)) {
61 snippet_with_applicability(cx, left.span, "..", &mut applicability),
63 snippet_with_applicability(cx, right.span, "..", &mut applicability)
65 span_sugg(expr, sugg, applicability);
70 snippet_with_applicability(cx, left.span, "..", &mut applicability),
72 snippet_with_applicability(cx, right.span, "..", &mut applicability)
74 span_sugg(expr, sugg, applicability);
79 snippet_with_applicability(cx, left.span, "..", &mut applicability),
81 snippet_with_applicability(cx, right.span, "..", &mut applicability)
83 span_sugg(expr, sugg, applicability);
89 if let ExprKind::Unary(UnOp::Neg, ref rhs) = expr.kind {
90 if let ExprKind::MethodCall(_, ref args) = rhs.kind {
91 if let Some(slf) = args.first() {
92 if let ExprKind::Lit(ref lit) = slf.kind {
94 LitKind::Int(..) | LitKind::Float(..) => {
95 let mut applicability = Applicability::MachineApplicable;
100 "unary minus has lower precedence than method call",
101 "consider adding parentheses to clarify your intent",
104 snippet_with_applicability(cx, rhs.span, "..", &mut applicability)
118 fn is_arith_expr(expr: &Expr) -> bool {
120 ExprKind::Binary(Spanned { node: op, .. }, _, _) => is_arith_op(op),
126 fn is_bit_op(op: BinOpKind) -> bool {
127 use syntax::ast::BinOpKind::*;
129 BitXor | BitAnd | BitOr | Shl | Shr => true,
135 fn is_arith_op(op: BinOpKind) -> bool {
136 use syntax::ast::BinOpKind::*;
138 Add | Sub | Mul | Div | Rem => true,