]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs
Rollup merge of #90741 - mbartlett21:patch-4, r=dtolnay
[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
13     /// 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?
17     /// In release builds `debug_assert!` macros are optimized out by the
18     /// compiler.
19     /// Therefore mutating something in a `debug_assert!` macro results in different behaviour
20     /// between a release and debug build.
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     #[clippy::version = "1.40.0"]
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<'tcx> LateLintPass<'tcx> for DebugAssertWithMutCall {
40     fn check_expr(&mut self, cx: &LateContext<'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(macro_args) = higher::extract_assert_macro_args(e) {
44                     for arg in macro_args {
45                         let mut visitor = MutArgVisitor::new(cx);
46                         visitor.visit_expr(arg);
47                         if let Some(span) = visitor.expr_span() {
48                             span_lint(
49                                 cx,
50                                 DEBUG_ASSERT_WITH_MUT_CALL,
51                                 span,
52                                 &format!("do not call a function with mutable arguments inside of `{}!`", dmn),
53                             );
54                         }
55                     }
56                 }
57             }
58         }
59     }
60 }
61
62 struct MutArgVisitor<'a, 'tcx> {
63     cx: &'a LateContext<'tcx>,
64     expr_span: Option<Span>,
65     found: bool,
66 }
67
68 impl<'a, 'tcx> MutArgVisitor<'a, 'tcx> {
69     fn new(cx: &'a LateContext<'tcx>) -> Self {
70         Self {
71             cx,
72             expr_span: None,
73             found: false,
74         }
75     }
76
77     fn expr_span(&self) -> Option<Span> {
78         if self.found { self.expr_span } else { None }
79     }
80 }
81
82 impl<'a, 'tcx> Visitor<'tcx> for MutArgVisitor<'a, 'tcx> {
83     type Map = Map<'tcx>;
84
85     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
86         match expr.kind {
87             ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) => {
88                 self.found = true;
89                 return;
90             },
91             ExprKind::If(..) => {
92                 self.found = true;
93                 return;
94             },
95             ExprKind::Path(_) => {
96                 if let Some(adj) = self.cx.typeck_results().adjustments().get(expr.hir_id) {
97                     if adj
98                         .iter()
99                         .any(|a| matches!(a.target.kind(), ty::Ref(_, _, Mutability::Mut)))
100                     {
101                         self.found = true;
102                         return;
103                     }
104                 }
105             },
106             // Don't check await desugars
107             ExprKind::Match(_, _, MatchSource::AwaitDesugar) => return,
108             _ if !self.found => self.expr_span = Some(expr.span),
109             _ => return,
110         }
111         walk_expr(self, expr);
112     }
113
114     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
115         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
116     }
117 }