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