Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit dd11ffa

Browse files
authored
Merge pull request rust-lang#3292 from kimsnj/commutative_assign_op
Limit commutative assign op lint to primitive types
2 parents f6882ed + f9e4f56 commit dd11ffa

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

clippy_lints/src/assign_ops.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
215215
lint(assignee, r);
216216
}
217217
// a = b commutative_op a
218-
if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
218+
// Limited to primitive type as these ops are know to be commutative
219+
if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r)
220+
&& cx.tables.expr_ty(assignee).is_primitive_ty() {
219221
match op.node {
220222
hir::BinOpKind::Add
221223
| hir::BinOpKind::Mul

tests/ui/assign_ops2.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,18 @@ impl MulAssign<i64> for Wrap {
5353
*self = *self * rhs
5454
}
5555
}
56+
57+
fn cow_add_assign() {
58+
use std::borrow::Cow;
59+
let mut buf = Cow::Owned(String::from("bar"));
60+
let cows = Cow::Borrowed("foo");
61+
62+
// this can be linted
63+
buf = buf + cows.clone();
64+
65+
// this should not as cow<str> Add is not commutative
66+
buf = cows + buf;
67+
println!("{}", buf);
68+
69+
}
70+

tests/ui/assign_ops2.stderr

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,5 +126,13 @@ help: or
126126
26 | a = a * a * a;
127127
| ^^^^^^^^^^^^^
128128

129-
error: aborting due to 9 previous errors
129+
error: manual implementation of an assign operation
130+
--> $DIR/assign_ops2.rs:63:5
131+
|
132+
63 | buf = buf + cows.clone();
133+
| ^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `buf += cows.clone()`
134+
|
135+
= note: `-D clippy::assign-op-pattern` implied by `-D warnings`
136+
137+
error: aborting due to 10 previous errors
130138

0 commit comments

Comments
 (0)