Skip to content

Commit 5818c42

Browse files
author
Daniel Smith
committed
Add lint for holding RefCell Ref across an await
1 parent 0ab75c3 commit 5818c42

File tree

5 files changed

+237
-0
lines changed

5 files changed

+237
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
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+
/// `RefCell` `Ref` or `RefMut`.
12+
///
13+
/// **Why is this bad?** `RefCell` refs only check for exclusive mutable access
14+
/// at runtime. Holding onto a `RefCell` ref across an `await` suspension point
15+
/// risks panics from a mutable ref shared while other refs are outstanding.
16+
///
17+
/// **Known problems:** None.
18+
///
19+
/// **Example:**
20+
///
21+
/// ```rust,ignore
22+
/// use std::cell::RefCell;
23+
///
24+
/// async fn foo(x: &RefCell<u32>) {
25+
/// let b = x.borrow_mut()();
26+
/// *ref += 1;
27+
/// bar.await;
28+
/// }
29+
/// ```
30+
///
31+
/// Use instead:
32+
/// ```rust,ignore
33+
/// use std::cell::RefCell;
34+
///
35+
/// async fn foo(x: &RefCell<u32>) {
36+
/// {
37+
/// let b = x.borrow_mut();
38+
/// *ref += 1;
39+
/// }
40+
/// bar.await;
41+
/// }
42+
/// ```
43+
pub AWAIT_HOLDING_REFCELL_REF,
44+
pedantic,
45+
"Inside an async function, holding a RefCell ref while calling await"
46+
}
47+
48+
declare_lint_pass!(AwaitHoldingRefCellRef => [AWAIT_HOLDING_REFCELL_REF]);
49+
50+
impl LateLintPass<'_> for AwaitHoldingRefCellRef {
51+
fn check_body(&mut self, cx: &LateContext<'_>, body: &'_ Body<'_>) {
52+
use AsyncGeneratorKind::{Block, Closure, Fn};
53+
if let Some(GeneratorKind::Async(Block | Closure | Fn)) = body.generator_kind {
54+
let body_id = BodyId {
55+
hir_id: body.value.hir_id,
56+
};
57+
let def_id = cx.tcx.hir().body_owner_def_id(body_id);
58+
let typeck_results = cx.tcx.typeck(def_id);
59+
check_interior_types(cx, &typeck_results.generator_interior_types, body.value.span);
60+
}
61+
}
62+
}
63+
64+
fn check_interior_types(cx: &LateContext<'_>, ty_causes: &[GeneratorInteriorTypeCause<'_>], span: Span) {
65+
for ty_cause in ty_causes {
66+
if let rustc_middle::ty::Adt(adt, _) = ty_cause.ty.kind() {
67+
if is_refcell_ref(cx, adt.did) {
68+
span_lint_and_note(
69+
cx,
70+
AWAIT_HOLDING_REFCELL_REF,
71+
ty_cause.span,
72+
"this RefCell Ref is held across an 'await' point. Consider ensuring the Ref is dropped before calling await.",
73+
ty_cause.scope_span.or(Some(span)),
74+
"these are all the await points this ref is held through",
75+
);
76+
}
77+
}
78+
}
79+
}
80+
81+
fn is_refcell_ref(cx: &LateContext<'_>, def_id: DefId) -> bool {
82+
match_def_path(cx, def_id, &paths::REFCELL_REF) || match_def_path(cx, def_id, &paths::REFCELL_REFMUT)
83+
}

clippy_lints/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ mod async_yields_async;
158158
mod atomic_ordering;
159159
mod attrs;
160160
mod await_holding_lock;
161+
mod await_holding_refcell_ref;
161162
mod bit_mask;
162163
mod blacklisted_name;
163164
mod blocks_in_if_conditions;
@@ -497,6 +498,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
497498
&attrs::UNKNOWN_CLIPPY_LINTS,
498499
&attrs::USELESS_ATTRIBUTE,
499500
&await_holding_lock::AWAIT_HOLDING_LOCK,
501+
&await_holding_refcell_ref::AWAIT_HOLDING_REFCELL_REF,
500502
&bit_mask::BAD_BIT_MASK,
501503
&bit_mask::INEFFECTIVE_BIT_MASK,
502504
&bit_mask::VERBOSE_BIT_MASK,
@@ -886,6 +888,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
886888
// end register lints, do not remove this comment, it’s used in `update_lints`
887889

