]> git.lizzy.rs Git - rust.git/blob - tests/ui/methods.rs
Merge pull request #3127 from mikerite/fix-2937
[rust.git] / tests / ui / methods.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
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.
9
10
11 #![feature(tool_lints)]
12
13
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, clippy::useless_format)]
18
19 use std::collections::BTreeMap;
20 use std::collections::HashMap;
21 use std::collections::HashSet;
22 use std::collections::VecDeque;
23 use std::ops::Mul;
24 use std::iter::FromIterator;
25 use std::rc::{self, Rc};
26 use std::sync::{self, Arc};
27
28 pub struct T;
29
30 impl T {
31     pub fn add(self, other: T) -> T { self }
32
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
36
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
40
41     fn into_u32(self) -> u32 { 0 } // fine
42     fn into_u16(&self) -> u16 { 0 }
43
44     fn to_something(self) -> u32 { 0 }
45
46     fn new(self) {}
47 }
48
49 struct Lt<'a> {
50     foo: &'a u32,
51 }
52
53 impl<'a> Lt<'a> {
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!() }
57 }
58
59 struct Lt2<'a> {
60     foo: &'a u32,
61 }
62
63 impl<'a> Lt2<'a> {
64     // The lifetime is different, but that’s irrelevant, see #734
65     pub fn new(s: &str) -> Lt2 { unimplemented!() }
66 }
67
68 struct Lt3<'a> {
69     foo: &'a u32,
70 }
71
72 impl<'a> Lt3<'a> {
73     // The lifetime is different, but that’s irrelevant, see #734
74     pub fn new() -> Lt3<'static> { unimplemented!() }
75 }
76
77 #[derive(Clone,Copy)]
78 struct U;
79
80 impl U {
81     fn new() -> Self { U }
82     fn to_something(self) -> u32 { 0 } // ok because U is Copy
83 }
84
85 struct V<T> {
86     _dummy: T
87 }
88
89 impl<T> V<T> {
90     fn new() -> Option<V<T>> { None }
91 }
92
93 impl Mul<T> for T {
94     type Output = T;
95     fn mul(self, other: T) -> T { self } // no error, obviously
96 }
97
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
100 /// within a macro
101 macro_rules! opt_map {
102     ($opt:expr, $map:expr) => {($opt).map($map)};
103 }
104
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() {
110     let opt = Some(1);
111
112     // Check OPTION_MAP_UNWRAP_OR
113     // single line case
114     let _ = opt.map(|x| x + 1)
115
116                .unwrap_or(0); // should lint even though this call is on a separate line
117     // multi line cases
118     let _ = opt.map(|x| {
119                         x + 1
120                     }
121               ).unwrap_or(0);
122     let _ = opt.map(|x| x + 1)
123                .unwrap_or({
124                     0
125                 });
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| {
130         Some(x + 1)
131     }
132     ).unwrap_or(None);
133     let _ = opt
134         .map(|x| Some(x + 1))
135         .unwrap_or(None);
136     // macro case
137     let _ = opt_map!(opt, |x| x + 1).unwrap_or(0); // should not lint
138
139     // Check OPTION_MAP_UNWRAP_OR_ELSE
140     // single line case
141     let _ = opt.map(|x| x + 1)
142
143                .unwrap_or_else(|| 0); // should lint even though this call is on a separate line
144     // multi line cases
145     let _ = opt.map(|x| {
146                         x + 1
147                     }
148               ).unwrap_or_else(|| 0);
149     let _ = opt.map(|x| x + 1)
150                .unwrap_or_else(||
151                     0
152                 );
153     // macro case
154     let _ = opt_map!(opt, |x| x + 1).unwrap_or_else(|| 0); // should not lint
155
156     // Check OPTION_MAP_OR_NONE
157     // single line case
158     let _ = opt.map_or(None, |x| Some(x + 1));
159     // multi line case
160     let _ = opt.map_or(None, |x| {
161                         Some(x + 1)
162                        }
163                 );
164 }
165
166 /// Checks implementation of the following lints:
167 /// * `RESULT_MAP_UNWRAP_OR_ELSE`
168 fn result_methods() {
169     let res: Result<i32, ()> = Ok(1);
170
171     // Check RESULT_MAP_UNWRAP_OR_ELSE
172     // single line case
173     let _ = res.map(|x| x + 1)
174
175                .unwrap_or_else(|e| 0); // should lint even though this call is on a separate line
176     // multi line cases
177     let _ = res.map(|x| {
178                         x + 1
179                     }
180               ).unwrap_or_else(|e| 0);
181     let _ = res.map(|x| x + 1)
182                .unwrap_or_else(|e|
183                     0
184                 );
185     // macro case
186     let _ = opt_map!(res, |x| x + 1).unwrap_or_else(|e| 0); // should not lint
187 }
188
189 /// Struct to generate false positives for things with .iter()
190 #[derive(Copy, Clone)]
191 struct HasIter;
192
193 impl HasIter {
194     fn iter(self) -> IteratorFalsePositives {
195         IteratorFalsePositives { foo: 0 }
196     }
197
198     fn iter_mut(self) -> IteratorFalsePositives {
199         IteratorFalsePositives { foo: 0 }
200     }
201 }
202
203 /// Struct to generate false positive for Iterator-based lints
204 #[derive(Copy, Clone)]
205 struct IteratorFalsePositives {
206     foo: u32,
207 }
208
209 impl IteratorFalsePositives {
210     fn filter(self) -> IteratorFalsePositives {
211         self
212     }
213
214     fn next(self) -> IteratorFalsePositives {
215         self
216     }
217
218     fn find(self) -> Option<u32> {
219         Some(self.foo)
220     }
221
222     fn position(self) -> Option<u32> {
223         Some(self.foo)
224     }
225
226     fn rposition(self) -> Option<u32> {
227         Some(self.foo)
228     }
229
230     fn nth(self, n: usize) -> Option<u32> {
231         Some(self.foo)
232     }
233
234     fn skip(self, _: usize) -> IteratorFalsePositives {
235         self
236     }
237 }
238
239 /// Checks implementation of `FILTER_NEXT` lint
240 fn filter_next() {
241     let v = vec![3, 2, 1, 0, -1, -2, -3];
242
243     // check single-line case
244     let _ = v.iter().filter(|&x| *x < 0).next();
245
246     // check multi-line case
247     let _ = v.iter().filter(|&x| {
248                                 *x < 0
249                             }
250                    ).next();
251
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();
255 }
256
257 /// Checks implementation of `SEARCH_IS_SOME` lint
258 fn search_is_some() {
259     let v = vec![3, 2, 1, 0, -1, -2, -3];
260
261     // check `find().is_some()`, single-line
262     let _ = v.iter().find(|&x| *x < 0).is_some();
263
264     // check `find().is_some()`, multi-line
265     let _ = v.iter().find(|&x| {
266                               *x < 0
267                           }
268                    ).is_some();
269
270     // check `position().is_some()`, single-line
271     let _ = v.iter().position(|&x| x < 0).is_some();
272
273     // check `position().is_some()`, multi-line
274     let _ = v.iter().position(|&x| {
275                                   x < 0
276                               }
277                    ).is_some();
278
279     // check `rposition().is_some()`, single-line
280     let _ = v.iter().rposition(|&x| x < 0).is_some();
281
282     // check `rposition().is_some()`, multi-line
283     let _ = v.iter().rposition(|&x| {
284                                    x < 0
285                                }
286                    ).is_some();
287
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();
293 }
294
295 /// Checks implementation of the `OR_FUN_CALL` lint
296 fn or_fun_call() {
297     struct Foo;
298
299     impl Foo {
300         fn new() -> Foo { Foo }
301     }
302
303     enum Enum {
304         A(i32),
305     }
306
307
308
309     fn make<T>() -> T { unimplemented!(); }
310
311     let with_enum = Some(Enum::A(1));
312     with_enum.unwrap_or(Enum::A(5));
313
314     let with_const_fn = Some(::std::time::Duration::from_secs(1));
315     with_const_fn.unwrap_or(::std::time::Duration::from_secs(5));
316
317     let with_constructor = Some(vec![1]);
318     with_constructor.unwrap_or(make());
319
320     let with_new = Some(vec![1]);
321     with_new.unwrap_or(Vec::new());
322
323     let with_const_args = Some(vec![1]);
324     with_const_args.unwrap_or(Vec::with_capacity(12));
325
326     let with_err : Result<_, ()> = Ok(vec![1]);
327     with_err.unwrap_or(make());
328
329     let with_err_args : Result<_, ()> = Ok(vec![1]);
330     with_err_args.unwrap_or(Vec::with_capacity(12));
331
332     let with_default_trait = Some(1);
333     with_default_trait.unwrap_or(Default::default());
334
335     let with_default_type = Some(1);
336     with_default_type.unwrap_or(u64::default());
337
338     let with_vec = Some(vec![1]);
339     with_vec.unwrap_or(vec![]);
340
341     // FIXME #944: ~|SUGGESTION with_vec.unwrap_or_else(|| vec![]);
342
343     let without_default = Some(Foo);
344     without_default.unwrap_or(Foo::new());
345
346     let mut map = HashMap::<u64, String>::new();
347     map.entry(42).or_insert(String::new());
348
349     let mut btree = BTreeMap::<u64, String>::new();
350     btree.entry(42).or_insert(String::new());
351
352     let stringy = Some(String::from(""));
353     let _ = stringy.unwrap_or("".to_owned());
354 }
355
356 /// Checks implementation of the `EXPECT_FUN_CALL` lint
357 fn expect_fun_call() {
358     struct Foo;
359
360     impl Foo {
361         fn new() -> Self { Foo }
362
363         fn expect(&self, msg: &str) {
364             panic!("{}", msg)
365         }
366     }
367
368     let with_some = Some("value");
369     with_some.expect("error");
370
371     let with_none: Option<i32> = None;
372     with_none.expect("error");
373
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));
377
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());
380
381     let with_ok: Result<(), ()> = Ok(());
382     with_ok.expect("error");
383
384     let with_err: Result<(), ()> = Err(());
385     with_err.expect("error");
386
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));
390
391     let with_err_and_as_str: Result<(), ()> = Err(());
392     with_err_and_as_str.expect(format!("Error {}: fake error", error_code).as_str());
393
394     let with_dummy_type = Foo::new();
395     with_dummy_type.expect("another test string");
396
397     let with_dummy_type_and_format = Foo::new();
398     with_dummy_type_and_format.expect(&format!("Error {}: fake error", error_code));
399
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());
402
403     //Issue #2979 - this should not lint
404     let msg = "bar";
405     Some("foo").expect(msg);
406
407     Some("foo").expect({ &format!("error") });
408     Some("foo").expect(format!("error").as_ref());
409 }
410
411 /// Checks implementation of `ITER_NTH` lint
412 fn iter_nth() {
413     let mut some_vec = vec![0, 1, 2, 3];
414     let mut boxed_slice: Box<[u8]> = Box::new([0, 1, 2, 3]);
415     let mut some_vec_deque: VecDeque<_> = some_vec.iter().cloned().collect();
416
417     {
418         // Make sure we lint `.iter()` for relevant types
419         let bad_vec = some_vec.iter().nth(3);
420         let bad_slice = &some_vec[..].iter().nth(3);
421         let bad_boxed_slice = boxed_slice.iter().nth(3);
422         let bad_vec_deque = some_vec_deque.iter().nth(3);
423     }
424
425     {
426         // Make sure we lint `.iter_mut()` for relevant types
427         let bad_vec = some_vec.iter_mut().nth(3);
428     }
429     {
430         let bad_slice = &some_vec[..].iter_mut().nth(3);
431     }
432     {
433         let bad_vec_deque = some_vec_deque.iter_mut().nth(3);
434     }
435
436     // Make sure we don't lint for non-relevant types
437     let false_positive = HasIter;
438     let ok = false_positive.iter().nth(3);
439     let ok_mut = false_positive.iter_mut().nth(3);
440 }
441
442 /// Checks implementation of `ITER_SKIP_NEXT` lint
443 fn iter_skip_next() {
444     let mut some_vec = vec![0, 1, 2, 3];
445     let _ = some_vec.iter().skip(42).next();
446     let _ = some_vec.iter().cycle().skip(42).next();
447     let _ = (1..10).skip(10).next();
448     let _ = &some_vec[..].iter().skip(3).next();
449     let foo = IteratorFalsePositives { foo : 0 };
450     let _ = foo.skip(42).next();
451     let _ = foo.filter().skip(42).next();
452 }
453
454 #[allow(clippy::similar_names)]
455 fn main() {
456     let opt = Some(0);
457     let _ = opt.unwrap();
458 }