|
| 1 | +use rustc_hir as hir; |
| 2 | +use rustc_middle::ty; |
| 3 | +use rustc_session::{declare_lint, declare_lint_pass}; |
| 4 | +use rustc_span::BytePos; |
| 5 | + |
| 6 | +use crate::lints::{FunctionCastsAsIntegerDiag, FunctionCastsAsIntegerSugg}; |
| 7 | +use crate::{LateContext, LateLintPass}; |
| 8 | + |
| 9 | +declare_lint! { |
| 10 | + /// The `function_casts_as_integer` lint detects cases where a function item is casted |
| 11 | + /// into an integer. |
| 12 | + /// |
| 13 | + /// ### Example |
| 14 | + /// |
| 15 | + /// ```rust |
| 16 | + /// fn foo() {} |
| 17 | + /// let x = foo as usize; |
| 18 | + /// ``` |
| 19 | + /// |
| 20 | + /// {{produces}} |
| 21 | + /// |
| 22 | + /// ### Explanation |
| 23 | + /// |
| 24 | + /// When casting a function item into an integer, it's implicitly creating a |
| 25 | + /// function pointer that will in turn be casted into an integer. By making |
| 26 | + /// it explicit, it improves readability of the code and prevents bugs. |
| 27 | + pub FUNCTION_CASTS_AS_INTEGER, |
| 28 | + Warn, |
| 29 | + "casting a function into an integer", |
| 30 | +} |
| 31 | + |
| 32 | +declare_lint_pass!( |
| 33 | + /// Lint for casts of functions into integers. |
| 34 | + FunctionCastsAsInteger => [FUNCTION_CASTS_AS_INTEGER] |
| 35 | +); |
| 36 | + |
| 37 | +impl<'tcx> LateLintPass<'tcx> for FunctionCastsAsInteger { |
| 38 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { |
| 39 | + let hir::ExprKind::Cast(cast_from_expr, cast_to_expr) = expr.kind else { return }; |
| 40 | + let cast_to_ty = cx.typeck_results().expr_ty(expr); |
| 41 | + // Casting to a function (pointer?), so all good. |
| 42 | + if matches!(cast_to_ty.kind(), ty::FnDef(..) | ty::FnPtr(..)) { |
| 43 | + return; |
| 44 | + } |
| 45 | + let cast_from_ty = cx.typeck_results().expr_ty(cast_from_expr); |
| 46 | + if matches!(cast_from_ty.kind(), ty::FnDef(..)) { |
| 47 | + cx.tcx.emit_node_span_lint( |
| 48 | + FUNCTION_CASTS_AS_INTEGER, |
| 49 | + expr.hir_id, |
| 50 | + cast_to_expr.span.with_lo(cast_from_expr.span.hi() + BytePos(1)), |
| 51 | + FunctionCastsAsIntegerDiag { |
| 52 | + sugg: FunctionCastsAsIntegerSugg { |
| 53 | + suggestion: cast_from_expr.span.shrink_to_hi(), |
| 54 | + // We get the function pointer to have a nice display. |
| 55 | + cast_from_ty: cx.typeck_results().expr_ty_adjusted(cast_from_expr), |
| 56 | + cast_to_ty, |
| 57 | + }, |
| 58 | + }, |
| 59 | + ); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments