]> git.lizzy.rs Git - rust.git/blob - tests/ui/methods.rs
Auto merge of #3635 - matthiaskrgr:revert_random_state_3603, r=xfix
[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 // aux-build:option_helpers.rs
11
12 #![warn(clippy::all, clippy::pedantic, clippy::option_unwrap_used)]
13 #![allow(
14     clippy::blacklisted_name,
15     unused,
16     clippy::print_stdout,
17     clippy::non_ascii_literal,
18     clippy::new_without_default,
19     clippy::missing_docs_in_private_items,
20     clippy::needless_pass_by_value,
21     clippy::default_trait_access,
22     clippy::use_self,
23     clippy::new_ret_no_self,
24     clippy::useless_format
25 )]
26
27 #[macro_use]
28 extern crate option_helpers;
29
30 use std::collections::BTreeMap;
31 use std::collections::HashMap;
32 use std::collections::HashSet;
33 use std::collections::VecDeque;
34 use std::ops::Mul;
35 use std::iter::FromIterator;
36 use std::rc::{self, Rc};
37 use std::sync::{self, Arc};
38
39 use option_helpers::IteratorFalsePositives;
40
41 pub struct T;
42
43 impl T {
44     pub fn add(self, other: T) -> T { self }
45
46     pub(crate) fn drop(&mut self) { } // no error, not public interfact
47     fn neg(self) -> Self { self } // no error, private function
48     fn eq(&self, other: T) -> bool { true } // no error, private function
49
50     fn sub(&self, other: T) -> &T { self } // no error, self is a ref
51     fn div(self) -> T { self } // no error, different #arguments
52     fn rem(self, other: T) { } // no error, wrong return type
53
54     fn into_u32(self) -> u32 { 0 } // fine
55     fn into_u16(&self) -> u16 { 0 }
56
57     fn to_something(self) -> u32 { 0 }
58
59     fn new(self) -> Self { unimplemented!(); }
60 }
61
62 struct Lt<'a> {
63     foo: &'a u32,
64 }
65
66 impl<'a> Lt<'a> {
67     // The lifetime is different, but that’s irrelevant, see #734
68     #[allow(clippy::needless_lifetimes)]
69     pub fn new<'b>(s: &'b str) -> Lt<'b> { unimplemented!() }
70 }
71
72 struct Lt2<'a> {
73     foo: &'a u32,
74 }
75
76 impl<'a> Lt2<'a> {
77     // The lifetime is different, but that’s irrelevant, see #734
78     pub fn new(s: &str) -> Lt2 { unimplemented!() }
79 }
80
81 struct Lt3<'a> {
82     foo: &'a u32,
83 }
84
85 impl<'a> Lt3<'a> {
86     // The lifetime is different, but that’s irrelevant, see #734
87     pub fn new() -> Lt3<'static> { unimplemented!() }
88 }
89
90 #[derive(Clone,Copy)]
91 struct U;
92
93 impl U {
94     fn new() -> Self { U }
95     fn to_something(self) -> u32 { 0 } // ok because U is Copy
96 }
97
98 struct V<T> {
99     _dummy: T
100 }
101
102 impl<T> V<T> {
103     fn new() -> Option<V<T>> { None }
104 }
105
106 impl Mul<T> for T {
107     type Output = T;
108     fn mul(self, other: T) -> T { self } // no error, obviously
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 /// Struct to generate false positives for things with .iter()
173 #[derive(Copy, Clone)]
174 struct HasIter;
175
176 impl HasIter {
177     fn iter(self) -> IteratorFalsePositives {
178         IteratorFalsePositives { foo: 0 }
179     }
180
181     fn iter_mut(self) -> IteratorFalsePositives {
182         IteratorFalsePositives { foo: 0 }
183     }
184 }
185
186 /// Checks implementation of `FILTER_NEXT` lint
187 fn filter_next() {
188     let v = vec![3, 2, 1, 0, -1, -2, -3];
189
190     // check single-line case
191     let _ = v.iter().filter(|&x| *x < 0).next();
192
193     // check multi-line case
194     let _ = v.iter().filter(|&x| {
195                                 *x < 0
196                             }
197                    ).next();
198
199     // check that we don't lint if the caller is not an Iterator
200     let foo = IteratorFalsePositives { foo: 0 };
201     let _ = foo.filter().next();
202 }
203
204 /// Checks implementation of `SEARCH_IS_SOME` lint
205 fn search_is_some() {
206     let v = vec![3, 2, 1, 0, -1, -2, -3];
207
208     // check `find().is_some()`, single-line
209     let _ = v.iter().find(|&x| *x < 0).is_some();
210
211     // check `find().is_some()`, multi-line
212     let _ = v.iter().find(|&x| {
213                               *x < 0
214                           }
215                    ).is_some();
216
217     // check `position().is_some()`, single-line
218     let _ = v.iter().position(|&x| x < 0).is_some();
219
220     // check `position().is_some()`, multi-line
221     let _ = v.iter().position(|&x| {
222                                   x < 0
223                               }
224                    ).is_some();
225
226     // check `rposition().is_some()`, single-line
227     let _ = v.iter().rposition(|&x| x < 0).is_some();
228
229     // check `rposition().is_some()`, multi-line
230     let _ = v.iter().rposition(|&x| {
231                                    x < 0
232                                }
233                    ).is_some();
234
235     // check that we don't lint if the caller is not an Iterator
236     let foo = IteratorFalsePositives { foo: 0 };
237     let _ = foo.find().is_some();
238     let _ = foo.position().is_some();
239     let _ = foo.rposition().is_some();
240 }
241
242 /// Checks implementation of the `OR_FUN_CALL` lint
243 fn or_fun_call() {
244     struct Foo;
245
246     impl Foo {
247         fn new() -> Foo { Foo }
248     }
249
250     enum Enum {
251         A(i32),
252     }
253
254
255
256     fn make<T>() -> T { unimplemented!(); }
257
258     let with_enum = Some(Enum::A(1));
259     with_enum.unwrap_or(Enum::A(5));
260
261     let with_const_fn = Some(::std::time::Duration::from_secs(1));
262     with_const_fn.unwrap_or(::std::time::Duration::from_secs(5));
263
264     let with_constructor = Some(vec![1]);
265     with_constructor.unwrap_or(make());
266
267     let with_new = Some(vec![1]);
268     with_new.unwrap_or(Vec::new());
269
270     let with_const_args = Some(vec![1]);
271     with_const_args.unwrap_or(Vec::with_capacity(12));
272
273     let with_err : Result<_, ()> = Ok(vec![1]);
274     with_err.unwrap_or(make());
275
276     let with_err_args : Result<_, ()> = Ok(vec![1]);
277     with_err_args.unwrap_or(Vec::with_capacity(12));
278
279     let with_default_trait = Some(1);
280     with_default_trait.unwrap_or(Default::default());
281
282     let with_default_type = Some(1);
283     with_default_type.unwrap_or(u64::default());
284
285     let with_vec = Some(vec![1]);
286     with_vec.unwrap_or(vec![]);
287
288     // FIXME #944: ~|SUGGESTION with_vec.unwrap_or_else(|| vec![]);
289
290     let without_default = Some(Foo);
291     without_default.unwrap_or(Foo::new());
292
293     let mut map = HashMap::<u64, String>::new();
294     map.entry(42).or_insert(String::new());
295
296     let mut btree = BTreeMap::<u64, String>::new();
297     btree.entry(42).or_insert(String::new());
298
299     let stringy = Some(String::from(""));
300     let _ = stringy.unwrap_or("".to_owned());
301 }
302
303 /// Checks implementation of `ITER_NTH` lint
304 fn iter_nth() {
305     let mut some_vec = vec![0, 1, 2, 3];
306     let mut boxed_slice: Box<[u8]> = Box::new([0, 1, 2, 3]);
307     let mut some_vec_deque: VecDeque<_> = some_vec.iter().cloned().collect();
308
309     {
310         // Make sure we lint `.iter()` for relevant types
311         let bad_vec = some_vec.iter().nth(3);
312         let bad_slice = &some_vec[..].iter().nth(3);
313         let bad_boxed_slice = boxed_slice.iter().nth(3);
314         let bad_vec_deque = some_vec_deque.iter().nth(3);
315     }
316
317     {
318         // Make sure we lint `.iter_mut()` for relevant types
319         let bad_vec = some_vec.iter_mut().nth(3);
320     }
321     {
322         let bad_slice = &some_vec[..].iter_mut().nth(3);
323     }
324     {
325         let bad_vec_deque = some_vec_deque.iter_mut().nth(3);
326     }
327
328     // Make sure we don't lint for non-relevant types
329     let false_positive = HasIter;
330     let ok = false_positive.iter().nth(3);
331     let ok_mut = false_positive.iter_mut().nth(3);
332 }
333
334 #[allow(clippy::similar_names)]
335 fn main() {
336     let opt = Some(0);
337     let _ = opt.unwrap();
338 }