1
1
use super :: OBFUSCATED_IF_ELSE ;
2
2
use clippy_utils:: diagnostics:: span_lint_and_sugg;
3
3
use clippy_utils:: source:: snippet_with_applicability;
4
+ use clippy_utils:: sugg:: Sugg ;
4
5
use rustc_errors:: Applicability ;
5
6
use rustc_hir as hir;
7
+ use rustc_hir:: ExprKind ;
6
8
use rustc_lint:: LateContext ;
7
9
8
10
pub ( super ) fn check < ' tcx > (
@@ -11,28 +13,33 @@ pub(super) fn check<'tcx>(
11
13
then_recv : & ' tcx hir:: Expr < ' _ > ,
12
14
then_arg : & ' tcx hir:: Expr < ' _ > ,
13
15
unwrap_arg : & ' tcx hir:: Expr < ' _ > ,
16
+ then_method_name : & str ,
14
17
) {
15
- // something.then_some(blah).unwrap_or(blah)
16
- // ^^^^^^^^^-then_recv ^^^^-then_arg ^^^^- unwrap_arg
17
- // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr
18
-
19
18
let recv_ty = cx. typeck_results ( ) . expr_ty ( then_recv) ;
20
19
21
20
if recv_ty. is_bool ( ) {
22
21
let mut applicability = Applicability :: MachineApplicable ;
22
+ let if_then = match then_method_name {
23
+ "then" if let ExprKind :: Closure ( closure) = then_arg. kind => {
24
+ let body = cx. tcx . hir ( ) . body ( closure. body ) ;
25
+ snippet_with_applicability ( cx, body. value . span , ".." , & mut applicability)
26
+ } ,
27
+ "then_some" => snippet_with_applicability ( cx, then_arg. span , ".." , & mut applicability) ,
28
+ _ => String :: new ( ) . into ( ) ,
29
+ } ;
30
+
23
31
let sugg = format ! (
24
32
"if {} {{ {} }} else {{ {} }}" ,
25
- snippet_with_applicability ( cx, then_recv. span , ".." , & mut applicability) ,
26
- snippet_with_applicability ( cx , then_arg . span , ".." , & mut applicability ) ,
33
+ Sugg :: hir_with_applicability ( cx, then_recv, ".." , & mut applicability) ,
34
+ if_then ,
27
35
snippet_with_applicability( cx, unwrap_arg. span, ".." , & mut applicability)
28
36
) ;
29
37
30
38
span_lint_and_sugg (
31
39
cx,
32
40
OBFUSCATED_IF_ELSE ,
33
41
expr. span ,
34
- "use of `.then_some(..).unwrap_or(..)` can be written \
35
- more clearly with `if .. else ..`",
42
+ "this method chain can be written more clearly with `if .. else ..`" ,
36
43
"try" ,
37
44
sugg,
38
45
applicability,
0 commit comments