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