1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir::{Expr, ExprKind};
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::rustc_errors::Applicability;
14 use crate::utils::{match_def_path, opt_def_id, paths, snippet, span_lint_and_then, walk_ptrs_ty_depth};
15 use if_chain::if_chain;
19 /// **What it does:** Checks for calls of `mem::discriminant()` on a non-enum type.
21 /// **Why is this bad?** The value of `mem::discriminant()` on non-enum types
24 /// **Known problems:** None.
28 /// mem::discriminant(&"hello");
29 /// mem::discriminant(&&Some(2));
31 declare_clippy_lint! {
32 pub MEM_DISCRIMINANT_NON_ENUM,
34 "calling mem::descriminant on non-enum type"
37 pub struct MemDiscriminant;
39 impl LintPass for MemDiscriminant {
40 fn get_lints(&self) -> LintArray {
41 lint_array![MEM_DISCRIMINANT_NON_ENUM]
45 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemDiscriminant {
46 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
48 if let ExprKind::Call(ref func, ref func_args) = expr.node;
49 // is `mem::discriminant`
50 if let ExprKind::Path(ref func_qpath) = func.node;
51 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(func_qpath, func.hir_id));
52 if match_def_path(cx.tcx, def_id, &paths::MEM_DISCRIMINANT);
54 let ty_param = cx.tables.node_substs(func.hir_id).type_at(0);
55 if !ty_param.is_enum();
60 MEM_DISCRIMINANT_NON_ENUM,
62 &format!("calling `mem::discriminant` on non-enum type `{}`", ty_param),
64 // if this is a reference to an enum, suggest dereferencing
65 let (base_ty, ptr_depth) = walk_ptrs_ty_depth(ty_param);
66 if ptr_depth >= 1 && base_ty.is_enum() {
67 let param = &func_args[0];
69 // cancel out '&'s first
70 let mut derefs_needed = ptr_depth;
71 let mut cur_expr = param;
72 while derefs_needed > 0 {
73 if let ExprKind::AddrOf(_, ref inner_expr) = cur_expr.node {
75 cur_expr = inner_expr;
81 let derefs: String = iter::repeat('*').take(derefs_needed).collect();
82 db.span_suggestion_with_applicability(
85 format!("{}{}", derefs, snippet(cx, cur_expr.span, "<param>")),
86 Applicability::MachineApplicable,