]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs
Auto merge of #85746 - m-ou-se:io-error-other, r=joshtriplett
[rust.git] / src / tools / clippy / clippy_lints / src / mutable_debug_assertion.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::{higher, is_direct_expn_of};
3 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
4 use rustc_hir::{BorrowKind, Expr, ExprKind, MatchSource, Mutability};
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(macro_args) = higher::extract_assert_macro_args(e) {
43                     for arg in macro_args {
44                         let mut visitor = MutArgVisitor::new(cx);
45                         visitor.visit_expr(arg);
46                         if let Some(span) = visitor.expr_span() {
47                             span_lint(
48                                 cx,
49                                 DEBUG_ASSERT_WITH_MUT_CALL,
50                                 span,
51                                 &format!("do not call a function with mutable arguments inside of `{}!`", dmn),
52                             );
53                         }
54                     }
55                 }
56             }
57         }
58     }
59 }
60
61 struct MutArgVisitor<'a, 'tcx> {
62     cx: &'a LateContext<'tcx>,
63     expr_span: Option<Span>,
64     found: bool,
65 }
66
67 impl<'a, 'tcx> MutArgVisitor<'a, 'tcx> {
68     fn new(cx: &'a LateContext<'tcx>) -> Self {
69         Self {
70             cx,
71             expr_span: None,
72             found: false,
73         }
74     }
75
76     fn expr_span(&self) -> Option<Span> {
77         if self.found { self.expr_span } else { None }
78     }
79 }
80
81 impl<'a, 'tcx> Visitor<'tcx> for MutArgVisitor<'a, 'tcx> {
82     type Map = Map<'tcx>;
83
84     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
85         match expr.kind {
86             ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) => {
87                 self.found = true;
88                 return;
89             },
90             ExprKind::If(..) => {
91                 self.found = true;
92                 return;
93             },
94             ExprKind::Path(_) => {
95                 if let Some(adj) = self.cx.typeck_results().adjustments().get(expr.hir_id) {
96                     if adj
97                         .iter()
98                         .any(|a| matches!(a.target.kind(), ty::Ref(_, _, Mutability::Mut)))
99                     {
100                         self.found = true;
101                         return;
102                     }
103                 }
104             },
105             // Don't check await desugars
106             ExprKind::Match(_, _, MatchSource::AwaitDesugar) => return,
107             _ if !self.found => self.expr_span = Some(expr.span),
108             _ => return,
109         }
110         walk_expr(self, expr);
111     }
112
113     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
114         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
115     }
116 }