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