]> git.lizzy.rs Git - rust.git/blob - tests/ui/methods.rs
Auto merge of #3519 - phansch:brave_newer_ui_tests, r=flip1995
[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 #![warn(clippy::all, clippy::pedantic, clippy::option_unwrap_used)]
11 #![allow(
12     clippy::blacklisted_name,
13     unused,
14     clippy::print_stdout,
15     clippy::non_ascii_literal,
16     clippy::new_without_default,
17     clippy::missing_docs_in_private_items,
18     clippy::needless_pass_by_value,
19     clippy::default_trait_access,
20     clippy::use_self,
21     clippy::new_ret_no_self,
22     clippy::useless_format
23 )]
24
25 use std::collections::BTreeMap;
26 use std::collections::HashMap;
27 use std::collections::HashSet;
28 use std::collections::VecDeque;
29 use std::ops::Mul;
30 use std::iter::FromIterator;
31 use std::rc::{self, Rc};
32 use std::sync::{self, Arc};
33
34 pub struct T;
35
36 impl T {
37     pub fn add(self, other: T) -> T { self }
38
39     pub(crate) fn drop(&mut self) { } // no error, not public interfact
40     fn neg(self) -> Self { self } // no error, private function
41     fn eq(&self, other: T) -> bool { true } // no error, private function
42
43     fn sub(&self, other: T) -> &T { self } // no error, self is a ref
44     fn div(self) -> T { self } // no error, different #arguments
45     fn rem(self, other: T) { } // no error, wrong return type
46
47     fn into_u32(self) -> u32 { 0 } // fine
48     fn into_u16(&self) -> u16 { 0 }
49
50     fn to_something(self) -> u32 { 0 }
51
52     fn new(self) -> Self { unimplemented!(); }
53 }
54
55 struct Lt<'a> {
56     foo: &'a u32,
57 }
58
59 impl<'a> Lt<'a> {
60     // The lifetime is different, but that’s irrelevant, see #734
61     #[allow(clippy::needless_lifetimes)]
62     pub fn new<'b>(s: &'b str) -> Lt<'b> { unimplemented!() }
63 }
64
65 struct Lt2<'a> {
66     foo: &'a u32,
67 }
68
69 impl<'a> Lt2<'a> {
70     // The lifetime is different, but that’s irrelevant, see #734
71     pub fn new(s: &str) -> Lt2 { unimplemented!() }
72 }
73
74 struct Lt3<'a> {
75     foo: &'a u32,
76 }
77
78 impl<'a> Lt3<'a> {
79     // The lifetime is different, but that’s irrelevant, see #734
80     pub fn new() -> Lt3<'static> { unimplemented!() }
81 }
82
83 #[derive(Clone,Copy)]
84 struct U;
85
86 impl U {
87     fn new() -> Self { U }
88     fn to_something(self) -> u32 { 0 } // ok because U is Copy
89 }
90
91 struct V<T> {
92     _dummy: T
93 }
94
95 impl<T> V<T> {
96     fn new() -> Option<V<T>> { None }
97 }
98
99 impl Mul<T> for T {
100     type Output = T;
101     fn mul(self, other: T) -> T { self } // no error, obviously
102 }
103
104 /// Utility macro to test linting behavior in `option_methods()`
105 /// The lints included in `option_methods()` should not lint if the call to map is partially
106 /// within a macro
107 macro_rules! opt_map {
108     ($opt:expr, $map:expr) => {($opt).map($map)};
109 }
110
111 /// Checks implementation of the following lints:
112 /// * `OPTION_MAP_UNWRAP_OR`
113 /// * `OPTION_MAP_UNWRAP_OR_ELSE`
114 /// * `OPTION_MAP_OR_NONE`
115 fn option_methods() {
116     let opt = Some(1);
117
118     // Check OPTION_MAP_UNWRAP_OR
119     // single line case
120     let _ = opt.map(|x| x + 1)
121
122                .unwrap_or(0); // should lint even though this call is on a separate line
123     // multi line cases
124     let _ = opt.map(|x| {
125                         x + 1
126                     }
127               ).unwrap_or(0);
128     let _ = opt.map(|x| x + 1)
129                .unwrap_or({
130                     0
131                 });
132     // single line `map(f).unwrap_or(None)` case
133     let _ = opt.map(|x| Some(x + 1)).unwrap_or(None);
134     // multiline `map(f).unwrap_or(None)` cases
135     let _ = opt.map(|x| {
136         Some(x + 1)
137     }
138     ).unwrap_or(None);
139     let _ = opt
140         .map(|x| Some(x + 1))
141         .unwrap_or(None);
142     // macro case
143     let _ = opt_map!(opt, |x| x + 1).unwrap_or(0); // should not lint
144
145     // Check OPTION_MAP_UNWRAP_OR_ELSE
146     // single line case
147     let _ = opt.map(|x| x + 1)
148
149                .unwrap_or_else(|| 0); // should lint even though this call is on a separate line
150     // multi line cases
151     let _ = opt.map(|x| {
152                         x + 1
153                     }
154               ).unwrap_or_else(|| 0);
155     let _ = opt.map(|x| x + 1)
156                .unwrap_or_else(||
157                     0
158                 );
159     // macro case
160     let _ = opt_map!(opt, |x| x + 1).unwrap_or_else(|| 0); // should not lint
161
162     // Check OPTION_MAP_OR_NONE
163     // single line case
164     let _ = opt.map_or(None, |x| Some(x + 1));
165     // multi line case
166     let _ = opt.map_or(None, |x| {
167                         Some(x + 1)
168                        }
169                 );
170 }
171
172 /// Checks implementation of the following lints:
173 /// * `RESULT_MAP_UNWRAP_OR_ELSE`
174 fn result_methods() {
175     let res: Result<i32, ()> = Ok(1);
176
177     // Check RESULT_MAP_UNWRAP_OR_ELSE
178     // single line case
179     let _ = res.map(|x| x + 1)
180
181                .unwrap_or_else(|e| 0); // should lint even though this call is on a separate line
182     // multi line cases
183     let _ = res.map(|x| {
184                         x + 1
185                     }
186               ).unwrap_or_else(|e| 0);
187     let _ = res.map(|x| x + 1)
188                .unwrap_or_else(|e|
189                     0
190                 );
191     // macro case
192     let _ = opt_map!(res, |x| x + 1).unwrap_or_else(|e| 0); // should not lint
193 }
194
195 /// Struct to generate false positives for things with .iter()
196 #[derive(Copy, Clone)]
197 struct HasIter;
198
199 impl HasIter {
200     fn iter(self) -> IteratorFalsePositives {
201         IteratorFalsePositives { foo: 0 }
202     }
203
204     fn iter_mut(self) -> IteratorFalsePositives {
205         IteratorFalsePositives { foo: 0 }
206     }
207 }
208
209 /// Struct to generate false positive for Iterator-based lints
210 #[derive(Copy, Clone)]
211 struct IteratorFalsePositives {
212     foo: u32,
213 }
214
215 impl IteratorFalsePositives {
216     fn filter(self) -> IteratorFalsePositives {
217         self
218     }
219
220     fn next(self) -> IteratorFalsePositives {
221         self
222     }
223
224     fn find(self) -> Option<u32> {
225         Some(self.foo)
226     }
227
228     fn position(self) -> Option<u32> {
229         Some(self.foo)
230     }
231
232     fn rposition(self) -> Option<u32> {
233         Some(self.foo)
234     }
235
236     fn nth(self, n: usize) -> Option<u32> {
237         Some(self.foo)
238     }
239
240     fn skip(self, _: usize) -> IteratorFalsePositives {
241         self
242     }
243 }
244
245 /// Checks implementation of `FILTER_NEXT` lint
246 fn filter_next() {
247     let v = vec![3, 2, 1, 0, -1, -2, -3];
248
249     // check single-line case
250     let _ = v.iter().filter(|&x| *x < 0).next();
251
252     // check multi-line case
253     let _ = v.iter().filter(|&x| {
254                                 *x < 0
255                             }
256                    ).next();
257
258     // check that we don't lint if the caller is not an Iterator
259     let foo = IteratorFalsePositives { foo: 0 };
260     let _ = foo.filter().next();
261 }
262
263 /// Checks implementation of `SEARCH_IS_SOME` lint
264 fn search_is_some() {
265     let v = vec![3, 2, 1, 0, -1, -2, -3];
266
267     // check `find().is_some()`, single-line
268     let _ = v.iter().find(|&x| *x < 0).is_some();
269
270     // check `find().is_some()`, multi-line
271     let _ = v.iter().find(|&x| {
272                               *x < 0
273                           }
274                    ).is_some();
275
276     // check `position().is_some()`, single-line
277     let _ = v.iter().position(|&x| x < 0).is_some();
278
279     // check `position().is_some()`, multi-line
280     let _ = v.iter().position(|&x| {
281                                   x < 0
282                               }
283                    ).is_some();
284
285     // check `rposition().is_some()`, single-line
286     let _ = v.iter().rposition(|&x| x < 0).is_some();
287
288     // check `rposition().is_some()`, multi-line
289     let _ = v.iter().rposition(|&x| {
290                                    x < 0
291                                }
292                    ).is_some();
293
294     // check that we don't lint if the caller is not an Iterator
295     let foo = IteratorFalsePositives { foo: 0 };
296     let _ = foo.find().is_some();
297     let _ = foo.position().is_some();
298     let _ = foo.rposition().is_some();
299 }
300
301 /// Checks implementation of the `OR_FUN_CALL` lint
302 fn or_fun_call() {
303     struct Foo;
304
305     impl Foo {
306         fn new() -> Foo { Foo }
307     }
308
309     enum Enum {
310         A(i32),
311     }
312
313
314
315     fn make<T>() -> T { unimplemented!(); }
316
317     let with_enum = Some(Enum::A(1));
318     with_enum.unwrap_or(Enum::A(5));
319
320     let with_const_fn = Some(::std::time::Duration::from_secs(1));
321     with_const_fn.unwrap_or(::std::time::Duration::from_secs(5));
322
323     let with_constructor = Some(vec![1]);
324     with_constructor.unwrap_or(make());
325
326     let with_new = Some(vec![1]);
327     with_new.unwrap_or(Vec::new());
328
329     let with_const_args = Some(vec![1]);
330     with_const_args.unwrap_or(Vec::with_capacity(12));
331
332     let with_err : Result<_, ()> = Ok(vec![1]);
333     with_err.unwrap_or(make());
334
335     let with_err_args : Result<_, ()> = Ok(vec![1]);
336     with_err_args.unwrap_or(Vec::with_capacity(12));
337
338     let with_default_trait = Some(1);
339     with_default_trait.unwrap_or(Default::default());
340
341     let with_default_type = Some(1);
342     with_default_type.unwrap_or(u64::default());
343
344     let with_vec = Some(vec![1]);
345     with_vec.unwrap_or(vec![]);
346
347     // FIXME #944: ~|SUGGESTION with_vec.unwrap_or_else(|| vec![]);
348
349     let without_default = Some(Foo);
350     without_default.unwrap_or(Foo::new());
351
352     let mut map = HashMap::<u64, String>::new();
353     map.entry(42).or_insert(String::new());
354
355     let mut btree = BTreeMap::<u64, String>::new();
356     btree.entry(42).or_insert(String::new());
357
358     let stringy = Some(String::from(""));
359     let _ = stringy.unwrap_or("".to_owned());
360 }
361
362 /// Checks implementation of `ITER_NTH` lint
363 fn iter_nth() {
364     let mut some_vec = vec![0, 1, 2, 3];
365     let mut boxed_slice: Box<[u8]> = Box::new([0, 1, 2, 3]);
366     let mut some_vec_deque: VecDeque<_> = some_vec.iter().cloned().collect();
367
368     {
369         // Make sure we lint `.iter()` for relevant types
370         let bad_vec = some_vec.iter().nth(3);
371         let bad_slice = &some_vec[..].iter().nth(3);
372         let bad_boxed_slice = boxed_slice.iter().nth(3);
373         let bad_vec_deque = some_vec_deque.iter().nth(3);
374     }
375
376     {
377         // Make sure we lint `.iter_mut()` for relevant types
378         let bad_vec = some_vec.iter_mut().nth(3);
379     }
380     {
381         let bad_slice = &some_vec[..].iter_mut().nth(3);
382     }
383     {
384         let bad_vec_deque = some_vec_deque.iter_mut().nth(3);
385     }
386
387     // Make sure we don't lint for non-relevant types
388     let false_positive = HasIter;
389     let ok = false_positive.iter().nth(3);
390     let ok_mut = false_positive.iter_mut().nth(3);
391 }
392
393 #[allow(clippy::similar_names)]
394 fn main() {
395     let opt = Some(0);
396     let _ = opt.unwrap();
397 }