@@ -3,6 +3,7 @@ use rustc_errors::Applicability;
3
3
use rustc_hir:: def:: Res ;
4
4
use rustc_hir:: { Arm , Expr , ExprKind , HirId , LangItem , MatchSource , Pat , PatKind , QPath } ;
5
5
use rustc_lint:: { LateContext , LateLintPass , LintContext } ;
6
+ use rustc_middle:: ty:: GenericArgKind ;
6
7
use rustc_session:: declare_lint_pass;
7
8
use rustc_span:: sym;
8
9
@@ -118,6 +119,10 @@ fn handle_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
118
119
&& implements_trait ( cx, match_ty, default_trait_id, & [ ] )
119
120
// We now get the bodies for both the `Some` and `None` arms.
120
121
&& let Some ( ( ( body_some, binding_id) , body_none) ) = get_some_and_none_bodies ( cx, arm1, arm2)
122
+ // We check that the initial expression also implies the `Default` trait.
123
+ && let Some ( match_expr_ty) = cx. typeck_results ( ) . expr_ty ( match_expr) . walk ( ) . nth ( 1 )
124
+ && let GenericArgKind :: Type ( match_expr_ty) = match_expr_ty. unpack ( )
125
+ && implements_trait ( cx, match_expr_ty, default_trait_id, & [ ] )
121
126
// We check that the `Some(x) => x` doesn't do anything apart "returning" the value in `Some`.
122
127
&& let ExprKind :: Path ( QPath :: Resolved ( _, path) ) = peel_blocks ( body_some) . kind
123
128
&& let Res :: Local ( local_id) = path. res
@@ -154,6 +159,10 @@ fn handle_if_let<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
154
159
&& let Some ( default_trait_id) = cx. tcx . get_diagnostic_item ( sym:: Default )
155
160
&& implements_trait ( cx, match_ty, default_trait_id, & [ ] )
156
161
&& let Some ( binding_id) = get_some ( cx, let_. pat )
162
+ // We check that the initial expression also implies the `Default` trait.
163
+ && let Some ( let_ty) = cx. typeck_results ( ) . expr_ty ( let_. init ) . walk ( ) . nth ( 1 )
164
+ && let GenericArgKind :: Type ( let_ty) = let_ty. unpack ( )
165
+ && implements_trait ( cx, let_ty, default_trait_id, & [ ] )
157
166
// We check that the `Some(x) => x` doesn't do anything apart "returning" the value in `Some`.
158
167
&& let ExprKind :: Path ( QPath :: Resolved ( _, path) ) = peel_blocks ( if_block) . kind
159
168
&& let Res :: Local ( local_id) = path. res
0 commit comments