]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/await_holding_invalid.rs
Auto merge of #6814 - hyd-dev:issue-6486, r=flip1995
[rust.git] / clippy_lints / src / await_holding_invalid.rs
1 use crate::utils::{match_def_path, paths, span_lint_and_note};
2 use rustc_hir::def_id::DefId;
3 use rustc_hir::{AsyncGeneratorKind, Body, BodyId, GeneratorKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_middle::ty::GeneratorInteriorTypeCause;
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::Span;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for calls to await while holding a
11     /// non-async-aware MutexGuard.
12     ///
13     /// **Why is this bad?** The Mutex types found in std::sync and parking_lot
14     /// are not designed to operate in an async context across await points.
15     ///
16     /// There are two potential solutions. One is to use an asynx-aware Mutex
17     /// type. Many asynchronous foundation crates provide such a Mutex type. The
18     /// other solution is to ensure the mutex is unlocked before calling await,
19     /// either by introducing a scope or an explicit call to Drop::drop.
20     ///
21     /// **Known problems:** Will report false positive for explicitly dropped guards ([#6446](https://github.com/rust-lang/rust-clippy/issues/6446)).
22     ///
23     /// **Example:**
24     ///
25     /// ```rust,ignore
26     /// use std::sync::Mutex;
27     ///
28     /// async fn foo(x: &Mutex<u32>) {
29     ///   let guard = x.lock().unwrap();
30     ///   *guard += 1;
31     ///   bar.await;
32     /// }
33     /// ```
34     ///
35     /// Use instead:
36     /// ```rust,ignore
37     /// use std::sync::Mutex;
38     ///
39     /// async fn foo(x: &Mutex<u32>) {
40     ///   {
41     ///     let guard = x.lock().unwrap();
42     ///     *guard += 1;
43     ///   }
44     ///   bar.await;
45     /// }
46     /// ```
47     pub AWAIT_HOLDING_LOCK,
48     pedantic,
49     "Inside an async function, holding a MutexGuard while calling await"
50 }
51
52 declare_clippy_lint! {
53     /// **What it does:** Checks for calls to await while holding a
54     /// `RefCell` `Ref` or `RefMut`.
55     ///
56     /// **Why is this bad?** `RefCell` refs only check for exclusive mutable access
57     /// at runtime. Holding onto a `RefCell` ref across an `await` suspension point
58     /// risks panics from a mutable ref shared while other refs are outstanding.
59     ///
60     /// **Known problems:** Will report false positive for explicitly dropped refs ([#6353](https://github.com/rust-lang/rust-clippy/issues/6353)).
61     ///
62     /// **Example:**
63     ///
64     /// ```rust,ignore
65     /// use std::cell::RefCell;
66     ///
67     /// async fn foo(x: &RefCell<u32>) {
68     ///   let mut y = x.borrow_mut();
69     ///   *y += 1;
70     ///   bar.await;
71     /// }
72     /// ```
73     ///
74     /// Use instead:
75     /// ```rust,ignore
76     /// use std::cell::RefCell;
77     ///
78     /// async fn foo(x: &RefCell<u32>) {
79     ///   {
80     ///      let mut y = x.borrow_mut();
81     ///      *y += 1;
82     ///   }
83     ///   bar.await;
84     /// }
85     /// ```
86     pub AWAIT_HOLDING_REFCELL_REF,
87     pedantic,
88     "Inside an async function, holding a RefCell ref while calling await"
89 }
90
91 declare_lint_pass!(AwaitHolding => [AWAIT_HOLDING_LOCK, AWAIT_HOLDING_REFCELL_REF]);
92
93 impl LateLintPass<'_> for AwaitHolding {
94     fn check_body(&mut self, cx: &LateContext<'_>, body: &'_ Body<'_>) {
95         use AsyncGeneratorKind::{Block, Closure, Fn};
96         if let Some(GeneratorKind::Async(Block | Closure | Fn)) = body.generator_kind {
97             let body_id = BodyId {
98                 hir_id: body.value.hir_id,
99             };
100             let typeck_results = cx.tcx.typeck_body(body_id);
101             check_interior_types(
102                 cx,
103                 &typeck_results.generator_interior_types.as_ref().skip_binder(),
104                 body.value.span,
105             );
106         }
107     }
108 }
109
110 fn check_interior_types(cx: &LateContext<'_>, ty_causes: &[GeneratorInteriorTypeCause<'_>], span: Span) {
111     for ty_cause in ty_causes {
112         if let rustc_middle::ty::Adt(adt, _) = ty_cause.ty.kind() {
113             if is_mutex_guard(cx, adt.did) {
114                 span_lint_and_note(
115                     cx,
116                     AWAIT_HOLDING_LOCK,
117                     ty_cause.span,
118                     "this MutexGuard is held across an 'await' point. Consider using an async-aware Mutex type or ensuring the MutexGuard is dropped before calling await",
119                     ty_cause.scope_span.or(Some(span)),
120                     "these are all the await points this lock is held through",
121                 );
122             }
123             if is_refcell_ref(cx, adt.did) {
124                 span_lint_and_note(
125                     cx,
126                     AWAIT_HOLDING_REFCELL_REF,
127                     ty_cause.span,
128                     "this RefCell Ref is held across an 'await' point. Consider ensuring the Ref is dropped before calling await",
129                     ty_cause.scope_span.or(Some(span)),
130                     "these are all the await points this ref is held through",
131                 );
132             }
133         }
134     }
135 }
136
137 fn is_mutex_guard(cx: &LateContext<'_>, def_id: DefId) -> bool {
138     match_def_path(cx, def_id, &paths::MUTEX_GUARD)
139         || match_def_path(cx, def_id, &paths::RWLOCK_READ_GUARD)
140         || match_def_path(cx, def_id, &paths::RWLOCK_WRITE_GUARD)
141         || match_def_path(cx, def_id, &paths::PARKING_LOT_MUTEX_GUARD)
142         || match_def_path(cx, def_id, &paths::PARKING_LOT_RWLOCK_READ_GUARD)
143         || match_def_path(cx, def_id, &paths::PARKING_LOT_RWLOCK_WRITE_GUARD)
144 }
145
146 fn is_refcell_ref(cx: &LateContext<'_>, def_id: DefId) -> bool {
147     match_def_path(cx, def_id, &paths::REFCELL_REF) || match_def_path(cx, def_id, &paths::REFCELL_REFMUT)
148 }