Skip to content

Commit 8fa68f1

Browse files
committed
Merge pull request #913 from oli-obk/assign_ops
suggest `a op= b` over `a = a op b`
2 parents c170aa2 + b0d008b commit 8fa68f1

File tree

7 files changed

+234
-3
lines changed

7 files changed

+234
-3
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ All notable changes to this project will be documented in this file.
7676
[`absurd_extreme_comparisons`]: https://github.com/Manishearth/rust-clippy/wiki#absurd_extreme_comparisons
7777
[`almost_swapped`]: https://github.com/Manishearth/rust-clippy/wiki#almost_swapped
7878
[`approx_constant`]: https://github.com/Manishearth/rust-clippy/wiki#approx_constant
79+
[`assign_op_pattern`]: https://github.com/Manishearth/rust-clippy/wiki#assign_op_pattern
80+
[`assign_ops`]: https://github.com/Manishearth/rust-clippy/wiki#assign_ops
7981
[`bad_bit_mask`]: https://github.com/Manishearth/rust-clippy/wiki#bad_bit_mask
8082
[`blacklisted_name`]: https://github.com/Manishearth/rust-clippy/wiki#blacklisted_name
8183
[`block_in_if_condition_expr`]: https://github.com/Manishearth/rust-clippy/wiki#block_in_if_condition_expr

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,15 @@ Table of contents:
1717

1818
## Lints
1919

20-
There are 147 lints included in this crate:
20+
There are 149 lints included in this crate:
2121

