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