3 use utils::{span_lint_and_then, span_lint, snippet_opt, SpanlessEq, get_trait_def_id, implements_trait};
4 use utils::{higher, sugg};
6 /// **What it does:** This lint checks for `+=` operations and similar.
8 /// **Why is this bad?** Projects with many developers from languages without those operations may
9 /// find them unreadable and not worth their weight.
11 /// **Known problems:** Types implementing `OpAssign` don't necessarily implement `Op`.
17 declare_restriction_lint! {
19 "any assignment operation"
22 /// **What it does:** Check for `a = a op b` or `a = b commutative_op a` patterns.
24 /// **Why is this bad?** These can be written as the shorter `a op= b`.
26 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have implementations that differ from the regular `Op` impl.
36 pub ASSIGN_OP_PATTERN,
38 "assigning the result of an operation on a variable to that same variable"
41 #[derive(Copy, Clone, Default)]
44 impl LintPass for AssignOps {
45 fn get_lints(&self) -> LintArray {
46 lint_array!(ASSIGN_OPS, ASSIGN_OP_PATTERN)
50 impl LateLintPass for AssignOps {
51 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
53 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
54 span_lint_and_then(cx, ASSIGN_OPS, expr.span, "assign operation detected", |db| {
55 let lhs = &sugg::Sugg::hir(cx, lhs, "..");
56 let rhs = &sugg::Sugg::hir(cx, rhs, "..");
58 db.span_suggestion(expr.span,
60 format!("{} = {}", lhs, sugg::make_binop(higher::binop(op.node), lhs, rhs)));
63 hir::ExprAssign(ref assignee, ref e) => {
64 if let hir::ExprBinary(op, ref l, ref r) = e.node {
65 let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
66 let ty = cx.tcx.expr_ty(assignee);
67 if ty.walk_shallow().next().is_some() {
68 return; // implements_trait does not work with generics
70 let rty = cx.tcx.expr_ty(rhs);
71 if rty.walk_shallow().next().is_some() {
72 return; // implements_trait does not work with generics
75 ($op:expr, $cx:expr, $ty:expr, $rty:expr, $($trait_name:ident:$full_trait_name:ident),+) => {
77 $(hir::$full_trait_name => {
78 let [krate, module] = ::utils::paths::OPS_MODULE;
79 let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
80 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
83 return; // useless if the trait doesn't exist
85 implements_trait($cx, $ty, trait_id, vec![$rty])
107 if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span),
108 snippet_opt(cx, rhs.span)) {
109 span_lint_and_then(cx,
112 "manual implementation of an assign operation",
114 db.span_suggestion(expr.span,
116 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r));
122 "manual implementation of an assign operation");
127 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
130 // a = b commutative_op a
131 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
133 hir::BiAdd | hir::BiMul | hir::BiAnd | hir::BiOr | hir::BiBitXor | hir::BiBitAnd |