@@ -4,7 +4,6 @@ use rustc_errors::Applicability;
44use rustc_hir:: * ;
55use rustc_lint:: { LateContext , LateLintPass } ;
66use rustc_session:: { declare_lint_pass, declare_tool_lint} ;
7- use rustc_span:: BytePos ;
87
98declare_clippy_lint ! {
109 /// **What it does:*** Checks for unnecessary `ok()` in if let.
@@ -46,33 +45,27 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OkIfLet {
4645 if let ExprKind :: MethodCall ( _, ok_span, ref result_types) = op. kind; //check is expr.ok() has type Result<T,E>.ok()
4746 if let PatKind :: TupleStruct ( QPath :: Resolved ( _, ref x) , ref y, _) = body[ 0 ] . pat. kind; //get operation
4847 if method_chain_args( op, & [ "ok" ] ) . is_some( ) ; //test to see if using ok() methoduse std::marker::Sized;
48+ let is_result_type = match_type( cx, cx. tables. expr_ty( & result_types[ 0 ] ) , & paths:: RESULT ) ;
49+ if print:: to_string( print:: NO_ANN , |s| s. print_path( x, false ) ) == "Some" && is_result_type;
4950
5051 then {
51- let is_result_type = match_type( cx, cx. tables. expr_ty( & result_types[ 0 ] ) , & paths:: RESULT ) ;
5252 let mut applicability = Applicability :: MachineApplicable ;
53- // ok_span = `ok`
54- // op.span = `x.parse() . ok()`
55- // op.span.until(op.span.with_lo(ok_span.lo() - BytePos(1))) = `x.parse() .`
56- // op.span.with_lo(ok_span.lo() - BytePos(1)) = ` ok()`
57- // op.span.with_hi(ok_span.hi() - BytePos(1)) = `x.parse() . o`
5853 let some_expr_string = snippet_with_applicability( cx, y[ 0 ] . span, "" , & mut applicability) ;
5954 let trimmed_ok = snippet_with_applicability( cx, op. span. until( ok_span) , "" , & mut applicability) ;
6055 let sugg = format!(
6156 "if let Ok({}) = {}" ,
6257 some_expr_string,
6358 trimmed_ok. trim( ) . trim_end_matches( '.' ) ,
6459 ) ;
65- if print:: to_string( print:: NO_ANN , |s| s. print_path( x, false ) ) == "Some" && is_result_type {
66- span_lint_and_sugg(
67- cx,
68- IF_LET_SOME_RESULT ,
69- expr. span. with_hi( ok_span. hi( ) + BytePos ( 2 ) ) ,
70- "Matching on `Some` with `ok()` is redundant" ,
71- & format!( "Consider matching on `Ok({})` and removing the call to `ok` instead" , some_expr_string) ,
72- sugg,
73- applicability,
74- ) ;
75- }
60+ span_lint_and_sugg(
61+ cx,
62+ IF_LET_SOME_RESULT ,
63+ expr. span. with_hi( op. span. hi( ) ) ,
64+ "Matching on `Some` with `ok()` is redundant" ,
65+ & format!( "Consider matching on `Ok({})` and removing the call to `ok` instead" , some_expr_string) ,
66+ sugg,
67+ applicability,
68+ ) ;
7669 }
7770 }
7871 }
0 commit comments