]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/tests/ui/unnecessary_fold.rs
New upstream version 1.74.1+dfsg1
[rustc.git] / src / tools / clippy / tests / ui / unnecessary_fold.rs
CommitLineData
f20569fa
XL
1#![allow(dead_code)]
2
3/// Calls which should trigger the `UNNECESSARY_FOLD` lint
4fn unnecessary_fold() {
5 // Can be replaced by .any
6 let _ = (0..3).fold(false, |acc, x| acc || x > 2);
7 // Can be replaced by .all
8 let _ = (0..3).fold(true, |acc, x| acc && x > 2);
9 // Can be replaced by .sum
10 let _: i32 = (0..3).fold(0, |acc, x| acc + x);
11 // Can be replaced by .product
12 let _: i32 = (0..3).fold(1, |acc, x| acc * x);
13}
14
15/// Should trigger the `UNNECESSARY_FOLD` lint, with an error span including exactly `.fold(...)`
16fn unnecessary_fold_span_for_multi_element_chain() {
17 let _: bool = (0..3).map(|x| 2 * x).fold(false, |acc, x| acc || x > 2);
18}
19
20/// Calls which should not trigger the `UNNECESSARY_FOLD` lint
21fn unnecessary_fold_should_ignore() {
22 let _ = (0..3).fold(true, |acc, x| acc || x > 2);
23 let _ = (0..3).fold(false, |acc, x| acc && x > 2);
24 let _ = (0..3).fold(1, |acc, x| acc + x);
25 let _ = (0..3).fold(0, |acc, x| acc * x);
26 let _ = (0..3).fold(0, |acc, x| 1 + acc + x);
27
28 // We only match against an accumulator on the left
29 // hand side. We could lint for .sum and .product when
30 // it's on the right, but don't for now (and this wouldn't
31 // be valid if we extended the lint to cover arbitrary numeric
32 // types).
33 let _ = (0..3).fold(false, |acc, x| x > 2 || acc);
34 let _ = (0..3).fold(true, |acc, x| x > 2 && acc);
35 let _ = (0..3).fold(0, |acc, x| x + acc);
36 let _ = (0..3).fold(1, |acc, x| x * acc);
37
38 let _ = [(0..2), (0..3)].iter().fold(0, |a, b| a + b.len());
39 let _ = [(0..2), (0..3)].iter().fold(1, |a, b| a * b.len());
40}
41
42/// Should lint only the line containing the fold
43fn unnecessary_fold_over_multiple_lines() {
44 let _ = (0..3)
45 .map(|x| x + 1)
46 .filter(|x| x % 2 == 0)
47 .fold(false, |acc, x| acc || x > 2);
48}
49
fe692bf9
FG
50fn issue10000() {
51 use std::collections::HashMap;
52 use std::hash::BuildHasher;
53
54 fn anything<T>(_: T) {}
55 fn num(_: i32) {}
56 fn smoketest_map<S: BuildHasher>(mut map: HashMap<i32, i32, S>) {
57 map.insert(0, 0);
58 assert_eq!(map.values().fold(0, |x, y| x + y), 0);
59
60 // more cases:
61 let _ = map.values().fold(0, |x, y| x + y);
62 let _ = map.values().fold(1, |x, y| x * y);
63 let _: i32 = map.values().fold(0, |x, y| x + y);
64 let _: i32 = map.values().fold(1, |x, y| x * y);
65 anything(map.values().fold(0, |x, y| x + y));
66 anything(map.values().fold(1, |x, y| x * y));
67 num(map.values().fold(0, |x, y| x + y));
68 num(map.values().fold(1, |x, y| x * y));
69 }
70
71 smoketest_map(HashMap::new());
72}
73
f20569fa 74fn main() {}