Skip to content

Commit d2400a4

Browse files
committed
Auto merge of #12873 - lochetti:issue_11103, r=llogiq
Add new lint `hashset_insert_after_contains` This PR closes #11103. This is my first PR creating a new lint (and the second attempt of creating this PR, the first one I was not able to continue because of personal reasons). Thanks for the patience :) The idea of the lint is to find insert in hashmanps inside if staments that are checking if the hashmap contains the same value that is being inserted. This is not necessary since you could simply call the insert and check for the bool returned if you still need the if statement. changelog: new lint: [hashset_insert_after_contains]
2 parents a4bdab3 + 4e71fc4 commit d2400a4

File tree

6 files changed

+273
-0
lines changed

6 files changed

+273
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5798,6 +5798,7 @@ Released 2018-09-13
57985798
[`semicolon_outside_block`]: https://rust-lang.github.io/rust-clippy/master/index.html#semicolon_outside_block
57995799
[`separated_literal_suffix`]: https://rust-lang.github.io/rust-clippy/master/index.html#separated_literal_suffix
58005800
[`serde_api_misuse`]: https://rust-lang.github.io/rust-clippy/master/index.html#serde_api_misuse
5801+
[`set_contains_or_insert`]: https://rust-lang.github.io/rust-clippy/master/index.html#set_contains_or_insert
58015802
[`shadow_reuse`]: https://rust-lang.github.io/rust-clippy/master/index.html#shadow_reuse
58025803
[`shadow_same`]: https://rust-lang.github.io/rust-clippy/master/index.html#shadow_same
58035804
[`shadow_unrelated`]: https://rust-lang.github.io/rust-clippy/master/index.html#shadow_unrelated

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
645645
crate::semicolon_block::SEMICOLON_OUTSIDE_BLOCK_INFO,
646646
crate::semicolon_if_nothing_returned::SEMICOLON_IF_NOTHING_RETURNED_INFO,
647647
crate::serde_api::SERDE_API_MISUSE_INFO,
648+
crate::set_contains_or_insert::SET_CONTAINS_OR_INSERT_INFO,
648649
crate::shadow::SHADOW_REUSE_INFO,
649650
crate::shadow::SHADOW_SAME_INFO,
650651
crate::shadow::SHADOW_UNRELATED_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,7 @@ mod self_named_constructors;
318318
mod semicolon_block;
319319
mod semicolon_if_nothing_returned;
320320
mod serde_api;
321+
mod set_contains_or_insert;
321322
mod shadow;
322323
mod significant_drop_tightening;
323324
mod single_call_fn;
@@ -1172,6 +1173,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
11721173
});
11731174
store.register_late_pass(move |_| Box::new(string_patterns::StringPatterns::new(msrv())));
11741175
store.register_early_pass(|| Box::new(field_scoped_visibility_modifiers::FieldScopedVisibilityModifiers));
1176+
store.register_late_pass(|_| Box::new(set_contains_or_insert::HashsetInsertAfterContains));
11751177
// add lints here, do not remove this comment, it's used in `new_lint`
11761178
}
11771179

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
use std::ops::ControlFlow;
2+
3+
use clippy_utils::diagnostics::span_lint;
4+
use clippy_utils::ty::is_type_diagnostic_item;
5+
use clippy_utils::visitors::for_each_expr;
6+
use clippy_utils::{higher, peel_hir_expr_while, SpanlessEq};
7+
use rustc_hir::{Expr, ExprKind, UnOp};
8+
use rustc_lint::{LateContext, LateLintPass};
9+
use rustc_session::declare_lint_pass;
10+
use rustc_span::symbol::Symbol;
11+
use rustc_span::{sym, Span};
12+
13+
declare_clippy_lint! {
14+
/// ### What it does
15+
/// Checks for usage of `contains` to see if a value is not
16+
/// present on `HashSet` followed by a `insert`.
17+
///
18+
/// ### Why is this bad?
19+
/// Using just `insert` and checking the returned `bool` is more efficient.
20+
///
21+
/// ### Known problems
22+
/// In case the value that wants to be inserted is borrowed and also expensive or impossible
23+
/// to clone. In such a scenario, the developer might want to check with `contains` before inserting,
24+
/// to avoid the clone. In this case, it will report a false positive.
25+
///
26+
/// ### Example
27+
/// ```rust
28+
/// use std::collections::HashSet;
29+
/// let mut set = HashSet::new();
30+
/// let value = 5;
31+
/// if !set.contains(&value) {
32+
/// set.insert(value);
33+
/// println!("inserted {value:?}");
34+
/// }
35+
/// ```
36+
/// Use instead:
37+
/// ```rust
38+
/// use std::collections::HashSet;
39+
/// let mut set = HashSet::new();
40+
/// let value = 5;
41+
/// if set.insert(&value) {
42+
/// println!("inserted {value:?}");
43+
/// }
44+
/// ```
45+
#[clippy::version = "1.80.0"]
46+
pub SET_CONTAINS_OR_INSERT,
47+
nursery,
48+
"call to `HashSet::contains` followed by `HashSet::insert`"
49+
}
50+
51+
declare_lint_pass!(HashsetInsertAfterContains => [SET_CONTAINS_OR_INSERT]);
52+
53+
impl<'tcx> LateLintPass<'tcx> for HashsetInsertAfterContains {
54+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
55+
if !expr.span.from_expansion()
56+
&& let Some(higher::If {
57+
cond: cond_expr,
58+
then: then_expr,
59+
..
60+
}) = higher::If::hir(expr)
61+
&& let Some(contains_expr) = try_parse_op_call(cx, cond_expr, sym!(contains))//try_parse_contains(cx, cond_expr)
62+
&& let Some(insert_expr) = find_insert_calls(cx, &contains_expr, then_expr)
63+
{
64+
span_lint(
65+
cx,
66+
SET_CONTAINS_OR_INSERT,
67+
vec![contains_expr.span, insert_expr.span],
68+
"usage of `HashSet::insert` after `HashSet::contains`",
69+
);
70+
}
71+
}
72+
}
73+
74+
struct OpExpr<'tcx> {
75+
receiver: &'tcx Expr<'tcx>,
76+
value: &'tcx Expr<'tcx>,
77+
span: Span,
78+
}
79+
80+
fn try_parse_op_call<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, symbol: Symbol) -> Option<OpExpr<'tcx>> {
81+
let expr = peel_hir_expr_while(expr, |e| {
82+
if let ExprKind::Unary(UnOp::Not, e) = e.kind {
83+
Some(e)
84+
} else {
85+
None
86+
}
87+
});
88+
89+
if let ExprKind::MethodCall(path, receiver, [value], span) = expr.kind {
90+
let value = value.peel_borrows();
91+
let value = peel_hir_expr_while(value, |e| {
92+
if let ExprKind::Unary(UnOp::Deref, e) = e.kind {
93+
Some(e)
94+
} else {
95+
None
96+
}
97+
});
98+
let receiver = receiver.peel_borrows();
99+
let receiver_ty = cx.typeck_results().expr_ty(receiver).peel_refs();
100+
if value.span.eq_ctxt(expr.span)
101+
&& is_type_diagnostic_item(cx, receiver_ty, sym::HashSet)
102+
&& path.ident.name == symbol
103+
{
104+
return Some(OpExpr { receiver, value, span });
105+
}
106+
}
107+
None
108+
}
109+
110+
fn find_insert_calls<'tcx>(
111+
cx: &LateContext<'tcx>,
112+
contains_expr: &OpExpr<'tcx>,
113+
expr: &'tcx Expr<'_>,
114+
) -> Option<OpExpr<'tcx>> {
115+
for_each_expr(cx, expr, |e| {
116+
if let Some(insert_expr) = try_parse_op_call(cx, e, sym!(insert))
117+
&& SpanlessEq::new(cx).eq_expr(contains_expr.receiver, insert_expr.receiver)
118+
&& SpanlessEq::new(cx).eq_expr(contains_expr.value, insert_expr.value)
119+
{
120+
ControlFlow::Break(insert_expr)
121+
} else {
122+
ControlFlow::Continue(())
123+
}
124+
})
125+
}

