1 use clippy_utils::consts::{constant_context, Constant};
2 use clippy_utils::diagnostics::span_lint;
3 use clippy_utils::is_path_diagnostic_item;
4 use if_chain::if_chain;
5 use rustc_ast::LitKind;
6 use rustc_hir::{Expr, ExprKind};
7 use rustc_lint::LateContext;
8 use rustc_middle::ty::Ty;
9 use rustc_span::symbol::sym;
11 use super::TRANSMUTING_NULL;
13 const LINT_MSG: &str = "transmuting a known null pointer into a reference";
15 pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, arg: &'tcx Expr<'_>, to_ty: Ty<'tcx>) -> bool {
20 // Catching transmute over constants that resolve to `null`.
21 let mut const_eval_context = constant_context(cx, cx.typeck_results());
23 if let ExprKind::Path(ref _qpath) = arg.kind;
24 if let Some(Constant::RawPtr(x)) = const_eval_context.expr(arg);
27 span_lint(cx, TRANSMUTING_NULL, expr.span, LINT_MSG);
33 // `std::mem::transmute(0 as *const i32)`
35 if let ExprKind::Cast(inner_expr, _cast_ty) = arg.kind;
36 if let ExprKind::Lit(ref lit) = inner_expr.kind;
37 if let LitKind::Int(0, _) = lit.node;
39 span_lint(cx, TRANSMUTING_NULL, expr.span, LINT_MSG);
45 // `std::mem::transmute(std::ptr::null::<i32>())`
47 if let ExprKind::Call(func1, []) = arg.kind;
48 if is_path_diagnostic_item(cx, func1, sym::ptr_null);
50 span_lint(cx, TRANSMUTING_NULL, expr.span, LINT_MSG);
56 // Also catch transmutations of variables which are known nulls.
57 // To do this, MIR const propagation seems to be the better tool.
58 // Whenever MIR const prop routines are more developed, this will
59 // become available. As of this writing (25/03/19) it is not yet.