]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mem_discriminant.rs
Merge remote-tracking branch 'upstream/master'
[rust.git] / clippy_lints / src / mem_discriminant.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
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.
9
10
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;
17
18 use std::iter;
19
20 /// **What it does:** Checks for calls of `mem::discriminant()` on a non-enum type.
21 ///
22 /// **Why is this bad?** The value of `mem::discriminant()` on non-enum types
23 /// is unspecified.
24 ///
25 /// **Known problems:** None.
26 ///
27 /// **Example:**
28 /// ```rust
29 /// mem::discriminant(&"hello");
30 /// mem::discriminant(&&Some(2));
31 /// ```
32 declare_clippy_lint! {
33     pub MEM_DISCRIMINANT_NON_ENUM,
34     correctness,
35     "calling mem::descriminant on non-enum type"
36 }
37
38 pub struct MemDiscriminant;
39
40 impl LintPass for MemDiscriminant {
41     fn get_lints(&self) -> LintArray {
42         lint_array![MEM_DISCRIMINANT_NON_ENUM]
43     }
44 }
45
46 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemDiscriminant {
47     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
48         if_chain! {
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);
54             // type is non-enum
55             let ty_param = cx.tables.node_substs(func.hir_id).type_at(0);
56             if !ty_param.is_enum();
57
58             then {
59                 span_lint_and_then(
60                     cx,
61                     MEM_DISCRIMINANT_NON_ENUM,
62                     expr.span,
63                     &format!("calling `mem::discriminant` on non-enum type `{}`", ty_param),
64                     |db| {
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];
69
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 {
75                                     derefs_needed -= 1;
76                                     cur_expr = inner_expr;
77                                 } else {
78                                     break;
79                                 }
80                             }
81
82                             let derefs: String = iter::repeat('*').take(derefs_needed).collect();
83                             db.span_suggestion_with_applicability(
84                                 param.span,
85                                 "try dereferencing",
86                                 format!("{}{}", derefs, snippet(cx, cur_expr.span, "<param>")),
87                                 Applicability::MachineApplicable,
88                             );
89                         }
90                     },
91                 )
92             }
93         }
94     }
95 }