Repository navigation
Expand file tree
/
Copy pathimmediately_bind_scoped.rs
More file actions
274 lines (246 loc) · 9.51 KB
/
Copy pathimmediately_bind_scoped.rs
File metadata and controls
274 lines (246 loc) · 9.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
use std::{fmt::Display, ops::ControlFlow};
use crate::{is_scoped_ty, method_call};
use clippy_utils::{
diagnostics::span_lint_and_help,
get_enclosing_block, get_parent_expr,
paths::{PathNS, lookup_path_str},
res::MaybeResPath,
ty::implements_trait,
visitors::for_each_expr,
};
use rustc_hir::{Expr, ExprKind, HirId, Node, PatKind, StmtKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::Ty;
dylint_linting::declare_late_lint! {
/// ### What it does
///
/// Makes sure that the user immediately binds `Scoped<Value>::get` and
/// `Scoped<Value>::take` results.
///
/// ### Why is this bad?
///
/// To avoid odd bugs with the garbage collector when dealing with scoped
/// values, it is important that `Scoped<Value>::get` and
/// `Scoped<Value>::take` results are immediately bound.
///
/// ### Example
///
/// ```
/// let a = scoped_a.get(agent);
/// ```
///
/// Use instead:
///
/// ```
/// let a = scoped_a.get(agent).bind(gc.nogc());
/// ```
///
/// Which ensures that no odd bugs occur.
///
/// ### Exception: If the result is immediately used without assigning to a
/// variable, binding can be skipped.
///
/// ```
/// scoped_a.get(agent).internal_delete(agent, scoped_b.get(agent), gc.reborrow());
/// ```
///
/// Here it is perfectly okay to skip the binding for both `scoped_a` and
/// `scoped_b` as the borrow checker would force you to again unbind both
/// `Value`s immediately.
pub IMMEDIATELY_BIND_SCOPED,
Deny,
"the result of `Scoped<Value>::get` or `Scoped<Value>::take` should be immediately bound"
}
impl<'tcx> LateLintPass<'tcx> for ImmediatelyBindScoped {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
// First we check if we have found a `Scoped<Value>::get` or `Scoped<Value>::take` call
if let Some(scoped_method) = is_scoped_get_or_take_method_call(cx, expr) {
// Which is followed by a trait method call to `bind` in which case
// it is all done properly and we can exit out of the lint.
if let Some(parent) = get_parent_expr(cx, expr)
&& is_bindable_bind_method_call(cx, parent)
{
return;
}
// Check if the unbound value is used in an argument position of a
// method or function call where binding can be safely skipped.
if is_in_argument_position(cx, expr) {
return;
}
// If the expression is assigned to a local variable, we need to
// check that it's next use is binding or as a function argument.
if let Some(local_hir_id) = get_assigned_local(cx, expr)
&& let Some(enclosing_block) = get_enclosing_block(cx, expr.hir_id)
{
let mut found_valid_next_use = false;
// Look for the next use of this local after the current expression.
// We need to traverse the statements in the block to find proper usage
for stmt in enclosing_block
.stmts
.iter()
.skip_while(|s| s.span.lo() < expr.span.hi())
{
// Extract relevant expressions from the statement and check
// it for a use valid of the local variable.
let Some(stmt_expr) = (match &stmt.kind {
StmtKind::Expr(expr) | StmtKind::Semi(expr) => Some(*expr),
StmtKind::Let(local) => local.init,
_ => None,
}) else {
continue;
};
// Check each expression in the current statement for use
// of the value, breaking when found and optionally marking
// it as valid.
if for_each_expr(cx, stmt_expr, |expr_in_stmt| {
if expr_in_stmt.res_local_id() == Some(local_hir_id) {
if is_valid_use_of_unbound_value(cx, expr_in_stmt, local_hir_id) {
found_valid_next_use = true;
}
return ControlFlow::Break(true);
}
ControlFlow::Continue(())
})
.unwrap_or(false)
{
break;
}
}
if !found_valid_next_use {
span_lint_and_help(
cx,
IMMEDIATELY_BIND_SCOPED,
expr.span,
format!(
"the result of `Scoped<Value>::{}` should be immediately bound",
scoped_method
),
None,
"immediately bind the value",
);
}
}
}
}
}
/// Check if an expression is assigned to a local variable and return the local's HirId
fn get_assigned_local(cx: &LateContext<'_>, expr: &Expr) -> Option<HirId> {
let parent_node = cx.tcx.parent_hir_id(expr.hir_id);
if let Node::LetStmt(local) = cx.tcx.hir_node(parent_node)
&& let Some(init) = local.init
&& init.hir_id == expr.hir_id
&& let PatKind::Binding(_, hir_id, _, _) = local.pat.kind
{
Some(hir_id)
} else {
None
}
}
/// Check if a use of an unbound value is valid, this is either by being a
/// binding or function argument, or in the return position of a function.
fn is_valid_use_of_unbound_value(cx: &LateContext<'_>, expr: &Expr, hir_id: HirId) -> bool {
// Check if we're in a method call and if so, check if it's a bind call
if let Some(parent) = get_parent_expr(cx, expr)
&& is_bindable_bind_method_call(cx, parent)
{
return true;
}
// If this is a method call to bind() on our local, it's valid
if is_bindable_bind_method_call(cx, expr) {
return true;
}
// If this is the local being used as a function argument, it's valid
if expr.res_local_id() == Some(hir_id) && is_in_argument_position(cx, expr) {
return true;
}
// If this is the self value of a method call, it's valid
if expr.res_local_id() == Some(hir_id) && is_in_self_position(cx, expr) {
return true;
}
false
}
fn is_in_self_position(cx: &LateContext<'_>, expr: &Expr) -> bool {
let mut current_expr = expr;
// Walk up the parent chain to see if we're in a method call
while let Some(parent) = get_parent_expr(cx, current_expr) {
// If we find a method call where our expression is in the receiver position
if let ExprKind::MethodCall(_, receiver, _, _) = parent.kind
&& receiver.hir_id == current_expr.hir_id
{
return true;
}
// Else continue walking up for other expression types
current_expr = parent;
}
false
}
/// Check if an expression is in an argument position where binding can be skipped
fn is_in_argument_position(cx: &LateContext<'_>, expr: &Expr) -> bool {
let mut current_expr = expr;
// Walk up the parent chain to see if we're in a function call argument
while let Some(parent) = get_parent_expr(cx, current_expr) {
match parent.kind {
// If we find a method call where our expression is an argument (not receiver)
ExprKind::MethodCall(_, receiver, args, _) => {
if receiver.hir_id != current_expr.hir_id
&& args.iter().any(|arg| arg.hir_id == current_expr.hir_id)
{
return true;
}
}
// If we find a function call where our expression is an argument
ExprKind::Call(_, args) => {
if args.iter().any(|arg| arg.hir_id == current_expr.hir_id) {
return true;
}
}
// Continue walking up for other expression types
_ => {}
}
current_expr = parent;
}
false
}
enum ScopedMethod {
Get,
Take,
}
impl Display for ScopedMethod {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ScopedMethod::Get => write!(f, "get"),
ScopedMethod::Take => write!(f, "take"),
}
}
}
fn is_scoped_get_or_take_method_call(cx: &LateContext<'_>, expr: &Expr) -> Option<ScopedMethod> {
if let Some((method, recv, _, _, _)) = method_call(expr)
&& let typeck_results = cx.typeck_results()
&& let recv_ty = typeck_results.expr_ty(recv)
&& is_scoped_ty(cx, &recv_ty)
{
match method {
"get" => Some(ScopedMethod::Get),
"take" => Some(ScopedMethod::Take),
_ => None,
}
} else {
None
}
}
fn is_bindable_bind_method_call(cx: &LateContext<'_>, expr: &Expr) -> bool {
if let Some((method, _, _, _, _)) = method_call(expr)
&& method == "bind"
&& let expr_ty = cx.typeck_results().expr_ty(expr)
&& implements_bindable_trait(cx, &expr_ty)
{
true
} else {
false
}
}
fn implements_bindable_trait<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'tcx>) -> bool {
lookup_path_str(cx.tcx, PathNS::Type, "nova_vm::engine::Bindable")
.first()
.is_some_and(|&trait_def_id| implements_trait(cx, *ty, trait_def_id, &[]))
}