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