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.
11 use crate::rustc::hir::{Expr, ExprKind};
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_errors::Applicability;
15 use crate::utils::{match_def_path, opt_def_id, paths, snippet, span_lint_and_then, walk_ptrs_ty_depth};
16 use if_chain::if_chain;
20 /// **What it does:** Checks for calls of `mem::discriminant()` on a non-enum type.
22 /// **Why is this bad?** The value of `mem::discriminant()` on non-enum types
25 /// **Known problems:** None.
29 /// mem::discriminant(&"hello");
30 /// mem::discriminant(&&Some(2));
32 declare_clippy_lint! {
33 pub MEM_DISCRIMINANT_NON_ENUM,
35 "calling mem::descriminant on non-enum type"
38 pub struct MemDiscriminant;
40 impl LintPass for MemDiscriminant {
41 fn get_lints(&self) -> LintArray {
42 lint_array![MEM_DISCRIMINANT_NON_ENUM]
46 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemDiscriminant {
47 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
49 if let ExprKind::Call(ref func, ref func_args) = expr.node;
50 // is `mem::discriminant`
51 if let ExprKind::Path(ref func_qpath) = func.node;
52 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(func_qpath, func.hir_id));
53 if match_def_path(cx.tcx, def_id, &paths::MEM_DISCRIMINANT);
55 let ty_param = cx.tables.node_substs(func.hir_id).type_at(0);
56 if !ty_param.is_enum();
61 MEM_DISCRIMINANT_NON_ENUM,
63 &format!("calling `mem::discriminant` on non-enum type `{}`", ty_param),
65 // if this is a reference to an enum, suggest dereferencing
66 let (base_ty, ptr_depth) = walk_ptrs_ty_depth(ty_param);
67 if ptr_depth >= 1 && base_ty.is_enum() {
68 let param = &func_args[0];
70 // cancel out '&'s first
71 let mut derefs_needed = ptr_depth;
72 let mut cur_expr = param;
73 while derefs_needed > 0 {
74 if let ExprKind::AddrOf(_, ref inner_expr) = cur_expr.node {
76 cur_expr = inner_expr;
82 let derefs: String = iter::repeat('*').take(derefs_needed).collect();
83 db.span_suggestion_with_applicability(
86 format!("{}{}", derefs, snippet(cx, cur_expr.span, "<param>")),
87 Applicability::MachineApplicable,