11use super :: OBFUSCATED_IF_ELSE ;
22use clippy_utils:: diagnostics:: span_lint_and_sugg;
33use clippy_utils:: source:: snippet_with_applicability;
4+ use clippy_utils:: sugg:: Sugg ;
45use rustc_errors:: Applicability ;
56use rustc_hir as hir;
7+ use rustc_hir:: ExprKind ;
68use rustc_lint:: LateContext ;
79
810pub ( super ) fn check < ' tcx > (
@@ -11,28 +13,33 @@ pub(super) fn check<'tcx>(
1113 then_recv : & ' tcx hir:: Expr < ' _ > ,
1214 then_arg : & ' tcx hir:: Expr < ' _ > ,
1315 unwrap_arg : & ' tcx hir:: Expr < ' _ > ,
16+ then_method_name : & str ,
1417) {
15- // something.then_some(blah).unwrap_or(blah)
16- // ^^^^^^^^^-then_recv ^^^^-then_arg ^^^^- unwrap_arg
17- // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr
18-
1918 let recv_ty = cx. typeck_results ( ) . expr_ty ( then_recv) ;
2019
2120 if recv_ty. is_bool ( ) {
2221 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+
2331 let sugg = format ! (
2432 "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 ,
2735 snippet_with_applicability( cx, unwrap_arg. span, ".." , & mut applicability)
2836 ) ;
2937
3038 span_lint_and_sugg (
3139 cx,
3240 OBFUSCATED_IF_ELSE ,
3341 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 ..`" ,
3643 "try" ,
3744 sugg,
3845 applicability,
0 commit comments