@@ -2,15 +2,18 @@ use std::convert::Infallible;
2
2
use std:: ops:: ControlFlow ;
3
3
4
4
use clippy_utils:: consts:: { ConstEvalCtxt , Constant } ;
5
- use clippy_utils:: diagnostics:: span_lint;
5
+ use clippy_utils:: diagnostics:: span_lint_and_then;
6
+ use clippy_utils:: msrvs:: { self , Msrv } ;
7
+ use clippy_utils:: sugg:: Sugg ;
6
8
use clippy_utils:: visitors:: { Descend , for_each_expr_without_closures} ;
7
9
use clippy_utils:: { method_chain_args, sext, sym} ;
10
+ use rustc_errors:: Applicability ;
8
11
use rustc_hir:: { BinOpKind , Expr , ExprKind } ;
9
12
use rustc_lint:: LateContext ;
10
13
use rustc_middle:: ty:: { self , Ty } ;
11
14
use rustc_span:: Symbol ;
12
15
13
- use super :: CAST_SIGN_LOSS ;
16
+ use super :: { CAST_SIGN_LOSS , utils } ;
14
17
15
18
/// A list of methods that can never return a negative value.
16
19
/// Includes methods that panic rather than returning a negative value.
@@ -42,13 +45,33 @@ pub(super) fn check<'cx>(
42
45
cast_op : & Expr < ' _ > ,
43
46
cast_from : Ty < ' cx > ,
44
47
cast_to : Ty < ' _ > ,
48
+ msrv : Msrv ,
45
49
) {
46
50
if should_lint ( cx, cast_op, cast_from, cast_to) {
47
- span_lint (
51
+ span_lint_and_then (
48
52
cx,
49
53
CAST_SIGN_LOSS ,
50
54
expr. span ,
51
55
format ! ( "casting `{cast_from}` to `{cast_to}` may lose the sign of the value" ) ,
56
+ |diag| {
57
+ if msrv. meets ( cx, msrvs:: INTEGER_SIGN_CAST )
58
+ && let Some ( cast) = utils:: is_signedness_cast ( cast_from, cast_to)
59
+ {
60
+ let method = match cast {
61
+ utils:: CastTo :: Signed => "cast_signed()" ,
62
+ utils:: CastTo :: Unsigned => "cast_unsigned()" ,
63
+ } ;
64
+ let mut app = Applicability :: MaybeIncorrect ;
65
+ let sugg = Sugg :: hir_with_context ( cx, cast_op, expr. span . ctxt ( ) , ".." , & mut app) ;
66
+
67
+ diag. span_suggestion (
68
+ expr. span ,
69
+ format ! ( "if this is intentional, consider using `{method}` instead" ) ,
70
+ format ! ( "{}.{method}" , sugg. maybe_paren( ) ) ,
71
+ app,
72
+ ) ;
73
+ }
74
+ } ,
52
75
) ;
53
76
}
54
77
}
0 commit comments