This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 657
/
Copy pathhooks.rs
287 lines (258 loc) · 9.18 KB
/
hooks.rs
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
275
276
277
278
279
280
281
282
283
284
285
286
287
use crate::react::{is_react_call_api, ReactLibrary};
use std::collections::{HashMap, HashSet};
use rome_js_semantic::{Capture, Closure, ClosureExtensions, SemanticModel};
use rome_js_syntax::{
binding_ext::AnyJsIdentifierBinding, AnyJsExpression, JsArrayBindingPattern,
JsArrayBindingPatternElementList, JsArrowFunctionExpression, JsCallExpression,
JsFunctionExpression, JsVariableDeclarator, TextRange,
};
use rome_rowan::AstNode;
use serde::{Deserialize, Serialize};
/// Return result of [react_hook_with_dependency].
pub(crate) struct ReactCallWithDependencyResult {
pub(crate) function_name_range: TextRange,
pub(crate) closure_node: Option<AnyJsExpression>,
pub(crate) dependencies_node: Option<AnyJsExpression>,
}
pub enum AnyJsFunctionExpression {
JsArrowFunctionExpression(JsArrowFunctionExpression),
JsFunctionExpression(JsFunctionExpression),
}
impl AnyJsFunctionExpression {
fn closure(&self, model: &SemanticModel) -> Closure {
match self {
Self::JsArrowFunctionExpression(arrow_function) => arrow_function.closure(model),
Self::JsFunctionExpression(function) => function.closure(model),
}
}
}
impl TryFrom<AnyJsExpression> for AnyJsFunctionExpression {
type Error = ();
fn try_from(expression: AnyJsExpression) -> Result<Self, Self::Error> {
match expression {
AnyJsExpression::JsArrowFunctionExpression(arrow_function) => {
Ok(Self::JsArrowFunctionExpression(arrow_function))
}
AnyJsExpression::JsFunctionExpression(function) => {
Ok(Self::JsFunctionExpression(function))
}
_ => Err(()),
}
}
}
impl ReactCallWithDependencyResult {
/// Returns all [Reference] captured by the closure argument of the React hook.
/// See [react_hook_with_dependency].
pub fn all_captures(&self, model: &SemanticModel) -> impl Iterator<Item = Capture> {
self.closure_node
.as_ref()
.and_then(|node| AnyJsFunctionExpression::try_from(node.clone()).ok())
.map(|function_expression| {
let closure = function_expression.closure(model);
let range = *closure.closure_range();
closure
.descendents()
.flat_map(|closure| closure.all_captures())
.filter(move |capture| capture.declaration_range().intersect(range).is_none())
})
.into_iter()
.flatten()
}
/// Returns all dependencies of a React hook.
/// See [react_hook_with_dependency]
pub fn all_dependencies(&self) -> impl Iterator<Item = AnyJsExpression> {
self.dependencies_node
.as_ref()
.and_then(|x| Some(x.as_js_array_expression()?.elements().into_iter()))
.into_iter()
.flatten()
.filter_map(|x| x.ok()?.as_any_js_expression().cloned())
}
}
#[derive(Default, Debug, Copy, Clone, Serialize, Deserialize)]
pub struct ReactHookConfiguration {
pub closure_index: Option<usize>,
pub dependencies_index: Option<usize>,
}
impl From<(usize, usize)> for ReactHookConfiguration {
fn from((closure, dependencies): (usize, usize)) -> Self {
Self {
closure_index: Some(closure),
dependencies_index: Some(dependencies),
}
}
}
pub(crate) fn react_hook_configuration<'a>(
call: &JsCallExpression,
hooks: &'a HashMap<String, ReactHookConfiguration>,
) -> Option<&'a ReactHookConfiguration> {
let name = call
.callee()
.ok()?
.as_js_identifier_expression()?
.name()
.ok()?
.value_token()
.ok()?;
let name = name.text_trimmed();
hooks.get(name)
}
const HOOKS_WITH_DEPS_API: [&str; 6] = [
"useEffect",
"useLayoutEffect",
"useInsertionEffect",
"useCallback",
"useMemo",
"useImperativeHandle",
];
/// Returns the [TextRange] of the hook name; the node of the
/// expression of the argument that correspond to the closure of
/// the hook; and the node of the dependency list of the hook.
///
/// Example:
/// ```js
/// useEffect(() => {}, []);
/// ^^ <- dependencies_node
/// ^^^^^^^^ <- closure_node
/// ^^^^^^^^^ <- function_name_range
/// ```
///
/// This function will use the parameter "hooks" with the configuration
/// of all function that are considered hooks. See [ReactHookConfiguration].
pub(crate) fn react_hook_with_dependency(
call: &JsCallExpression,
hooks: &HashMap<String, ReactHookConfiguration>,
model: &SemanticModel,
) -> Option<ReactCallWithDependencyResult> {
let expression = call.callee().ok()?;
let name = match &expression {
AnyJsExpression::JsIdentifierExpression(identifier) => {
Some(identifier.name().ok()?.value_token().ok()?)
}
AnyJsExpression::JsStaticMemberExpression(member) => {
Some(member.member().ok()?.as_js_name()?.value_token().ok()?)
}
_ => None,
}?;
let function_name_range = name.text_trimmed_range();
let name = name.text_trimmed();
// check if the hooks api is imported from the react library
if HOOKS_WITH_DEPS_API.contains(&name)
&& !is_react_call_api(expression, model, ReactLibrary::React, name)
{
return None;
}
let hook = hooks.get(name)?;
let closure_index = hook.closure_index?;
let dependencies_index = hook.dependencies_index?;
let mut indices = [closure_index, dependencies_index];
indices.sort();
let [closure_node, dependencies_node] = call.get_arguments_by_index(indices);
Some(ReactCallWithDependencyResult {
function_name_range,
closure_node: closure_node.and_then(|x| x.as_any_js_expression().cloned()),
dependencies_node: dependencies_node.and_then(|x| x.as_any_js_expression().cloned()),
})
}
/// Specifies which, if any, of the returns of a React hook are stable.
/// See [is_binding_react_stable].
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct StableReactHookConfiguration {
/// Name of the React hook
hook_name: String,
/// Index of the position of the stable return, [None] if
/// none returns are stable
index: Option<usize>,
}
impl StableReactHookConfiguration {
pub fn new(hook_name: &str, index: Option<usize>) -> Self {
Self {
hook_name: hook_name.into(),
index,
}
}
}
/// Checks if the binding is bound to a stable React hook
/// return value. Stable returns do not need to be specified
/// as dependencies.
///
/// Example:
/// ```js
/// let [name, setName] = useState("");
/// useEffect(() => {
/// // name is NOT stable, so it must be specified as dependency
/// console.log(name);
/// // setName IS stable, so it must not be specified as dependency
/// console.log(setName("a"));
/// }, [name]);
/// ```
pub fn is_binding_react_stable(
binding: &AnyJsIdentifierBinding,
stable_config: &HashSet<StableReactHookConfiguration>,
) -> bool {
fn array_binding_declarator_index(
binding: &AnyJsIdentifierBinding,
) -> Option<(JsVariableDeclarator, Option<usize>)> {
let index = binding.syntax().index() / 2;
let declarator = binding
.parent::<JsArrayBindingPatternElementList>()?
.parent::<JsArrayBindingPattern>()?
.parent::<JsVariableDeclarator>()?;
Some((declarator, Some(index)))
}
fn assignment_declarator(
binding: &AnyJsIdentifierBinding,
) -> Option<(JsVariableDeclarator, Option<usize>)> {
let declarator = binding.parent::<JsVariableDeclarator>()?;
Some((declarator, None))
}
array_binding_declarator_index(binding)
.or_else(|| assignment_declarator(binding))
.and_then(|(declarator, index)| {
let hook_name = declarator
.initializer()?
.expression()
.ok()?
.as_js_call_expression()?
.callee()
.ok()?
.as_js_identifier_expression()?
.name()
.ok()?
.value_token()
.ok()?
.token_text();
let stable = StableReactHookConfiguration {
hook_name: hook_name.to_string(),
index,
};
Some(stable_config.contains(&stable))
})
.unwrap_or(false)
}
#[cfg(test)]
mod test {
use super::*;
use rome_js_parser::JsParserOptions;
use rome_js_syntax::JsFileSource;
#[test]
pub fn ok_react_stable_captures() {
let r = rome_js_parser::parse(
"const ref = useRef();",
JsFileSource::js_module(),
JsParserOptions::default(),
);
let node = r
.syntax()
.descendants()
.filter(|x| x.text_trimmed() == "ref")
.last()
.unwrap();
let set_name = AnyJsIdentifierBinding::cast(node).unwrap();
let config = HashSet::from_iter([
StableReactHookConfiguration::new("useRef", None),
StableReactHookConfiguration::new("useState", Some(1)),
]);
assert!(is_binding_react_stable(&set_name, &config));
}
}