Skip to content

Commit cb90674

Browse files
committed
add iter_over_hash_type lint
1 parent 9a4dd10 commit cb90674

File tree

7 files changed

+167
-0
lines changed

7 files changed

+167
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5123,6 +5123,7 @@ Released 2018-09-13
51235123
[`iter_on_empty_collections`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_on_empty_collections
51245124
[`iter_on_single_items`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_on_single_items
51255125
[`iter_out_of_bounds`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_out_of_bounds
5126+
[`iter_over_hash_type`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_over_hash_type
51265127
[`iter_overeager_cloned`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_overeager_cloned
51275128
[`iter_skip_next`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_skip_next
51285129
[`iter_skip_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_skip_zero

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
230230
crate::items_after_statements::ITEMS_AFTER_STATEMENTS_INFO,
231231
crate::items_after_test_module::ITEMS_AFTER_TEST_MODULE_INFO,
232232
crate::iter_not_returning_iterator::ITER_NOT_RETURNING_ITERATOR_INFO,
233+
crate::iter_over_hash_type::ITER_OVER_HASH_TYPE_INFO,
233234
crate::iter_without_into_iter::INTO_ITER_WITHOUT_ITER_INFO,
234235
crate::iter_without_into_iter::ITER_WITHOUT_INTO_ITER_INFO,
235236
crate::large_const_arrays::LARGE_CONST_ARRAYS_INFO,
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
use clippy_utils::paths::{HASHMAP_KEYS, HASHMAP_VALUES, HASHSET_ITER_TY};
2+
use clippy_utils::{diagnostics::span_lint, match_def_path};
3+
use clippy_utils::higher::ForLoop;
4+
use clippy_utils::ty::is_type_diagnostic_item;
5+
use rustc_lint::{LateContext, LateLintPass};
6+
use rustc_session::{declare_lint_pass, declare_tool_lint};
7+
use rustc_span::sym;
8+
9+
declare_clippy_lint! {
10+
/// ### What it does
11+
/// This is a restriction lint which prevents the use of hash types (i.e., `HashSet` and `HashMap`) in for loops.
12+
///
13+
/// ### Why is this bad?
14+
/// Because hash types are unordered, when iterated through such as in a for loop, the values are returned in
15+
/// a pseudo-random order. As a result, on redundant systems this may cause inconsistencies and anomalies.
16+
/// In addition, the unknown order of the elements may reduce readability or introduce other undesired
17+
/// side effects.
18+
///
19+
/// ### Example
20+
/// ```no_run
21+
/// let my_map = new Hashmap<i32, String>();
22+
/// for (key, value) in my_map { /* ... */ }
23+
/// ```
24+
/// Use instead:
25+
/// ```no_run
26+
/// let my_map = new Hashmap<i32, String>();
27+
/// let mut keys = my_map.keys().clone().collect::<Vec<_>();
28+
/// keys.sort();
29+
/// for key in keys {
30+
/// let value = &my_map[value];
31+
/// }
32+
/// ```
33+
#[clippy::version = "1.75.0"]
34+
pub ITER_OVER_HASH_TYPE,
35+
restriction,
36+
"iterating over unordered hash-based types (`HashMap` and `HashSet`)"
37+
}
38+
39+
declare_lint_pass!(IterOverHashType => [ITER_OVER_HASH_TYPE]);
40+
41+
impl LateLintPass<'_> for IterOverHashType {
42+
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ rustc_hir::Expr<'_>) {
43+
if let Some(for_loop) = ForLoop::hir(expr)
44+
&& !for_loop.body.span.from_expansion()
45+
&& let ty = cx.typeck_results().expr_ty(for_loop.arg).peel_refs()
46+
&& let Some(adt) = ty.ty_adt_def()
47+
&& let did = adt.did()
48+
&& (match_def_path(cx, did, &HASHMAP_KEYS)
49+
|| match_def_path(cx, did, &HASHMAP_VALUES)
50+
|| match_def_path(cx, did, &HASHSET_ITER_TY)
51+
|| is_type_diagnostic_item(cx, ty, sym::HashMap)
52+
|| is_type_diagnostic_item(cx, ty, sym::HashSet))
53+
{
54+
span_lint(
55+
cx,
56+
ITER_OVER_HASH_TYPE,
57+
expr.span,
58+
"iterating over unordered hash-based type",
59+
);
60+
};
61+
}
62+
}
63+

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ mod item_name_repetitions;
165165
mod items_after_statements;
166166
mod items_after_test_module;
167167
mod iter_not_returning_iterator;
168+
mod iter_over_hash_type;
168169
mod iter_without_into_iter;
169170
mod large_const_arrays;
170171
mod large_enum_variant;
@@ -1065,6 +1066,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10651066
});
10661067
store.register_late_pass(move |_| Box::new(manual_hash_one::ManualHashOne::new(msrv())));
10671068
store.register_late_pass(|_| Box::new(iter_without_into_iter::IterWithoutIntoIter));
1069+
store.register_late_pass(|_| Box::new(iter_over_hash_type::IterOverHashType));
10681070
// add lints here, do not remove this comment, it's used in `new_lint`
10691071
}
10701072

clippy_utils/src/paths.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ pub const FUTURES_IO_ASYNCREADEXT: [&str; 3] = ["futures_util", "io", "AsyncRead
3232
pub const FUTURES_IO_ASYNCWRITEEXT: [&str; 3] = ["futures_util", "io", "AsyncWriteExt"];
3333
pub const HASHMAP_CONTAINS_KEY: [&str; 6] = ["std", "collections", "hash", "map", "HashMap", "contains_key"];
3434
pub const HASHMAP_INSERT: [&str; 6] = ["std", "collections", "hash", "map", "HashMap", "insert"];
35+
pub const HASHMAP_KEYS: [&str; 5] = ["std", "collections", "hash", "map", "Keys"];
36+
pub const HASHMAP_VALUES: [&str; 5] = ["std", "collections", "hash", "map", "Values"];
37+
pub const HASHSET_ITER_TY: [&str; 5] = ["std", "collections", "hash", "set", "Iter"];
3538
pub const HASHSET_ITER: [&str; 6] = ["std", "collections", "hash", "set", "HashSet", "iter"];
3639
pub const IDENT: [&str; 3] = ["rustc_span", "symbol", "Ident"];
3740
pub const IDENT_AS_STR: [&str; 4] = ["rustc_span", "symbol", "Ident", "as_str"];

tests/ui/iter_over_hash_type.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//@aux-build:proc_macros.rs
2+
3+
#![warn(clippy::iter_over_hash_type)]
4+
use std::collections::{HashMap, HashSet};
5+
6+
extern crate proc_macros;
7+
8+
fn main() {
9+
let hash_set = HashSet::<i32>::new();
10+
let hash_map = HashMap::<i32, i32>::new();
11+
let vec = Vec::<i32>::new();
12+
13+
for x in &hash_set {
14+
let _ = x;
15+
}
16+
for x in hash_set.iter() {
17+
let _ = x;
18+
}
19+
for x in hash_set {
20+
let _ = x;
21+
}
22+
for (x, y) in &hash_map {
23+
let _ = (x, y);
24+
}
25+
for x in hash_map.keys() {
26+
let _ = x;
27+
}
28+
for x in hash_map.values() {
29+
let _ = x;
30+
}
31+
32+
// shouldnt fire
33+
for x in &vec {
34+
let _ = x;
35+
}
36+
for x in vec {
37+
let _ = x;
38+
}
39+
40+
// should not lint, this comes from an external crate
41+
proc_macros::external! {
42+
for _ in HashMap::<i32, i32>::new() {}
43+
}
44+
}

tests/ui/iter_over_hash_type.stderr

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
error: iterating over unordered hash-based type
2+
--> $DIR/iter_over_hash_type.rs:13:5
3+
|
4+
LL | / for x in &hash_set {
5+
LL | | let _ = x;
6+
LL | | }
7+
| |_____^
8+
|
9+
= note: `-D clippy::iter-over-hash-type` implied by `-D warnings`
10+
= help: to override `-D warnings` add `#[allow(clippy::iter_over_hash_type)]`
11+
12+
error: iterating over unordered hash-based type
13+
--> $DIR/iter_over_hash_type.rs:16:5
14+
|
15+
LL | / for x in hash_set.iter() {
16+
LL | | let _ = x;
17+
LL | | }
18+
| |_____^
19+
20+
error: iterating over unordered hash-based type
21+
--> $DIR/iter_over_hash_type.rs:19:5
22+
|
23+
LL | / for x in hash_set {
24+
LL | | let _ = x;
25+
LL | | }
26+
| |_____^
27+
28+
error: iterating over unordered hash-based type
29+
--> $DIR/iter_over_hash_type.rs:22:5
30+
|
31+
LL | / for (x, y) in &hash_map {
32+
LL | | let _ = (x, y);
33+
LL | | }
34+
| |_____^
35+
36+
error: iterating over unordered hash-based type
37+
--> $DIR/iter_over_hash_type.rs:25:5
38+
|
39+
LL | / for x in hash_map.keys() {
40+
LL | | let _ = x;
41+
LL | | }
42+
| |_____^
43+
44+
error: iterating over unordered hash-based type
45+
--> $DIR/iter_over_hash_type.rs:28:5
46+
|
47+
LL | / for x in hash_map.values() {
48+
LL | | let _ = x;
49+
LL | | }
50+
| |_____^
51+
52+
error: aborting due to 6 previous errors
53+

0 commit comments

Comments
 (0)