]> git.lizzy.rs Git - rust.git/blob - tests/ui/try_err.rs
5e85d091a2ae73359046f06a82d7e3ce744d9672
[rust.git] / tests / ui / try_err.rs
1 // run-rustfix
2 // aux-build:macro_rules.rs
3
4 #![deny(clippy::try_err)]
5
6 #[macro_use]
7 extern crate macro_rules;
8
9 // Tests that a simple case works
10 // Should flag `Err(err)?`
11 pub fn basic_test() -> Result<i32, i32> {
12     let err: i32 = 1;
13     // To avoid warnings during rustfix
14     if true {
15         Err(err)?;
16     }
17     Ok(0)
18 }
19
20 // Tests that `.into()` is added when appropriate
21 pub fn into_test() -> Result<i32, i32> {
22     let err: u8 = 1;
23     // To avoid warnings during rustfix
24     if true {
25         Err(err)?;
26     }
27     Ok(0)
28 }
29
30 // Tests that tries in general don't trigger the error
31 pub fn negative_test() -> Result<i32, i32> {
32     Ok(nested_error()? + 1)
33 }
34
35 // Tests that `.into()` isn't added when the error type
36 // matches the surrounding closure's return type, even
37 // when it doesn't match the surrounding function's.
38 pub fn closure_matches_test() -> Result<i32, i32> {
39     let res: Result<i32, i8> = Some(1)
40         .into_iter()
41         .map(|i| {
42             let err: i8 = 1;
43             // To avoid warnings during rustfix
44             if true {
45                 Err(err)?;
46             }
47             Ok(i)
48         })
49         .next()
50         .unwrap();
51
52     Ok(res?)
53 }
54
55 // Tests that `.into()` isn't added when the error type
56 // doesn't match the surrounding closure's return type.
57 pub fn closure_into_test() -> Result<i32, i32> {
58     let res: Result<i32, i16> = Some(1)
59         .into_iter()
60         .map(|i| {
61             let err: i8 = 1;
62             // To avoid warnings during rustfix
63             if true {
64                 Err(err)?;
65             }
66             Ok(i)
67         })
68         .next()
69         .unwrap();
70
71     Ok(res?)
72 }
73
74 fn nested_error() -> Result<i32, i32> {
75     Ok(1)
76 }
77
78 fn main() {
79     basic_test().unwrap();
80     into_test().unwrap();
81     negative_test().unwrap();
82     closure_matches_test().unwrap();
83     closure_into_test().unwrap();
84
85     // We don't want to lint in external macros
86     try_err!();
87 }
88
89 macro_rules! bar {
90     () => {
91         String::from("aasdfasdfasdfa")
92     };
93 }
94
95 macro_rules! foo {
96     () => {
97         bar!()
98     };
99 }
100
101 pub fn macro_inside(fail: bool) -> Result<i32, String> {
102     if fail {
103         Err(foo!())?;
104     }
105     Ok(0)
106 }