5 #![deny(clippy, clippy_pedantic)]
6 #![allow(blacklisted_name, unused, print_stdout, non_ascii_literal, new_without_default, new_without_default_derive, missing_docs_in_private_items)]
8 use std::collections::BTreeMap;
9 use std::collections::HashMap;
10 use std::collections::HashSet;
11 use std::collections::VecDeque;
13 use std::iter::FromIterator;
18 fn add(self, other: T) -> T { self }
19 fn drop(&mut self) { }
21 fn sub(&self, other: T) -> &T { self } // no error, self is a ref
22 fn div(self) -> T { self } // no error, different #arguments
23 fn rem(self, other: T) { } // no error, wrong return type
25 fn into_u32(self) -> u32 { 0 } // fine
26 fn into_u16(&self) -> u16 { 0 }
28 fn to_something(self) -> u32 { 0 }
40 // The lifetime is different, but that’s irrelevant, see #734
41 #[allow(needless_lifetimes)]
42 pub fn new<'b>(s: &'b str) -> Lt<'b> { unimplemented!() }
50 // The lifetime is different, but that’s irrelevant, see #734
51 pub fn new(s: &str) -> Lt2 { unimplemented!() }
59 // The lifetime is different, but that’s irrelevant, see #734
60 pub fn new() -> Lt3<'static> { unimplemented!() }
67 fn new() -> Self { U }
68 fn to_something(self) -> u32 { 0 } // ok because U is Copy
76 fn new() -> Option<V<T>> { None }
81 fn mul(self, other: T) -> T { self } // no error, obviously
84 /// Utility macro to test linting behavior in `option_methods()`
85 /// The lints included in `option_methods()` should not lint if the call to map is partially
87 macro_rules! opt_map {
88 ($opt:expr, $map:expr) => {($opt).map($map)};
91 /// Checks implementation of the following lints:
92 /// * `OPTION_MAP_UNWRAP_OR`
93 /// * `OPTION_MAP_UNWRAP_OR_ELSE`
97 // Check OPTION_MAP_UNWRAP_OR
99 let _ = opt.map(|x| x + 1)
101 .unwrap_or(0); // should lint even though this call is on a separate line
103 let _ = opt.map(|x| {
107 let _ = opt.map(|x| x + 1)
112 let _ = opt_map!(opt, |x| x + 1).unwrap_or(0); // should not lint
114 // Check OPTION_MAP_UNWRAP_OR_ELSE
116 let _ = opt.map(|x| x + 1)
118 .unwrap_or_else(|| 0); // should lint even though this call is on a separate line
120 let _ = opt.map(|x| {
123 ).unwrap_or_else(|| 0);
124 let _ = opt.map(|x| x + 1)
129 let _ = opt_map!(opt, |x| x + 1).unwrap_or_else(|| 0); // should not lint
132 /// Struct to generate false positives for things with .iter()
133 #[derive(Copy, Clone)]
137 fn iter(self) -> IteratorFalsePositives {
138 IteratorFalsePositives { foo: 0 }
141 fn iter_mut(self) -> IteratorFalsePositives {
142 IteratorFalsePositives { foo: 0 }
146 /// Struct to generate false positive for Iterator-based lints
147 #[derive(Copy, Clone)]
148 struct IteratorFalsePositives {
152 impl IteratorFalsePositives {
153 fn filter(self) -> IteratorFalsePositives {
157 fn next(self) -> IteratorFalsePositives {
161 fn find(self) -> Option<u32> {
165 fn position(self) -> Option<u32> {
169 fn rposition(self) -> Option<u32> {
173 fn nth(self, n: usize) -> Option<u32> {
177 fn skip(self, _: usize) -> IteratorFalsePositives {
182 #[derive(Copy, Clone)]
186 fn chars(self) -> std::str::Chars<'static> {
191 /// Checks implementation of `FILTER_NEXT` lint
193 let v = vec![3, 2, 1, 0, -1, -2, -3];
195 // check single-line case
196 let _ = v.iter().filter(|&x| *x < 0).next();
200 // check multi-line case
201 let _ = v.iter().filter(|&x| {
206 // check that we don't lint if the caller is not an Iterator
207 let foo = IteratorFalsePositives { foo: 0 };
208 let _ = foo.filter().next();
211 /// Checks implementation of `SEARCH_IS_SOME` lint
212 fn search_is_some() {
213 let v = vec![3, 2, 1, 0, -1, -2, -3];
215 // check `find().is_some()`, single-line
216 let _ = v.iter().find(|&x| *x < 0).is_some();
220 // check `find().is_some()`, multi-line
221 let _ = v.iter().find(|&x| {
226 // check `position().is_some()`, single-line
227 let _ = v.iter().position(|&x| x < 0).is_some();
231 // check `position().is_some()`, multi-line
232 let _ = v.iter().position(|&x| {
237 // check `rposition().is_some()`, single-line
238 let _ = v.iter().rposition(|&x| x < 0).is_some();
242 // check `rposition().is_some()`, multi-line
243 let _ = v.iter().rposition(|&x| {
248 // check that we don't lint if the caller is not an Iterator
249 let foo = IteratorFalsePositives { foo: 0 };
250 let _ = foo.find().is_some();
251 let _ = foo.position().is_some();
252 let _ = foo.rposition().is_some();
255 /// Checks implementation of the `OR_FUN_CALL` lint
260 fn new() -> Foo { Foo }
267 const fn make_const(i: i32) -> i32 { i }
269 fn make<T>() -> T { unimplemented!(); }
271 let with_enum = Some(Enum::A(1));
272 with_enum.unwrap_or(Enum::A(5));
274 let with_const_fn = Some(1);
275 with_const_fn.unwrap_or(make_const(5));
277 let with_constructor = Some(vec![1]);
278 with_constructor.unwrap_or(make());
283 let with_new = Some(vec![1]);
284 with_new.unwrap_or(Vec::new());
289 let with_const_args = Some(vec![1]);
290 with_const_args.unwrap_or(Vec::with_capacity(12));
295 let with_err : Result<_, ()> = Ok(vec![1]);
296 with_err.unwrap_or(make());
301 let with_err_args : Result<_, ()> = Ok(vec![1]);
302 with_err_args.unwrap_or(Vec::with_capacity(12));
307 let with_default_trait = Some(1);
308 with_default_trait.unwrap_or(Default::default());
313 let with_default_type = Some(1);
314 with_default_type.unwrap_or(u64::default());
319 let with_vec = Some(vec![1]);
320 with_vec.unwrap_or(vec![]);
323 // FIXME #944: ~|SUGGESTION with_vec.unwrap_or_else(|| vec![]);
325 let without_default = Some(Foo);
326 without_default.unwrap_or(Foo::new());
331 let mut map = HashMap::<u64, String>::new();
332 map.entry(42).or_insert(String::new());
337 let mut btree = BTreeMap::<u64, String>::new();
338 btree.entry(42).or_insert(String::new());
343 let stringy = Some(String::from(""));
344 let _ = stringy.unwrap_or("".to_owned());
350 /// Checks implementation of `ITER_NTH` lint
352 let mut some_vec = vec![0, 1, 2, 3];
353 let mut boxed_slice: Box<[u8]> = Box::new([0, 1, 2, 3]);
354 let mut some_vec_deque: VecDeque<_> = some_vec.iter().cloned().collect();
357 // Make sure we lint `.iter()` for relevant types
358 let bad_vec = some_vec.iter().nth(3);
360 let bad_slice = &some_vec[..].iter().nth(3);
362 let bad_boxed_slice = boxed_slice.iter().nth(3);
364 let bad_vec_deque = some_vec_deque.iter().nth(3);
369 // Make sure we lint `.iter_mut()` for relevant types
370 let bad_vec = some_vec.iter_mut().nth(3);
374 let bad_slice = &some_vec[..].iter_mut().nth(3);
378 let bad_vec_deque = some_vec_deque.iter_mut().nth(3);
382 // Make sure we don't lint for non-relevant types
383 let false_positive = HasIter;
384 let ok = false_positive.iter().nth(3);
385 let ok_mut = false_positive.iter_mut().nth(3);
388 /// Checks implementation of `ITER_SKIP_NEXT` lint
389 fn iter_skip_next() {
390 let mut some_vec = vec![0, 1, 2, 3];
392 let _ = some_vec.iter().skip(42).next();
395 let _ = some_vec.iter().cycle().skip(42).next();
398 let _ = (1..10).skip(10).next();
401 let _ = &some_vec[..].iter().skip(3).next();
404 let foo = IteratorFalsePositives { foo : 0 };
405 let _ = foo.skip(42).next();
406 let _ = foo.filter().skip(42).next();
409 struct GetFalsePositive {
413 impl GetFalsePositive {
414 fn get(&self, pos: usize) -> Option<&u32> { self.arr.get(pos) }
415 fn get_mut(&mut self, pos: usize) -> Option<&mut u32> { self.arr.get_mut(pos) }
418 /// Checks implementation of `GET_UNWRAP` lint
420 let mut boxed_slice: Box<[u8]> = Box::new([0, 1, 2, 3]);
421 let mut some_slice = &mut [0, 1, 2, 3];
422 let mut some_vec = vec![0, 1, 2, 3];
423 let mut some_vecdeque: VecDeque<_> = some_vec.iter().cloned().collect();
424 let mut some_hashmap: HashMap<u8, char> = HashMap::from_iter(vec![(1, 'a'), (2, 'b')]);
425 let mut some_btreemap: BTreeMap<u8, char> = BTreeMap::from_iter(vec![(1, 'a'), (2, 'b')]);
426 let mut false_positive = GetFalsePositive { arr: [0, 1, 2] };
428 { // Test `get().unwrap()`
429 let _ = boxed_slice.get(1).unwrap();
433 let _ = some_slice.get(0).unwrap();
437 let _ = some_vec.get(0).unwrap();
441 let _ = some_vecdeque.get(0).unwrap();
445 let _ = some_hashmap.get(&1).unwrap();
449 let _ = some_btreemap.get(&1).unwrap();
454 let _ = false_positive.get(0).unwrap();
457 { // Test `get_mut().unwrap()`
458 *boxed_slice.get_mut(0).unwrap() = 1;
462 *some_slice.get_mut(0).unwrap() = 1;
466 *some_vec.get_mut(0).unwrap() = 1;
470 *some_vecdeque.get_mut(0).unwrap() = 1;
475 // Check false positives
476 *some_hashmap.get_mut(&1).unwrap() = 'b';
477 *some_btreemap.get_mut(&1).unwrap() = 'b';
478 *false_positive.get_mut(0).unwrap() = 1;
483 #[allow(similar_names)]
488 let _ = opt.unwrap();
490 let res: Result<i32, ()> = Ok(0);
491 let _ = res.unwrap();
493 res.ok().expect("disaster!");
494 // the following should not warn, since `expect` isn't implemented unless
495 // the error type implements `Debug`
496 let res2: Result<i32, MyError> = Ok(0);
497 res2.ok().expect("oh noes!");
498 let res3: Result<u32, MyErrorWithParam<u8>>= Ok(0);
499 res3.ok().expect("whoof");
500 let res4: Result<u32, io::Error> = Ok(0);
501 res4.ok().expect("argh");
502 let res5: io::Result<u32> = Ok(0);
503 res5.ok().expect("oops");
504 let res6: Result<u32, &str> = Ok(0);
505 res6.ok().expect("meh");
508 struct MyError(()); // doesn't implement Debug
511 struct MyErrorWithParam<T> {
515 #[allow(unnecessary_operation)]
517 "".chars().next() == Some(' ');
522 Some(' ') != "".chars().next();
528 fn str_extend_chars() {
530 let def = String::from("def");
531 let mut s = String::new();
534 s.extend(abc.chars());
540 s.extend("abc".chars());
546 s.extend(def.chars());
551 s.extend(abc.chars().skip(1));
552 s.extend("abc".chars().skip(1));
553 s.extend(['a', 'b', 'c'].iter());
563 vec![1].clone(); // ok, not a Copy type
564 Some(vec![1]).clone(); // ok, not a Copy type
570 fn clone_on_copy_generic<T: Copy>(t: T) {
579 fn clone_on_double_ref() {
582 let z: &Vec<_> = y.clone();
585 println!("{:p} {:p}",*y, z);
588 fn single_char_pattern() {
602 // Not yet testing for multi-byte characters
603 // Changing `r.len() == 1` to `r.chars().count() == 1` in `lint_single_char_pattern`
604 // should have done this but produced an ICE
606 // We may not want to suggest changing these anyway
607 // See: https://github.com/Manishearth/rust-clippy/issues/650#issuecomment-184328984
611 // Can't use this lint for unicode code points which don't fit in a char
638 x.split_terminator("x");
642 x.rsplit_terminator("x");
662 x.match_indices("x");
666 x.rmatch_indices("x");
670 x.trim_left_matches("x");
674 x.trim_right_matches("x");
679 let h = HashSet::<String>::new();
680 h.contains("X"); // should not warn
683 #[allow(result_unwrap_used)]
684 fn temporary_cstring() {
685 use std::ffi::CString;
687 CString::new("foo").unwrap().as_ptr();
693 fn iter_clone_collect() {
695 let v2 : Vec<isize> = v.iter().cloned().collect();