forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathastUtils.js
More file actions
369 lines (331 loc) · 12.2 KB
/
astUtils.js
File metadata and controls
369 lines (331 loc) · 12.2 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import traverse, {NodePath, Node} from '@babel/traverse';
import {File} from '@babel/types';
import type {HooksNode} from 'react-debug-tools/src/ReactDebugHooks';
export type SourceConsumer = any;
export type SourceFileASTWithHookDetails = {
sourceFileAST: File,
line: number,
source: string,
};
const AST_NODE_TYPES = Object.freeze({
CALL_EXPRESSION: 'CallExpression',
MEMBER_EXPRESSION: 'MemberExpression',
ARRAY_PATTERN: 'ArrayPattern',
IDENTIFIER: 'Identifier',
NUMERIC_LITERAL: 'NumericLiteral',
});
// Check if line number obtained from source map and the line number in hook node match
function checkNodeLocation(
path: NodePath,
line: number,
column: number,
): boolean {
const {start, end} = path.node.loc;
if (line < start.line || line > end.line) {
return false;
}
if (
(line === start.line && column < start.column) ||
(line === end.line && column > end.column)
) {
return false;
}
return true;
}
// Checks whether hookNode is a member of targetHookNode
function filterMemberNodesOfTargetHook(
targetHookNode: NodePath,
hookNode: NodePath,
): boolean {
const targetHookName = targetHookNode.node.id.name;
return (
targetHookName ===
(hookNode.node.init.object && hookNode.node.init.object.name) ||
targetHookName === hookNode.node.init.name
);
}
// Checks whether hook is the first member node of a state variable declaration node
function filterMemberWithHookVariableName(hook: NodePath): boolean {
return (
hook.node.init.property.type === AST_NODE_TYPES.NUMERIC_LITERAL &&
hook.node.init.property.value === 0
);
}
// Returns all AST Nodes associated with 'potentialReactHookASTNode'
function getFilteredHookASTNodes(
potentialReactHookASTNode: NodePath,
potentialHooksFound: Array<NodePath>,
source: string,
): Array<NodePath> {
let nodesAssociatedWithReactHookASTNode: NodePath[] = [];
if (nodeContainsHookVariableName(potentialReactHookASTNode)) {
// made custom hooks to enter this, always
// Case 1.
// Directly usable Node -> const ref = useRef(null);
// -> const [tick, setTick] = useState(1);
// Case 2.
// Custom Hooks -> const someVariable = useSomeCustomHook();
// -> const [someVariable, someFunction] = useAnotherCustomHook();
nodesAssociatedWithReactHookASTNode.unshift(potentialReactHookASTNode);
} else {
// Case 3.
// Indirectly usable Node -> const tickState = useState(1);
// [tick, setTick] = tickState;
// -> const tickState = useState(1);
// const tick = tickState[0];
// const setTick = tickState[1];
nodesAssociatedWithReactHookASTNode = potentialHooksFound.filter(hookNode =>
filterMemberNodesOfTargetHook(potentialReactHookASTNode, hookNode),
);
}
return nodesAssociatedWithReactHookASTNode;
}
// Returns Hook name
export function getHookName(
hook: HooksNode,
originalSourceAST: mixed,
originalSourceCode: string,
originalSourceLineNumber: number,
originalSourceColumnNumber: number,
): string | null {
const hooksFromAST = getPotentialHookDeclarationsFromAST(originalSourceAST);
const potentialReactHookASTNode = hooksFromAST.find(node => {
const nodeLocationCheck = checkNodeLocation(
node,
originalSourceLineNumber,
originalSourceColumnNumber,
);
const hookDeclaractionCheck = isConfirmedHookDeclaration(node);
return nodeLocationCheck && hookDeclaractionCheck;
});
if (!potentialReactHookASTNode) {
return null;
}
// nodesAssociatedWithReactHookASTNode could directly be used to obtain the hook variable name
// depending on the type of potentialReactHookASTNode
try {
const nodesAssociatedWithReactHookASTNode = getFilteredHookASTNodes(
potentialReactHookASTNode,
hooksFromAST,
originalSourceCode,
);
return getHookNameFromNode(
hook,
nodesAssociatedWithReactHookASTNode,
potentialReactHookASTNode,
);
} catch (error) {
console.error(error);
return null;
}
}
function getHookNameFromNode(
originalHook: HooksNode,
nodesAssociatedWithReactHookASTNode: NodePath[],
potentialReactHookASTNode: NodePath,
): string | null {
let hookVariableName: string | null;
const isCustomHook = originalHook.id === null;
switch (nodesAssociatedWithReactHookASTNode.length) {
case 1:
// CASE 1A (nodesAssociatedWithReactHookASTNode[0] !== potentialReactHookASTNode):
// const flagState = useState(true); -> later referenced as
// const [flag, setFlag] = flagState;
//
// CASE 1B (nodesAssociatedWithReactHookASTNode[0] === potentialReactHookASTNode):
// const [flag, setFlag] = useState(true); -> we have access to the hook variable straight away
//
// CASE 1C (isCustomHook && nodesAssociatedWithReactHookASTNode[0] === potentialReactHookASTNode):
// const someVariable = useSomeCustomHook(); -> we have access to hook variable straight away
// const [someVariable, someFunction] = useAnotherCustomHook(); -> we ignore variable names in this case
// as it is unclear what variable name to show
if (
isCustomHook &&
nodesAssociatedWithReactHookASTNode[0] === potentialReactHookASTNode
) {
hookVariableName = getHookVariableName(
potentialReactHookASTNode,
isCustomHook,
);
break;
}
hookVariableName = getHookVariableName(
nodesAssociatedWithReactHookASTNode[0],
);
break;
case 2:
// const flagState = useState(true); -> later referenced as
// const flag = flagState[0];
// const setFlag = flagState[1];
nodesAssociatedWithReactHookASTNode = nodesAssociatedWithReactHookASTNode.filter(
hookPath => filterMemberWithHookVariableName(hookPath),
);
if (nodesAssociatedWithReactHookASTNode.length !== 1) {
// Something went wrong, only a single desirable hook should remain here
throw new Error("Couldn't isolate AST Node containing hook variable.");
}
hookVariableName = getHookVariableName(
nodesAssociatedWithReactHookASTNode[0],
);
break;
default:
// Case 0:
// const flagState = useState(true); -> which is not accessed anywhere
//
// Case > 2 (fallback):
// const someState = React.useState(() => 0)
//
// const stateVariable = someState[0]
// const setStateVariable = someState[1]
//
// const [number2, setNumber2] = someState
//
// We assign the state variable for 'someState' to multiple variables,
// and hence cannot isolate a unique variable name. In such cases,
// default to showing 'someState'
hookVariableName = getHookVariableName(potentialReactHookASTNode);
break;
}
return hookVariableName;
}
// Extracts the variable name from hook node path
function getHookVariableName(
hook: NodePath,
isCustomHook: boolean = false,
): string | null {
const nodeType = hook.node.id.type;
switch (nodeType) {
case AST_NODE_TYPES.ARRAY_PATTERN:
return !isCustomHook ? hook.node.id.elements[0].name : null;
case AST_NODE_TYPES.IDENTIFIER:
return hook.node.id.name;
default:
throw new Error(`Invalid node type: ${nodeType}`);
}
}
function getPotentialHookDeclarationsFromAST(sourceAST: File): NodePath[] {
const potentialHooksFound: NodePath[] = [];
traverse(sourceAST, {
enter(path) {
if (path.isVariableDeclarator() && isPotentialHookDeclaration(path)) {
potentialHooksFound.push(path);
}
},
});
return potentialHooksFound;
}
// Check if 'path' contains declaration of the form const X = useState(0);
function isConfirmedHookDeclaration(path: NodePath): boolean {
const node = path.node.init;
if (node.type !== AST_NODE_TYPES.CALL_EXPRESSION) {
return false;
}
const callee = node.callee;
return isHook(callee);
}
// We consider hooks to be a hook name identifier or a member expression containing a hook name.
function isHook(node: Node): boolean {
if (node.type === AST_NODE_TYPES.IDENTIFIER) {
return isHookName(node.name);
} else if (
node.type === AST_NODE_TYPES.MEMBER_EXPRESSION &&
!node.computed &&
isHook(node.property)
) {
const obj = node.object;
const isPascalCaseNameSpace = /^[A-Z].*/;
return (
obj.type === AST_NODE_TYPES.IDENTIFIER &&
isPascalCaseNameSpace.test(obj.name)
);
} else {
// TODO Possibly handle inline require statements e.g. require("useStable")(...)
// This does not seem like a high priority, since inline requires are probably
// not common and are also typically in compiled code rather than source code.
return false;
}
}
// Catch all identifiers that begin with "use"
// followed by an uppercase Latin character to exclude identifiers like "user".
// Copied from packages/eslint-plugin-react-hooks/src/RulesOfHooks
function isHookName(name: string): boolean {
return /^use[A-Z0-9].*$/.test(name);
}
// Check if the AST Node COULD be a React Hook
function isPotentialHookDeclaration(path: NodePath): boolean {
// The array potentialHooksFound will contain all potential hook declaration cases we support
const nodePathInit = path.node.init;
if (nodePathInit != null) {
if (nodePathInit.type === AST_NODE_TYPES.CALL_EXPRESSION) {
// CASE: CallExpression
// 1. const [count, setCount] = useState(0); -> destructured pattern
// 2. const [A, setA] = useState(0), const [B, setB] = useState(0); -> multiple inline declarations
// 3. const [
// count,
// setCount
// ] = useState(0); -> multiline hook declaration
// 4. const ref = useRef(null); -> generic hooks
const callee = nodePathInit.callee;
return isHook(callee);
} else if (
nodePathInit.type === AST_NODE_TYPES.MEMBER_EXPRESSION ||
nodePathInit.type === AST_NODE_TYPES.IDENTIFIER
) {
// CASE: MemberExpression
// const countState = React.useState(0);
// const count = countState[0];
// const setCount = countState[1]; -> Accessing members following hook declaration
// CASE: Identifier
// const countState = React.useState(0);
// const [count, setCount] = countState; -> destructuring syntax following hook declaration
return true;
}
}
return false;
}
/// Check whether 'node' is hook decalration of form useState(0); OR React.useState(0);
function isReactFunction(node: Node, functionName: string): boolean {
return (
node.name === functionName ||
(node.type === 'MemberExpression' &&
node.object.name === 'React' &&
node.property.name === functionName)
);
}
// Check if 'path' is either State or Reducer hook
function isStateOrReducerHook(path: NodePath): boolean {
const callee = path.node.init.callee;
return (
isReactFunction(callee, 'useState') || isReactFunction(callee, 'useReducer')
);
}
// Check whether hookNode of a declaration contains obvious variable name
function nodeContainsHookVariableName(hookNode: NodePath): boolean {
// We determine cases where variable names are obvious in declarations. Examples:
// const [tick, setTick] = useState(1); OR const ref = useRef(null);
// Here tick/ref are obvious hook variables in the hook declaration node itself
// 1. True for satisfying above cases
// 2. False for everything else. Examples:
// const countState = React.useState(0);
// const count = countState[0];
// const setCount = countState[1]; -> not obvious, hook variable can't be determined
// from the hook declaration node alone
// 3. For custom hooks we force pass true since we are only concerned with the AST node
// regardless of how it is accessed in source code. (See: getHookVariableName)
const node = hookNode.node.id;
if (
node.type === AST_NODE_TYPES.ARRAY_PATTERN ||
(node.type === AST_NODE_TYPES.IDENTIFIER && !isStateOrReducerHook(hookNode))
) {
return true;
}
return false;
}