@@ -2,8 +2,9 @@ use clippy_utils::consts::{constant, Constant};
22use clippy_utils:: diagnostics:: { span_lint, span_lint_and_then} ;
33use clippy_utils:: expr_or_init;
44use clippy_utils:: source:: snippet;
5+ use clippy_utils:: sugg:: Sugg ;
56use clippy_utils:: ty:: { get_discriminant_value, is_isize_or_usize} ;
6- use rustc_errors:: { Applicability , SuggestionStyle } ;
7+ use rustc_errors:: { Applicability , Diagnostic , SuggestionStyle } ;
78use rustc_hir:: def:: { DefKind , Res } ;
89use rustc_hir:: { BinOpKind , Expr , ExprKind } ;
910use rustc_lint:: LateContext ;
@@ -163,19 +164,34 @@ pub(super) fn check(
163164 _ => return ,
164165 } ;
165166
166- let name_of_cast_from = snippet ( cx, cast_expr. span , ".." ) ;
167- let cast_to_snip = snippet ( cx, cast_to_span, ".." ) ;
168- let suggestion = format ! ( "{cast_to_snip}::try_from({name_of_cast_from})" ) ;
169-
170167 span_lint_and_then ( cx, CAST_POSSIBLE_TRUNCATION , expr. span , & msg, |diag| {
171168 diag. help ( "if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ..." ) ;
172- diag. span_suggestion_with_style (
173- expr. span ,
174- "... or use `try_from` and handle the error accordingly" ,
175- suggestion,
176- Applicability :: Unspecified ,
177- // always show the suggestion in a separate line
178- SuggestionStyle :: ShowAlways ,
179- ) ;
169+ if !cast_from. is_floating_point ( ) {
170+ offer_suggestion ( cx, expr, cast_expr, cast_to_span, diag) ;
171+ }
180172 } ) ;
181173}
174+
175+ fn offer_suggestion (
176+ cx : & LateContext < ' _ > ,
177+ expr : & Expr < ' _ > ,
178+ cast_expr : & Expr < ' _ > ,
179+ cast_to_span : Span ,
180+ diag : & mut Diagnostic ,
181+ ) {
182+ let cast_to_snip = snippet ( cx, cast_to_span, ".." ) ;
183+ let suggestion = if cast_to_snip == "_" {
184+ format ! ( "{}.try_into()" , Sugg :: hir( cx, cast_expr, ".." ) . maybe_par( ) )
185+ } else {
186+ format ! ( "{cast_to_snip}::try_from({})" , Sugg :: hir( cx, cast_expr, ".." ) )
187+ } ;
188+
189+ diag. span_suggestion_with_style (
190+ expr. span ,
191+ "... or use `try_from` and handle the error accordingly" ,
192+ suggestion,
193+ Applicability :: Unspecified ,
194+ // always show the suggestion in a separate line
195+ SuggestionStyle :: ShowAlways ,
196+ ) ;
197+ }
0 commit comments