@@ -2,7 +2,7 @@ use rustc_errors::Applicability;
2
2
use rustc_hir:: def:: Res ;
3
3
use rustc_hir:: { Arm , Expr , ExprKind , HirId , LangItem , MatchSource , Pat , PatKind , QPath } ;
4
4
use rustc_lint:: { LateContext , LateLintPass , LintContext } ;
5
- use rustc_middle:: ty:: GenericArgKind ;
5
+ use rustc_middle:: ty:: { self , GenericArgKind } ;
6
6
use rustc_session:: declare_lint_pass;
7
7
use rustc_span:: sym;
8
8
@@ -152,6 +152,42 @@ fn handle<'tcx>(cx: &LateContext<'tcx>, if_let_or_match: IfLetOrMatch<'tcx>, exp
152
152
&& is_default_equivalent ( cx, body_none)
153
153
&& let Some ( receiver) = Sugg :: hir_opt ( cx, condition) . map ( Sugg :: maybe_par)
154
154
{
155
+ // We check if the expression is not a None variant
156
+ if let Some ( none_def_id) = cx. tcx . lang_items ( ) . option_none_variant ( ) {
157
+ if let ExprKind :: Path ( QPath :: Resolved ( _, path) ) = & condition. kind {
158
+ if let Some ( def_id) = path. res . opt_def_id ( ) {
159
+ if cx. tcx . parent ( def_id) == none_def_id {
160
+ return span_lint_and_sugg (
161
+ cx,
162
+ MANUAL_UNWRAP_OR_DEFAULT ,
163
+ expr. span ,
164
+ format ! ( "{expr_name} can be simplified with `.unwrap_or_default()`" ) ,
165
+ "replace it with" ,
166
+ format ! ( "{receiver}::</* Type */>.unwrap_or_default()" ) ,
167
+ Applicability :: HasPlaceholders ,
168
+ ) ;
169
+ }
170
+ }
171
+ }
172
+ }
173
+
174
+ // We check if the expression is not a method or function with a unspecified return type
175
+ if let ExprKind :: MethodCall ( _, expr, _, _) = & condition. kind {
176
+ if let ty:: Adt ( _, substs) = cx. typeck_results ( ) . expr_ty ( expr) . kind ( ) {
177
+ if let Some ( ok_type) = substs. first ( ) {
178
+ return span_lint_and_sugg (
179
+ cx,
180
+ MANUAL_UNWRAP_OR_DEFAULT ,
181
+ expr. span ,
182
+ format ! ( "{expr_name} can be simplified with `.unwrap_or_default()`" ) ,
183
+ format ! ( "explicit the type {ok_type} and replace your expression with" ) ,
184
+ format ! ( "{receiver}.unwrap_or_default()" ) ,
185
+ Applicability :: Unspecified ,
186
+ ) ;
187
+ }
188
+ }
189
+ }
190
+
155
191
// Machine applicable only if there are no comments present
156
192
let applicability = if span_contains_comment ( cx. sess ( ) . source_map ( ) , expr. span ) {
157
193
Applicability :: MaybeIncorrect
0 commit comments