]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mutable_debug_assertion.rs
Add lint for debug_assert_with_mut_call
[rust.git] / clippy_lints / src / mutable_debug_assertion.rs
1 use crate::utils::{is_direct_expn_of, span_lint};
2 use if_chain::if_chain;
3 use matches::matches;
4 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
5 use rustc::hir::{Expr, ExprKind, Mutability, StmtKind, UnOp};
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_lint_pass, declare_tool_lint, ty};
8 use syntax_pos::Span;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for function/method calls with a mutable
12     /// parameter in `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!` macros.
13     ///
14     /// **Why is this bad?** In release builds `debug_assert!` macros are optimized out by the
15     /// compiler.
16     /// Therefore mutating something in a `debug_assert!` macro results in different behaviour
17     /// between a release and debug build.
18     ///
19     /// **Known problems:** None
20     ///
21     /// **Example:**
22     /// ```rust,ignore
23     /// debug_assert_eq!(vec![3].pop(), Some(3));
24     /// // or
25     /// fn take_a_mut_parameter(_: &mut u32) -> bool { unimplemented!() }
26     /// debug_assert!(take_a_mut_parameter(&mut 5));
27     /// ```
28     pub DEBUG_ASSERT_WITH_MUT_CALL,
29     correctness,
30     "mutable arguments in `debug_assert{,_ne,_eq}!`"
31 }
32
33 declare_lint_pass!(DebugAssertWithMutCall => [DEBUG_ASSERT_WITH_MUT_CALL]);
34
35 const DEBUG_MACRO_NAMES: [&str; 3] = ["debug_assert", "debug_assert_eq", "debug_assert_ne"];
36
37 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DebugAssertWithMutCall {
38     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
39         for dmn in &DEBUG_MACRO_NAMES {
40             if is_direct_expn_of(e.span, dmn).is_some() {
41                 if let Some(span) = extract_call(cx, e) {
42                     span_lint(
43                         cx,
44                         DEBUG_ASSERT_WITH_MUT_CALL,
45                         span,
46                         &format!("do not call a function with mutable arguments inside of `{}!`", dmn),
47                     );
48                 }
49             }
50         }
51     }
52 }
53
54 //HACK(hellow554): remove this when #4694 is implemented
55 #[allow(clippy::cognitive_complexity)]
56 fn extract_call<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, e: &'tcx Expr) -> Option<Span> {
57     if_chain! {
58         if let ExprKind::Block(ref block, _) = e.kind;
59         if block.stmts.len() == 1;
60         if let StmtKind::Semi(ref matchexpr) = block.stmts[0].kind;
61         then {
62             if_chain! {
63                 if let ExprKind::Match(ref ifclause, _, _) = matchexpr.kind;
64                 if let ExprKind::DropTemps(ref droptmp) = ifclause.kind;
65                 if let ExprKind::Unary(UnOp::UnNot, ref condition) = droptmp.kind;
66                 then {
67                     // debug_assert
68                     let mut visitor = MutArgVisitor::new(cx);
69                     visitor.visit_expr(condition);
70                     return visitor.expr_span();
71                 } else {
72                     // debug_assert_{eq,ne}
73                     if_chain! {
74                         if let ExprKind::Block(ref matchblock, _) = matchexpr.kind;
75                         if let Some(ref matchheader) = matchblock.expr;
76                         if let ExprKind::Match(ref headerexpr, _, _) = matchheader.kind;
77                         if let ExprKind::Tup(ref conditions) = headerexpr.kind;
78                         if conditions.len() == 2;
79                         then {
80                             if let ExprKind::AddrOf(_, ref lhs) = conditions[0].kind {
81                                 let mut visitor = MutArgVisitor::new(cx);
82                                 visitor.visit_expr(lhs);
83                                 if let Some(span) = visitor.expr_span() {
84                                     return Some(span);
85                                 }
86                             }
87                             if let ExprKind::AddrOf(_, ref rhs) = conditions[1].kind {
88                                 let mut visitor = MutArgVisitor::new(cx);
89                                 visitor.visit_expr(rhs);
90                                 if let Some(span) = visitor.expr_span() {
91                                     return Some(span);
92                                 }
93                             }
94                         }
95                     }
96                 }
97             }
98         }
99     }
100
101     None
102 }
103
104 struct MutArgVisitor<'a, 'tcx> {
105     cx: &'a LateContext<'a, 'tcx>,
106     expr_span: Option<Span>,
107     found: bool,
108 }
109
110 impl<'a, 'tcx> MutArgVisitor<'a, 'tcx> {
111     fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
112         Self {
113             cx,
114             expr_span: None,
115             found: false,
116         }
117     }
118
119     fn expr_span(&self) -> Option<Span> {
120         if self.found {
121             self.expr_span
122         } else {
123             None
124         }
125     }
126 }
127
128 impl<'a, 'tcx> Visitor<'tcx> for MutArgVisitor<'a, 'tcx> {
129     fn visit_expr(&mut self, expr: &'tcx Expr) {
130         match expr.kind {
131             ExprKind::AddrOf(Mutability::MutMutable, _) => {
132                 self.found = true;
133                 return;
134             },
135             ExprKind::Path(_) => {
136                 if let Some(adj) = self.cx.tables.adjustments().get(expr.hir_id) {
137                     if adj
138                         .iter()
139                         .any(|a| matches!(a.target.kind, ty::Ref(_, _, Mutability::MutMutable)))
140                     {
141                         self.found = true;
142                         return;
143                     }
144                 }
145             },
146             _ if !self.found => self.expr_span = Some(expr.span),
147             _ => return,
148         }
149         walk_expr(self, expr)
150     }
151
152     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
153         NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
154     }
155 }