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