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::declare_lint_pass;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc_errors::Applicability;
6 use rustc_hir::{BorrowKind, Expr, ExprKind};
7 use rustc_session::declare_tool_lint;
11 declare_clippy_lint! {
12 /// **What it does:** Checks for calls of `mem::discriminant()` on a non-enum type.
14 /// **Why is this bad?** The value of `mem::discriminant()` on non-enum types
17 /// **Known problems:** None.
23 /// mem::discriminant(&"hello");
24 /// mem::discriminant(&&Some(2));
26 pub MEM_DISCRIMINANT_NON_ENUM,
28 "calling mem::descriminant on non-enum type"
31 declare_lint_pass!(MemDiscriminant => [MEM_DISCRIMINANT_NON_ENUM]);
33 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemDiscriminant {
34 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
36 if let ExprKind::Call(ref func, ref func_args) = expr.kind;
37 // is `mem::discriminant`
38 if let ExprKind::Path(ref func_qpath) = func.kind;
39 if let Some(def_id) = cx.tables.qpath_res(func_qpath, func.hir_id).opt_def_id();
40 if match_def_path(cx, def_id, &paths::MEM_DISCRIMINANT);
42 let ty_param = cx.tables.node_substs(func.hir_id).type_at(0);
43 if !ty_param.is_enum();
48 MEM_DISCRIMINANT_NON_ENUM,
50 &format!("calling `mem::discriminant` on non-enum type `{}`", ty_param),
52 // if this is a reference to an enum, suggest dereferencing
53 let (base_ty, ptr_depth) = walk_ptrs_ty_depth(ty_param);
54 if ptr_depth >= 1 && base_ty.is_enum() {
55 let param = &func_args[0];
57 // cancel out '&'s first
58 let mut derefs_needed = ptr_depth;
59 let mut cur_expr = param;
60 while derefs_needed > 0 {
61 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref inner_expr) = cur_expr.kind {
63 cur_expr = inner_expr;
69 let derefs: String = iter::repeat('*').take(derefs_needed).collect();
73 format!("{}{}", derefs, snippet(cx, cur_expr.span, "<param>")),
74 Applicability::MachineApplicable,