]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/casts/fn_to_numeric_cast_with_truncation.rs
Rollup merge of #102227 - devnexen:solarish_get_path, r=m-ou-se
[rust.git] / src / tools / clippy / clippy_lints / src / casts / fn_to_numeric_cast_with_truncation.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use rustc_errors::Applicability;
4 use rustc_hir::Expr;
5 use rustc_lint::LateContext;
6 use rustc_middle::ty::{self, Ty};
7
8 use super::{utils, FN_TO_NUMERIC_CAST_WITH_TRUNCATION};
9
10 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
11     // We only want to check casts to `ty::Uint` or `ty::Int`
12     match cast_to.kind() {
13         ty::Uint(_) | ty::Int(..) => { /* continue on */ },
14         _ => return,
15     }
16     match cast_from.kind() {
17         ty::FnDef(..) | ty::FnPtr(_) => {
18             let mut applicability = Applicability::MaybeIncorrect;
19             let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
20
21             let to_nbits = utils::int_ty_to_nbits(cast_to, cx.tcx);
22             if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
23                 span_lint_and_sugg(
24                     cx,
25                     FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
26                     expr.span,
27                     &format!("casting function pointer `{from_snippet}` to `{cast_to}`, which truncates the value"),
28                     "try",
29                     format!("{from_snippet} as usize"),
30                     applicability,
31                 );
32             }
33         },
34         _ => {},
35     }
36 }