1 use crate::utils::{match_def_path, paths, snippet, span_lint_and_then, walk_ptrs_ty_depth};
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::{BorrowKind, Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for calls of `mem::discriminant()` on a non-enum type.
13 /// **Why is this bad?** The value of `mem::discriminant()` on non-enum types
16 /// **Known problems:** None.
22 /// mem::discriminant(&"hello");
23 /// mem::discriminant(&&Some(2));
25 pub MEM_DISCRIMINANT_NON_ENUM,
27 "calling `mem::descriminant` on non-enum type"
30 declare_lint_pass!(MemDiscriminant => [MEM_DISCRIMINANT_NON_ENUM]);
32 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemDiscriminant {
33 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
35 if let ExprKind::Call(ref func, ref func_args) = expr.kind;
36 // is `mem::discriminant`
37 if let ExprKind::Path(ref func_qpath) = func.kind;
38 if let Some(def_id) = cx.tables.qpath_res(func_qpath, func.hir_id).opt_def_id();
39 if match_def_path(cx, def_id, &paths::MEM_DISCRIMINANT);
41 let ty_param = cx.tables.node_substs(func.hir_id).type_at(0);
42 if !ty_param.is_enum();
47 MEM_DISCRIMINANT_NON_ENUM,
49 &format!("calling `mem::discriminant` on non-enum type `{}`", ty_param),
51 // if this is a reference to an enum, suggest dereferencing
52 let (base_ty, ptr_depth) = walk_ptrs_ty_depth(ty_param);
53 if ptr_depth >= 1 && base_ty.is_enum() {
54 let param = &func_args[0];
56 // cancel out '&'s first
57 let mut derefs_needed = ptr_depth;
58 let mut cur_expr = param;
59 while derefs_needed > 0 {
60 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref inner_expr) = cur_expr.kind {
62 cur_expr = inner_expr;
68 let derefs: String = iter::repeat('*').take(derefs_needed).collect();
72 format!("{}{}", derefs, snippet(cx, cur_expr.span, "<param>")),
73 Applicability::MachineApplicable,