888890
store.register_late_pass(|| box await_holding_lock::AwaitHoldingLock);
891+
store.register_late_pass(|| box await_holding_refcell_ref::AwaitHoldingRefCellRef);
889892
store.register_late_pass(|| box serde_api::SerdeAPI);
890893
store.register_late_pass(|| box utils::internal_lints::CompilerLintFunctions::new());
891894
store.register_late_pass(|| box utils::internal_lints::LintWithoutLintPass::default());
@@ -1157,6 +1160,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
11571160
store.register_group(true, "clippy::pedantic", Some("clippy_pedantic"), vec![
11581161
LintId::of(&attrs::INLINE_ALWAYS),
11591162
LintId::of(&await_holding_lock::AWAIT_HOLDING_LOCK),
1163+
LintId::of(&await_holding_refcell_ref::AWAIT_HOLDING_REFCELL_REF),
11601164
LintId::of(&checked_conversions::CHECKED_CONVERSIONS),
11611165
LintId::of(&copies::MATCH_SAME_ARMS),
11621166
LintId::of(&copies::SAME_FUNCTIONS_IN_IF_CONDITION),

clippy_lints/src/utils/paths.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ pub const RANGE_ARGUMENT_TRAIT: [&str; 3] = ["core", "ops", "RangeBounds"];
9191
pub const RC: [&str; 3] = ["alloc", "rc", "Rc"];
9292
pub const RC_PTR_EQ: [&str; 4] = ["alloc", "rc", "Rc", "ptr_eq"];
9393
pub const RECEIVER: [&str; 4] = ["std", "sync", "mpsc", "Receiver"];
94+
pub const REFCELL_REF: [&str; 3] = ["core", "cell", "Ref"];
95+
pub const REFCELL_REFMUT: [&str; 3] = ["core", "cell", "RefMut"];
9496
pub const REGEX_BUILDER_NEW: [&str; 5] = ["regex", "re_builder", "unicode", "RegexBuilder", "new"];
9597
pub const REGEX_BYTES_BUILDER_NEW: [&str; 5] = ["regex", "re_builder", "bytes", "RegexBuilder", "new"];
9698
pub const REGEX_BYTES_NEW: [&str; 4] = ["regex", "re_bytes", "Regex", "new"];

tests/ui/await_holding_refcell_ref.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// edition:2018
2+
#![warn(clippy::await_holding_refcell_ref)]
3+
4+
use std::cell::RefCell;
5+
6+
async fn bad(x: &RefCell<u32>) -> u32 {
7+
let b = x.borrow();
8+
baz().await
9+
}
10+
11+
async fn bad_mut(x: &RefCell<u32>) -> u32 {
12+
let b = x.borrow_mut();
13+
baz().await
14+
}
15+
16+
async fn good(x: &RefCell<u32>) -> u32 {
17+
{
18+
let b = x.borrow_mut();
19+
let y = *b + 1;
20+
}
21+
baz().await;
22+
let b = x.borrow_mut();
23+
47
24+
}
25+
26+
async fn baz() -> u32 {
27+
42
28+
}
29+
30+
async fn also_bad(x: &RefCell<u32>) -> u32 {
31+
let first = baz().await;
32+
33+
let b = x.borrow_mut();
34+
35+
let second = baz().await;
36+
37+
let third = baz().await;
38+
39+
first + second + third
40+
}
41+
42+
async fn not_good(x: &RefCell<u32>) -> u32 {
43+
let first = baz().await;
44+
45+
let second = {
46+
let b = x.borrow_mut();
47+
baz().await
48+
};
49+
50+
let third = baz().await;
51+
52+
first + second + third
53+
}
54+
55+
#[allow(clippy::manual_async_fn)]
56+
fn block_bad(x: &RefCell<u32>) -> impl std::future::Future<Output = u32> + '_ {
57+
async move {
58+
let b = x.borrow_mut();
59+
baz().await
60+
}
61+
}
62+
63+
fn main() {
64+
let m = RefCell::new(100);
65+
good(&m);
66+
bad(&m);
67+
bad_mut(&m);
68+
also_bad(&m);
69+
not_good(&m);
70+
block_bad(&m);
71+
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
error: this RefCell Ref is held across an 'await' point. Consider ensuring the Ref is dropped before calling await.
2+
--> $DIR/await_holding_refcell_ref.rs:7:9
3+
|
4+
LL | let b = x.borrow();
5+
| ^
6+
|
7+
= note: `-D clippy::await-holding-refcell-ref` implied by `-D warnings`
8+
note: these are all the await points this ref is held through
9+
--> $DIR/await_holding_refcell_ref.rs:7:5
10+
|
11+
LL | / let b = x.borrow();
12+
LL | | baz().await
13+
LL | | }
14+
| |_^
15+
16+
error: this RefCell Ref is held across an 'await' point. Consider ensuring the Ref is dropped before calling await.
17+
--> $DIR/await_holding_refcell_ref.rs:12:9
18+
|
19+
LL | let b = x.borrow_mut();
20+
| ^
21+
|
22+
note: these are all the await points this ref is held through
23+
--> $DIR/await_holding_refcell_ref.rs:12:5
24+
|
25+
LL | / let b = x.borrow_mut();
26+
LL | | baz().await
27+
LL | | }
28+
| |_^
29+
30+
error: this RefCell Ref is held across an 'await' point. Consider ensuring the Ref is dropped before calling await.
31+
--> $DIR/await_holding_refcell_ref.rs:33:9
32+
|
33+
LL | let b = x.borrow_mut();
34+
| ^
35+
|
36+
note: these are all the await points this ref is held through
37+
--> $DIR/await_holding_refcell_ref.rs:33:5
38+
|
39+
LL | / let b = x.borrow_mut();
40+
LL | |
41+
LL | | let second = baz().await;
42+
LL | |
43+
... |
44+
LL | | first + second + third
45+
LL | | }
46+
| |_^
47+
48+
error: this RefCell Ref is held across an 'await' point. Consider ensuring the Ref is dropped before calling await.
49+
--> $DIR/await_holding_refcell_ref.rs:46:13
50+
|
51+
LL | let b = x.borrow_mut();
52+
| ^
53+
|
54+
note: these are all the await points this ref is held through
55+
--> $DIR/await_holding_refcell_ref.rs:46:9
56+
|
57+
LL | / let b = x.borrow_mut();
58+
LL | | baz().await
59+
LL | | };
60+
| |_____^
61+
62+
error: this RefCell Ref is held across an 'await' point. Consider ensuring the Ref is dropped before calling await.
63+
--> $DIR/await_holding_refcell_ref.rs:58:13
64+
|
65+
LL | let b = x.borrow_mut();
66+
| ^
67+
|
68+
note: these are all the await points this ref is held through
69+
--> $DIR/await_holding_refcell_ref.rs:58:9
70+
|
71+
LL | / let b = x.borrow_mut();
72+
LL | | baz().await
73+
LL | | }
74+
| |_____^
75+
76+
error: aborting due to 5 previous errors
77+

0 commit comments

Comments
 (0)