@@ -12,13 +12,13 @@ use rustc_hir::LangItem::{self, OptionNone, OptionSome, PollPending, PollReady,
1212use rustc_hir:: { Arm , Expr , ExprKind , Guard , Node , Pat , PatKind , QPath , UnOp } ;
1313use rustc_lint:: LateContext ;
1414use rustc_middle:: ty:: { self , GenericArgKind , Ty } ;
15- use rustc_span:: { sym, Symbol } ;
15+ use rustc_span:: { sym, Span , Symbol } ;
1616use std:: fmt:: Write ;
1717use std:: ops:: ControlFlow ;
1818
1919pub ( super ) fn check < ' tcx > ( cx : & LateContext < ' tcx > , expr : & ' tcx Expr < ' _ > ) {
2020 if let Some ( higher:: WhileLet { let_pat, let_expr, .. } ) = higher:: WhileLet :: hir ( expr) {
21- find_sugg_for_if_let ( cx, expr, let_pat, let_expr, "while" , false ) ;
21+ find_method_sugg_for_if_let ( cx, expr, let_pat, let_expr, "while" , false ) ;
2222 }
2323}
2424
@@ -28,8 +28,34 @@ pub(super) fn check_if_let<'tcx>(
2828 pat : & ' tcx Pat < ' _ > ,
2929 scrutinee : & ' tcx Expr < ' _ > ,
3030 has_else : bool ,
31+ let_span : Span ,
3132) {
32- find_sugg_for_if_let ( cx, expr, pat, scrutinee, "if" , has_else) ;
33+ find_if_let_true ( cx, pat, scrutinee, let_span) ;
34+ find_method_sugg_for_if_let ( cx, expr, pat, scrutinee, "if" , has_else) ;
35+ }
36+
37+ fn find_if_let_true < ' tcx > ( cx : & LateContext < ' tcx > , pat : & ' tcx Pat < ' _ > , scrutinee : & ' tcx Expr < ' _ > , let_span : Span ) {
38+ if let PatKind :: Lit ( lit) = pat. kind
39+ && let ExprKind :: Lit ( lit) = lit. kind
40+ && let LitKind :: Bool ( is_true) = lit. node
41+ {
42+ let mut snip = snippet ( cx, scrutinee. span , ".." ) . into_owned ( ) ;
43+
44+ if !is_true {
45+ // Invert condition for `if let false = ...`
46+ snip. insert ( 0 , '!' ) ;
47+ }
48+
49+ span_lint_and_sugg (
50+ cx,
51+ REDUNDANT_PATTERN_MATCHING ,
52+ let_span,
53+ "using `if let` to pattern match a boolean" ,
54+ "consider using a regular `if` expression" ,
55+ snip,
56+ Applicability :: MachineApplicable ,
57+ ) ;
58+ }
3359}
3460
3561// Extract the generic arguments out of a type
@@ -100,7 +126,7 @@ fn find_method_and_type<'tcx>(
100126 }
101127}
102128
103- fn find_sugg_for_if_let < ' tcx > (
129+ fn find_method_sugg_for_if_let < ' tcx > (
104130 cx : & LateContext < ' tcx > ,
105131 expr : & ' tcx Expr < ' _ > ,
106132 let_pat : & Pat < ' _ > ,
0 commit comments