@@ -4,7 +4,6 @@ use rustc_errors::Applicability;
4
4
use rustc_hir:: * ;
5
5
use rustc_lint:: { LateContext , LateLintPass } ;
6
6
use rustc_session:: { declare_lint_pass, declare_tool_lint} ;
7
- use rustc_span:: BytePos ;
8
7
9
8
declare_clippy_lint ! {
10
9
/// **What it does:*** Checks for unnecessary `ok()` in if let.
@@ -46,33 +45,27 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OkIfLet {
46
45
if let ExprKind :: MethodCall ( _, ok_span, ref result_types) = op. kind; //check is expr.ok() has type Result<T,E>.ok()
47
46
if let PatKind :: TupleStruct ( QPath :: Resolved ( _, ref x) , ref y, _) = body[ 0 ] . pat. kind; //get operation
48
47
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;
49
50
50
51
then {
51
- let is_result_type = match_type( cx, cx. tables. expr_ty( & result_types[ 0 ] ) , & paths:: RESULT ) ;
52
52
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`
58
53
let some_expr_string = snippet_with_applicability( cx, y[ 0 ] . span, "" , & mut applicability) ;
59
54
let trimmed_ok = snippet_with_applicability( cx, op. span. until( ok_span) , "" , & mut applicability) ;
60
55
let sugg = format!(
61
56
"if let Ok({}) = {}" ,
62
57
some_expr_string,
63
58
trimmed_ok. trim( ) . trim_end_matches( '.' ) ,
64
59
) ;
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
+ ) ;
76
69
}
77
70
}
78
71
}
0 commit comments