1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 #![feature(tool_lints)]
14 #![warn(clippy::all, clippy::pedantic, clippy::option_unwrap_used)]
15 #![allow(clippy::blacklisted_name, unused, clippy::print_stdout, clippy::non_ascii_literal, clippy::new_without_default,
16 clippy::new_without_default_derive, clippy::missing_docs_in_private_items, clippy::needless_pass_by_value,
17 clippy::default_trait_access, clippy::use_self)]
19 use std::collections::BTreeMap;
20 use std::collections::HashMap;
21 use std::collections::HashSet;
22 use std::collections::VecDeque;
24 use std::iter::FromIterator;
25 use std::rc::{self, Rc};
26 use std::sync::{self, Arc};
31 pub fn add(self, other: T) -> T { self }
33 pub(crate) fn drop(&mut self) { } // no error, not public interfact
34 fn neg(self) -> Self { self } // no error, private function
35 fn eq(&self, other: T) -> bool { true } // no error, private function
37 fn sub(&self, other: T) -> &T { self } // no error, self is a ref
38 fn div(self) -> T { self } // no error, different #arguments
39 fn rem(self, other: T) { } // no error, wrong return type
41 fn into_u32(self) -> u32 { 0 } // fine
42 fn into_u16(&self) -> u16 { 0 }
44 fn to_something(self) -> u32 { 0 }
54 // The lifetime is different, but that’s irrelevant, see #734
55 #[allow(clippy::needless_lifetimes)]
56 pub fn new<'b>(s: &'b str) -> Lt<'b> { unimplemented!() }
64 // The lifetime is different, but that’s irrelevant, see #734
65 pub fn new(s: &str) -> Lt2 { unimplemented!() }
73 // The lifetime is different, but that’s irrelevant, see #734
74 pub fn new() -> Lt3<'static> { unimplemented!() }
81 fn new() -> Self { U }
82 fn to_something(self) -> u32 { 0 } // ok because U is Copy
90 fn new() -> Option<V<T>> { None }
95 fn mul(self, other: T) -> T { self } // no error, obviously
98 /// Utility macro to test linting behavior in `option_methods()`
99 /// The lints included in `option_methods()` should not lint if the call to map is partially
101 macro_rules! opt_map {
102 ($opt:expr, $map:expr) => {($opt).map($map)};
105 /// Checks implementation of the following lints:
106 /// * `OPTION_MAP_UNWRAP_OR`
107 /// * `OPTION_MAP_UNWRAP_OR_ELSE`
108 /// * `OPTION_MAP_OR_NONE`
109 fn option_methods() {
112 // Check OPTION_MAP_UNWRAP_OR
114 let _ = opt.map(|x| x + 1)
116 .unwrap_or(0); // should lint even though this call is on a separate line
118 let _ = opt.map(|x| {
122 let _ = opt.map(|x| x + 1)
126 // single line `map(f).unwrap_or(None)` case
127 let _ = opt.map(|x| Some(x + 1)).unwrap_or(None);
128 // multiline `map(f).unwrap_or(None)` cases
129 let _ = opt.map(|x| {
134 .map(|x| Some(x + 1))
137 let _ = opt_map!(opt, |x| x + 1).unwrap_or(0); // should not lint
139 // Check OPTION_MAP_UNWRAP_OR_ELSE
141 let _ = opt.map(|x| x + 1)
143 .unwrap_or_else(|| 0); // should lint even though this call is on a separate line
145 let _ = opt.map(|x| {
148 ).unwrap_or_else(|| 0);
149 let _ = opt.map(|x| x + 1)
154 let _ = opt_map!(opt, |x| x + 1).unwrap_or_else(|| 0); // should not lint
156 // Check OPTION_MAP_OR_NONE
158 let _ = opt.map_or(None, |x| Some(x + 1));
160 let _ = opt.map_or(None, |x| {
166 /// Checks implementation of the following lints:
167 /// * `RESULT_MAP_UNWRAP_OR_ELSE`
168 fn result_methods() {
169 let res: Result<i32, ()> = Ok(1);
171 // Check RESULT_MAP_UNWRAP_OR_ELSE
173 let _ = res.map(|x| x + 1)
175 .unwrap_or_else(|e| 0); // should lint even though this call is on a separate line
177 let _ = res.map(|x| {
180 ).unwrap_or_else(|e| 0);
181 let _ = res.map(|x| x + 1)
186 let _ = opt_map!(res, |x| x + 1).unwrap_or_else(|e| 0); // should not lint
189 /// Struct to generate false positives for things with .iter()
190 #[derive(Copy, Clone)]
194 fn iter(self) -> IteratorFalsePositives {
195 IteratorFalsePositives { foo: 0 }
198 fn iter_mut(self) -> IteratorFalsePositives {
199 IteratorFalsePositives { foo: 0 }
203 /// Struct to generate false positive for Iterator-based lints
204 #[derive(Copy, Clone)]
205 struct IteratorFalsePositives {
209 impl IteratorFalsePositives {
210 fn filter(self) -> IteratorFalsePositives {
214 fn next(self) -> IteratorFalsePositives {
218 fn find(self) -> Option<u32> {
222 fn position(self) -> Option<u32> {
226 fn rposition(self) -> Option<u32> {
230 fn nth(self, n: usize) -> Option<u32> {
234 fn skip(self, _: usize) -> IteratorFalsePositives {
239 /// Checks implementation of `FILTER_NEXT` lint
241 let v = vec![3, 2, 1, 0, -1, -2, -3];
243 // check single-line case
244 let _ = v.iter().filter(|&x| *x < 0).next();
246 // check multi-line case
247 let _ = v.iter().filter(|&x| {
252 // check that we don't lint if the caller is not an Iterator
253 let foo = IteratorFalsePositives { foo: 0 };
254 let _ = foo.filter().next();
257 /// Checks implementation of `SEARCH_IS_SOME` lint
258 fn search_is_some() {
259 let v = vec![3, 2, 1, 0, -1, -2, -3];
261 // check `find().is_some()`, single-line
262 let _ = v.iter().find(|&x| *x < 0).is_some();
264 // check `find().is_some()`, multi-line
265 let _ = v.iter().find(|&x| {
270 // check `position().is_some()`, single-line
271 let _ = v.iter().position(|&x| x < 0).is_some();
273 // check `position().is_some()`, multi-line
274 let _ = v.iter().position(|&x| {
279 // check `rposition().is_some()`, single-line
280 let _ = v.iter().rposition(|&x| x < 0).is_some();
282 // check `rposition().is_some()`, multi-line
283 let _ = v.iter().rposition(|&x| {
288 // check that we don't lint if the caller is not an Iterator
289 let foo = IteratorFalsePositives { foo: 0 };
290 let _ = foo.find().is_some();
291 let _ = foo.position().is_some();
292 let _ = foo.rposition().is_some();
295 /// Checks implementation of the `OR_FUN_CALL` lint
300 fn new() -> Foo { Foo }
309 fn make<T>() -> T { unimplemented!(); }
311 let with_enum = Some(Enum::A(1));
312 with_enum.unwrap_or(Enum::A(5));
314 let with_const_fn = Some(::std::time::Duration::from_secs(1));
315 with_const_fn.unwrap_or(::std::time::Duration::from_secs(5));
317 let with_constructor = Some(vec![1]);
318 with_constructor.unwrap_or(make());
320 let with_new = Some(vec![1]);
321 with_new.unwrap_or(Vec::new());
323 let with_const_args = Some(vec![1]);
324 with_const_args.unwrap_or(Vec::with_capacity(12));
326 let with_err : Result<_, ()> = Ok(vec![1]);
327 with_err.unwrap_or(make());
329 let with_err_args : Result<_, ()> = Ok(vec![1]);
330 with_err_args.unwrap_or(Vec::with_capacity(12));
332 let with_default_trait = Some(1);
333 with_default_trait.unwrap_or(Default::default());
335 let with_default_type = Some(1);
336 with_default_type.unwrap_or(u64::default());
338 let with_vec = Some(vec![1]);
339 with_vec.unwrap_or(vec![]);
341 // FIXME #944: ~|SUGGESTION with_vec.unwrap_or_else(|| vec![]);
343 let without_default = Some(Foo);
344 without_default.unwrap_or(Foo::new());
346 let mut map = HashMap::<u64, String>::new();
347 map.entry(42).or_insert(String::new());
349 let mut btree = BTreeMap::<u64, String>::new();
350 btree.entry(42).or_insert(String::new());
352 let stringy = Some(String::from(""));
353 let _ = stringy.unwrap_or("".to_owned());
356 /// Checks implementation of the `EXPECT_FUN_CALL` lint
357 fn expect_fun_call() {
361 fn new() -> Self { Foo }
363 fn expect(&self, msg: &str) {
368 let with_some = Some("value");
369 with_some.expect("error");
371 let with_none: Option<i32> = None;
372 with_none.expect("error");
374 let error_code = 123_i32;
375 let with_none_and_format: Option<i32> = None;
376 with_none_and_format.expect(&format!("Error {}: fake error", error_code));
378 let with_none_and_as_str: Option<i32> = None;
379 with_none_and_as_str.expect(format!("Error {}: fake error", error_code).as_str());
381 let with_ok: Result<(), ()> = Ok(());
382 with_ok.expect("error");
384 let with_err: Result<(), ()> = Err(());
385 with_err.expect("error");
387 let error_code = 123_i32;
388 let with_err_and_format: Result<(), ()> = Err(());
389 with_err_and_format.expect(&format!("Error {}: fake error", error_code));
391 let with_err_and_as_str: Result<(), ()> = Err(());
392 with_err_and_as_str.expect(format!("Error {}: fake error", error_code).as_str());
394 let with_dummy_type = Foo::new();
395 with_dummy_type.expect("another test string");
397 let with_dummy_type_and_format = Foo::new();
398 with_dummy_type_and_format.expect(&format!("Error {}: fake error", error_code));
400 let with_dummy_type_and_as_str = Foo::new();
401 with_dummy_type_and_as_str.expect(format!("Error {}: fake error", error_code).as_str());
403 //Issue #2979 - this should not lint
405 Some("foo").expect(msg);
408 /// Checks implementation of `ITER_NTH` lint
410 let mut some_vec = vec![0, 1, 2, 3];
411 let mut boxed_slice: Box<[u8]> = Box::new([0, 1, 2, 3]);
412 let mut some_vec_deque: VecDeque<_> = some_vec.iter().cloned().collect();
415 // Make sure we lint `.iter()` for relevant types
416 let bad_vec = some_vec.iter().nth(3);
417 let bad_slice = &some_vec[..].iter().nth(3);
418 let bad_boxed_slice = boxed_slice.iter().nth(3);
419 let bad_vec_deque = some_vec_deque.iter().nth(3);
423 // Make sure we lint `.iter_mut()` for relevant types
424 let bad_vec = some_vec.iter_mut().nth(3);
427 let bad_slice = &some_vec[..].iter_mut().nth(3);
430 let bad_vec_deque = some_vec_deque.iter_mut().nth(3);
433 // Make sure we don't lint for non-relevant types
434 let false_positive = HasIter;
435 let ok = false_positive.iter().nth(3);
436 let ok_mut = false_positive.iter_mut().nth(3);
439 /// Checks implementation of `ITER_SKIP_NEXT` lint
440 fn iter_skip_next() {
441 let mut some_vec = vec![0, 1, 2, 3];
442 let _ = some_vec.iter().skip(42).next();
443 let _ = some_vec.iter().cycle().skip(42).next();
444 let _ = (1..10).skip(10).next();
445 let _ = &some_vec[..].iter().skip(3).next();
446 let foo = IteratorFalsePositives { foo : 0 };
447 let _ = foo.skip(42).next();
448 let _ = foo.filter().skip(42).next();
451 #[allow(clippy::similar_names)]
454 let _ = opt.unwrap();