tests/ui/set_contains_or_insert.rs

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#![allow(unused)]
2+
#![allow(clippy::nonminimal_bool)]
3+
#![allow(clippy::needless_borrow)]
4+
#![warn(clippy::set_contains_or_insert)]
5+
6+
use std::collections::HashSet;
7+
8+
fn main() {
9+
should_warn_cases();
10+
11+
should_not_warn_cases();
12+
}
13+
14+
fn should_warn_cases() {
15+
let mut set = HashSet::new();
16+
let value = 5;
17+
18+
if !set.contains(&value) {
19+
set.insert(value);
20+
println!("Just a comment");
21+
}
22+
23+
if set.contains(&value) {
24+
set.insert(value);
25+
println!("Just a comment");
26+
}
27+
28+
if !set.contains(&value) {
29+
set.insert(value);
30+
}
31+
32+
if !!set.contains(&value) {
33+
set.insert(value);
34+
println!("Just a comment");
35+
}
36+
37+
if (&set).contains(&value) {
38+
set.insert(value);
39+
}
40+
41+
let borrow_value = &6;
42+
if !set.contains(borrow_value) {
43+
set.insert(*borrow_value);
44+
}
45+
46+
let borrow_set = &mut set;
47+
if !borrow_set.contains(&value) {
48+
borrow_set.insert(value);
49+
}
50+
}
51+
52+
fn should_not_warn_cases() {
53+
let mut set = HashSet::new();
54+
let value = 5;
55+
let another_value = 6;
56+
57+
if !set.contains(&value) {
58+
set.insert(another_value);
59+
}
60+
61+
if !set.contains(&value) {
62+
println!("Just a comment");
63+
}
64+
65+
if simply_true() {
66+
set.insert(value);
67+
}
68+
69+
if !set.contains(&value) {
70+
set.replace(value); //it is not insert
71+
println!("Just a comment");
72+
}
73+
74+
if set.contains(&value) {
75+
println!("value is already in set");
76+
} else {
77+
set.insert(value);
78+
}
79+
}
80+
81+
fn simply_true() -> bool {
82+
true
83+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
error: usage of `HashSet::insert` after `HashSet::contains`
2+
--> tests/ui/set_contains_or_insert.rs:18:13
3+
|
4+
LL | if !set.contains(&value) {
5+
| ^^^^^^^^^^^^^^^^
6+
LL | set.insert(value);
7+
| ^^^^^^^^^^^^^
8+
|
9+
= note: `-D clippy::set-contains-or-insert` implied by `-D warnings`
10+
= help: to override `-D warnings` add `#[allow(clippy::set_contains_or_insert)]`
11+
12+
error: usage of `HashSet::insert` after `HashSet::contains`
13+
--> tests/ui/set_contains_or_insert.rs:23:12
14+
|
15+
LL | if set.contains(&value) {
16+
| ^^^^^^^^^^^^^^^^
17+
LL | set.insert(value);
18+
| ^^^^^^^^^^^^^
19+
20+
error: usage of `HashSet::insert` after `HashSet::contains`
21+
--> tests/ui/set_contains_or_insert.rs:28:13
22+
|
23+
LL | if !set.contains(&value) {
24+
| ^^^^^^^^^^^^^^^^
25+
LL | set.insert(value);
26+
| ^^^^^^^^^^^^^
27+
28+
error: usage of `HashSet::insert` after `HashSet::contains`
29+
--> tests/ui/set_contains_or_insert.rs:32:14
30+
|
31+
LL | if !!set.contains(&value) {
32+
| ^^^^^^^^^^^^^^^^
33+
LL | set.insert(value);
34+
| ^^^^^^^^^^^^^
35+
36+
error: usage of `HashSet::insert` after `HashSet::contains`
37+
--> tests/ui/set_contains_or_insert.rs:37:15
38+
|
39+
LL | if (&set).contains(&value) {
40+
| ^^^^^^^^^^^^^^^^
41+
LL | set.insert(value);
42+
| ^^^^^^^^^^^^^
43+
44+
error: usage of `HashSet::insert` after `HashSet::contains`
45+
--> tests/ui/set_contains_or_insert.rs:42:13
46+
|
47+
LL | if !set.contains(borrow_value) {
48+
| ^^^^^^^^^^^^^^^^^^^^^^
49+
LL | set.insert(*borrow_value);
50+
| ^^^^^^^^^^^^^^^^^^^^^
51+
52+
error: usage of `HashSet::insert` after `HashSet::contains`
53+
--> tests/ui/set_contains_or_insert.rs:47:20
54+
|
55+
LL | if !borrow_set.contains(&value) {
56+
| ^^^^^^^^^^^^^^^^
57+
LL | borrow_set.insert(value);
58+
| ^^^^^^^^^^^^^
59+
60+
error: aborting due to 7 previous errors
61+

0 commit comments

Comments
 (0)