]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/casts/fn_to_numeric_cast_with_truncation.rs
hir: Preserve used syntax in `TyKind::TraitObject`
[rust.git] / clippy_lints / src / casts / fn_to_numeric_cast_with_truncation.rs
1 use rustc_errors::Applicability;
2 use rustc_hir::Expr;
3 use rustc_lint::LateContext;
4 use rustc_middle::ty::{self, Ty};
5
6 use crate::utils::{snippet_with_applicability, span_lint_and_sugg};
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!(
28                         "casting function pointer `{}` to `{}`, which truncates the value",
29                         from_snippet, cast_to
30                     ),
31                     "try",
32                     format!("{} as usize", from_snippet),
33                     applicability,
34                 );
35             }
36         },
37         _ => {},
38     }
39 }