2222
name | default | meaning
2323
---------------------------------------------------------------------------------------------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2424
[absurd_extreme_comparisons](https://github.com/Manishearth/rust-clippy/wiki#absurd_extreme_comparisons) | warn | a comparison involving a maximum or minimum value involves a case that is always true or always false
2525
[almost_swapped](https://github.com/Manishearth/rust-clippy/wiki#almost_swapped) | warn | `foo = bar; bar = foo` sequence
2626
[approx_constant](https://github.com/Manishearth/rust-clippy/wiki#approx_constant) | warn | the approximate of a known float constant (in `std::f64::consts` or `std::f32::consts`) is found; suggests to use the constant
27+
[assign_op_pattern](https://github.com/Manishearth/rust-clippy/wiki#assign_op_pattern) | warn | assigning the result of an operation on a variable to that same variable
28+
[assign_ops](https://github.com/Manishearth/rust-clippy/wiki#assign_ops) | allow | Any assignment operation
2729
[bad_bit_mask](https://github.com/Manishearth/rust-clippy/wiki#bad_bit_mask) | warn | expressions of the form `_ & mask == select` that will only ever return `true` or `false` (because in the example `select` containing bits that `mask` doesn't have)
2830
[blacklisted_name](https://github.com/Manishearth/rust-clippy/wiki#blacklisted_name) | warn | usage of a blacklisted/placeholder name
2931
[block_in_if_condition_expr](https://github.com/Manishearth/rust-clippy/wiki#block_in_if_condition_expr) | warn | braces can be eliminated in conditions that are expressions, e.g `if { true } ...`

src/assign_ops.rs

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
use rustc::hir;
2+
use rustc::lint::*;
3+
use utils::{span_lint_and_then, span_lint, snippet_opt, SpanlessEq, get_trait_def_id, implements_trait};
4+
5+
/// **What it does:** This lint checks for `+=` operations and similar
6+
///
7+
/// **Why is this bad?** Projects with many developers from languages without those operations
8+
/// may find them unreadable and not worth their weight
9+
///
10+
/// **Known problems:** Types implementing `OpAssign` don't necessarily implement `Op`
11+
///
12+
/// **Example:**
13+
/// ```
14+
/// a += 1;
15+
/// ```
16+
declare_restriction_lint! {
17+
pub ASSIGN_OPS,
18+
"Any assignment operation"
19+
}
20+
21+
/// **What it does:** Check for `a = a op b` or `a = b commutative_op a` patterns
22+
///
23+
/// **Why is this bad?** These can be written as the shorter `a op= b`
24+
///
25+
/// **Known problems:** While forbidden by the spec, `OpAssign` traits may have implementations that differ from the regular `Op` impl
26+
///
27+
/// **Example:**
28+
///
29+
/// ```
30+
/// let mut a = 5;
31+
/// ...
32+
/// a = a + b;
33+
/// ```
34+
declare_lint! {
35+
pub ASSIGN_OP_PATTERN,
36+
Warn,
37+
"assigning the result of an operation on a variable to that same variable"
38+
}
39+
40+
#[derive(Copy, Clone, Default)]
41+
pub struct AssignOps;
42+
43+
impl LintPass for AssignOps {
44+
fn get_lints(&self) -> LintArray {
45+
lint_array!(ASSIGN_OPS, ASSIGN_OP_PATTERN)
46+
}
47+
}
48+
49+
impl LateLintPass for AssignOps {
50+
fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
51+
match expr.node {
52+
hir::ExprAssignOp(op, ref lhs, ref rhs) => {
53+
if let (Some(l), Some(r)) = (snippet_opt(cx, lhs.span), snippet_opt(cx, rhs.span)) {
54+
span_lint_and_then(cx,
55+
ASSIGN_OPS,
56+
expr.span,
57+
"assign operation detected",
58+
|db| {
59+
match rhs.node {
60+
hir::ExprBinary(op2, _, _) if op2 != op => {
61+
db.span_suggestion(expr.span,
62+
"replace it with",
63+
format!("{} = {} {} ({})", l, l, op.node.as_str(), r));
64+
},
65+
_ => {
66+
db.span_suggestion(expr.span,
67+
"replace it with",
68+
format!("{} = {} {} {}", l, l, op.node.as_str(), r));
69+
}
70+
}
71+
});
72+
} else {
73+
span_lint(cx,
74+
ASSIGN_OPS,
75+
expr.span,
76+
"assign operation detected");
77+
}
78+
},
79+
hir::ExprAssign(ref assignee, ref e) => {
80+
if let hir::ExprBinary(op, ref l, ref r) = e.node {
81+
let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
82+
let ty = cx.tcx.expr_ty(assignee);
83+
if ty.walk_shallow().next().is_some() {
84+
return; // implements_trait does not work with generics
85+
}
86+
let rty = cx.tcx.expr_ty(rhs);
87+
if rty.walk_shallow().next().is_some() {
88+
return; // implements_trait does not work with generics
89+
}
90+
macro_rules! ops {
91+
($op:expr, $cx:expr, $ty:expr, $rty:expr, $($trait_name:ident:$full_trait_name:ident),+) => {
92+
match $op {
93+
$(hir::$full_trait_name => {
94+
let [krate, module] = ::utils::paths::OPS_MODULE;
95+
let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
96+
let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
97+
trait_id
98+
} else {
99+
return; // useless if the trait doesn't exist
100+
};
101+
implements_trait($cx, $ty, trait_id, vec![$rty])
102+
},)*
103+
_ => false,
104+
}
105+
}
106+
}
107+
if ops!(op.node, cx, ty, rty, Add:BiAdd,
108+
Sub:BiSub,
109+
Mul:BiMul,
110+
Div:BiDiv,
111+
Rem:BiRem,
112+
And:BiAnd,
113+
Or:BiOr,
114+
BitAnd:BiBitAnd,
115+
BitOr:BiBitOr,
116+
BitXor:BiBitXor,
117+
Shr:BiShr,
118+
Shl:BiShl
119+
) {
120+
if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span)) {
121+
span_lint_and_then(cx,
122+
ASSIGN_OP_PATTERN,
123+
expr.span,
124+
"manual implementation of an assign operation",
125+
|db| {
126+
db.span_suggestion(expr.span,
127+
"replace it with",
128+
format!("{} {}= {}", snip_a, op.node.as_str(), snip_r));
129+
});
130+
} else {
131+
span_lint(cx,
132+
ASSIGN_OP_PATTERN,
133+
expr.span,
134+
"manual implementation of an assign operation");
135+
}
136+
}
137+
};
138+
// a = a op b
139+
if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
140+
lint(assignee, r);
141+
}
142+
// a = b commutative_op a
143+
if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
144+
match op.node {
145+
hir::BiAdd | hir::BiMul |
146+
hir::BiAnd | hir::BiOr |
147+
hir::BiBitXor | hir::BiBitAnd | hir::BiBitOr => {
148+
lint(assignee, l);
149+
},
150+
_ => {},
151+
}
152+
}
153+
}
154+
},
155+
_ => {},
156+
}
157+
}
158+
}

src/lib.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
#![feature(question_mark)]
88
#![feature(stmt_expr_attributes)]
99
#![allow(indexing_slicing, shadow_reuse, unknown_lints)]
10-
#![allow(float_arithmetic, integer_arithmetic)]
1110

1211
extern crate rustc_driver;
1312
extern crate getopts;
@@ -203,6 +202,7 @@ pub mod utils;
203202
pub mod approx_const;
204203
pub mod arithmetic;
205204
pub mod array_indexing;
205+
pub mod assign_ops;
206206
pub mod attrs;
207207
pub mod bit_mask;
208208
pub mod blacklisted_name;
@@ -394,10 +394,12 @@ pub fn plugin_registrar(reg: &mut Registry) {
394394
reg.register_late_lint_pass(box unsafe_removed_from_name::UnsafeNameRemoval);
395395
reg.register_late_lint_pass(box mem_forget::MemForget);
396396
reg.register_late_lint_pass(box arithmetic::Arithmetic::default());
397+
reg.register_late_lint_pass(box assign_ops::AssignOps);
397398

398399
reg.register_lint_group("clippy_restrictions", vec![
399400
arithmetic::FLOAT_ARITHMETIC,
400401
arithmetic::INTEGER_ARITHMETIC,
402+
assign_ops::ASSIGN_OPS,
401403
]);
402404

403405
reg.register_lint_group("clippy_pedantic", vec![
@@ -432,6 +434,7 @@ pub fn plugin_registrar(reg: &mut Registry) {
432434
reg.register_lint_group("clippy", vec![
433435
approx_const::APPROX_CONSTANT,
434436
array_indexing::OUT_OF_BOUNDS_INDEXING,
437+
assign_ops::ASSIGN_OP_PATTERN,
435438
attrs::DEPRECATED_SEMVER,
436439
attrs::INLINE_ALWAYS,
437440
bit_mask::BAD_BIT_MASK,

src/utils/paths.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ pub const LINKED_LIST: [&'static str; 3] = ["collections", "linked_list", "Linke
2929
pub const MEM_FORGET: [&'static str; 3] = ["core", "mem", "forget"];
3030
pub const MUTEX: [&'static str; 4] = ["std", "sync", "mutex", "Mutex"];
3131
pub const OPEN_OPTIONS: [&'static str; 3] = ["std", "fs", "OpenOptions"];
32+
pub const OPS_MODULE: [&'static str; 2] = ["core", "ops"];
3233
pub const OPTION: [&'static str; 3] = ["core", "option", "Option"];
3334
pub const RANGE: [&'static str; 3] = ["core", "ops", "Range"];
3435
pub const RANGE_FROM: [&'static str; 3] = ["core", "ops", "RangeFrom"];

tests/compile-fail/assign_ops.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#![feature(plugin)]
2+
#![plugin(clippy)]
3+
4+
#[deny(assign_ops)]
5+
#[allow(unused_assignments)]
6+
fn main() {
7+
let mut i = 1i32;
8+
i += 2; //~ ERROR assign operation detected
9+
//~^ HELP replace it with
10+
//~| SUGGESTION i = i + 2
11+
i -= 6; //~ ERROR assign operation detected
12+
//~^ HELP replace it with
13+
//~| SUGGESTION i = i - 6
14+
i *= 5; //~ ERROR assign operation detected
15+
//~^ HELP replace it with
16+
//~| SUGGESTION i = i * 5
17+
i /= 32; //~ ERROR assign operation detected
18+
//~^ HELP replace it with
19+
//~| SUGGESTION i = i / 32
20+
i %= 42; //~ ERROR assign operation detected
21+
//~^ HELP replace it with
22+
//~| SUGGESTION i = i % 42
23+
i >>= i; //~ ERROR assign operation detected
24+
//~^ HELP replace it with
25+
//~| SUGGESTION i = i >> i
26+
i <<= 9 + 6 - 7; //~ ERROR assign operation detected
27+
//~^ HELP replace it with
28+
//~| SUGGESTION i = i << (9 + 6 - 7)
29+
}
30+
31+
#[allow(dead_code, unused_assignments)]
32+
#[deny(assign_op_pattern)]
33+
fn bla() {
34+
let mut a = 5;
35+
a = a + 1; //~ ERROR manual implementation of an assign operation
36+
//~^ HELP replace it with
37+
//~| SUGGESTION a += 1
38+
a = 1 + a; //~ ERROR manual implementation of an assign operation
39+
//~^ HELP replace it with
40+
//~| SUGGESTION a += 1
41+
a = a - 1; //~ ERROR manual implementation of an assign operation
42+
//~^ HELP replace it with
43+
//~| SUGGESTION a -= 1
44+
a = a * 99; //~ ERROR manual implementation of an assign operation
45+
//~^ HELP replace it with
46+
//~| SUGGESTION a *= 99
47+
a = 42 * a; //~ ERROR manual implementation of an assign operation
48+
//~^ HELP replace it with
49+
//~| SUGGESTION a *= 42
50+
a = a / 2; //~ ERROR manual implementation of an assign operation
51+
//~^ HELP replace it with
52+
//~| SUGGESTION a /= 2
53+
a = a % 5; //~ ERROR manual implementation of an assign operation
54+
//~^ HELP replace it with
55+
//~| SUGGESTION a %= 5
56+
a = a & 1; //~ ERROR manual implementation of an assign operation
57+
//~^ HELP replace it with
58+
//~| SUGGESTION a &= 1
59+
a = 1 - a;
60+
a = 5 / a;
61+
a = 42 % a;
62+
a = 6 << a;
63+
let mut s = String::new();
64+
s = s + "bla";
65+
}

tests/compile-fail/strings.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,6 @@ fn main() {
6565

6666
// the add is only caught for String
6767
let mut x = 1;
68-
x = x + 1;
68+
x = x + 1; //~ WARN assign_op_pattern
6969
assert_eq!(2, x);
7070
}

0 commit comments

Comments
 (0)