[patch] Compile hooks with any number of args in infer mode
Mofei Zhang committed
Dec 7, 2023 at 16:14 UTC
9e267714dbcd410aecd7f188dd1051717bb9fe25
5 files changed
+71
-4
compiler/packages/babel-plugin-react-forget/src/Entrypoint/Program.ts
+5
-4
@@ -489,10 +489,7 @@ function isComponentOrHookLike(
489
): boolean {
490
const functionName = getFunctionName(node);
491
// Check if the name is component or hook like:
492
- if (
493
- functionName !== null &&
494
- (isComponentName(functionName) || isHook(functionName))
495
- ) {
492
+ if (functionName !== null && isComponentName(functionName)) {
493
return (
494
// As an added check we also look for hook invocations or JSX
495
callsHooksOrCreatesJsx(node) &&
@@ -503,7 +500,11 @@ function isComponentOrHookLike(
500
*/
501
node.get("params").length <= 1
502
);
503
+ } else if (functionName !== null && isHook(functionName)) {
504
+ // Hooks have hook invocations or JSX, but can take any # of arguments
505
+ return callsHooksOrCreatesJsx(node);
506
}
507
+
508
/*
509
* Otherwise for function or arrow function expressions, check if they
510
* appear as the argument to React.forwardRef() or React.memo():
compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/infer-compile-hooks-with-multiple-params.expect.md
new
+52
@@ -0,0 +1,52 @@
1
+
2
+## Input
3
+
4
+```javascript
5
+// @compilationMode(infer)
6
+import { useNoAlias } from "shared-runtime";
7
+
8
+// This should be compiled by Forget
9
+function useFoo(value1, value2) {
10
+ return {
11
+ value: useNoAlias(value1 + value2),
12
+ };
13
+}
14
+
15
+export const FIXTURE_ENTRYPOINT = {
16
+ fn: useFoo,
17
+ params: [1, 2],
18
+};
19
+
20
+```
21
+
22
+## Code
23
+
24
+```javascript
25
+import { unstable_useMemoCache as useMemoCache } from "react"; // @compilationMode(infer)
26
+import { useNoAlias } from "shared-runtime";
27
+
28
+// This should be compiled by Forget
29
+function useFoo(value1, value2) {
30
+ const $ = useMemoCache(2);
31
+
32
+ const t0 = useNoAlias(value1 + value2);
33
+ let t1;
34
+ if ($[0] !== t0) {
35
+ t1 = { value: t0 };
36
+ $[0] = t0;
37
+ $[1] = t1;
38
+ } else {
39
+ t1 = $[1];
40
+ }
41
+ return t1;
42
+}
43
+
44
+export const FIXTURE_ENTRYPOINT = {
45
+ fn: useFoo,
46
+ params: [1, 2],
47
+};
48
+
49
+```
50
+
51
+### Eval output
52
+(kind: ok) {"value":{}}
\ No newline at end of file
compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/infer-compile-hooks-with-multiple-params.js
new
+14
@@ -0,0 +1,14 @@
1
+// @compilationMode(infer)
2
+import { useNoAlias } from "shared-runtime";
3
+
4
+// This should be compiled by Forget
5
+function useFoo(value1, value2) {
6
+ return {
7
+ value: useNoAlias(value1 + value2),
8
+ };
9
+}
10
+
11
+export const FIXTURE_ENTRYPOINT = {
12
+ fn: useFoo,
13
+ params: [1, 2],
14
+};