1
1
use clippy_utils:: consts:: { constant, Constant } ;
2
- use clippy_utils:: diagnostics:: { span_lint, span_lint_and_help , span_lint_and_then} ;
2
+ use clippy_utils:: diagnostics:: { span_lint, span_lint_and_then} ;
3
3
use clippy_utils:: expr_or_init;
4
4
use clippy_utils:: source:: snippet;
5
5
use clippy_utils:: sugg:: Sugg ;
6
6
use clippy_utils:: ty:: { get_discriminant_value, is_isize_or_usize} ;
7
- use rustc_errors:: { Applicability , SuggestionStyle } ;
7
+ use rustc_errors:: { Applicability , Diagnostic , SuggestionStyle } ;
8
8
use rustc_hir:: def:: { DefKind , Res } ;
9
9
use rustc_hir:: { BinOpKind , Expr , ExprKind } ;
10
10
use rustc_lint:: LateContext ;
@@ -155,14 +155,7 @@ pub(super) fn check(
155
155
} ,
156
156
157
157
( ty:: Float ( _) , true ) => {
158
- return span_lint_and_help (
159
- cx,
160
- CAST_POSSIBLE_TRUNCATION ,
161
- expr. span ,
162
- & format ! ( "casting `{cast_from}` to `{cast_to}` may truncate the value" ) ,
163
- None ,
164
- help,
165
- ) ;
158
+ format ! ( "casting `{cast_from}` to `{cast_to}` may truncate the value" )
166
159
} ,
167
160
168
161
( ty:: Float ( FloatTy :: F64 ) , false ) if matches ! ( cast_to. kind( ) , & ty:: Float ( FloatTy :: F32 ) ) => {
@@ -172,22 +165,34 @@ pub(super) fn check(
172
165
_ => return ,
173
166
} ;
174
167
168
+ span_lint_and_then ( cx, CAST_POSSIBLE_TRUNCATION , expr. span , & msg, |diag| {
169
+ diag. help ( help) ;
170
+ if !cast_from. is_floating_point ( ) {
171
+ offer_suggestion ( cx, expr, cast_expr, cast_to_span, diag) ;
172
+ }
173
+ } ) ;
174
+ }
175
+
176
+ fn offer_suggestion (
177
+ cx : & LateContext < ' _ > ,
178
+ expr : & Expr < ' _ > ,
179
+ cast_expr : & Expr < ' _ > ,
180
+ cast_to_span : Span ,
181
+ diag : & mut Diagnostic ,
182
+ ) {
175
183
let cast_to_snip = snippet ( cx, cast_to_span, ".." ) ;
176
184
let suggestion = if cast_to_snip == "_" {
177
185
format ! ( "{}.try_into()" , Sugg :: hir( cx, cast_expr, ".." ) . maybe_par( ) )
178
186
} else {
179
187
format ! ( "{cast_to_snip}::try_from({})" , Sugg :: hir( cx, cast_expr, ".." ) )
180
188
} ;
181
189
182
- span_lint_and_then ( cx, CAST_POSSIBLE_TRUNCATION , expr. span , & msg, |diag| {
183
- diag. help ( help) ;
184
- diag. span_suggestion_with_style (
185
- expr. span ,
186
- "... or use `try_from` and handle the error accordingly" ,
187
- suggestion,
188
- Applicability :: Unspecified ,
189
- // always show the suggestion in a separate line
190
- SuggestionStyle :: ShowAlways ,
191
- ) ;
192
- } ) ;
190
+ diag. span_suggestion_with_style (
191
+ expr. span ,
192
+ "... or use `try_from` and handle the error accordingly" ,
193
+ suggestion,
194
+ Applicability :: Unspecified ,
195
+ // always show the suggestion in a separate line
196
+ SuggestionStyle :: ShowAlways ,
197
+ ) ;
193
198
}
0 commit comments