[Babel] Refactor visitor to separate function
This lets us extend to ArrowFunctionExpression
Sathya Gunasekaran committed
Mar 20, 2023 at 17:42 UTC
93b79e4aa048677094a72d799ef2480761424303
1 file changed
+41
-34
compiler/forget/src/Babel/BabelPlugin.ts
+41
-34
@@ -39,45 +39,52 @@ export default function ReactForgetBabelPlugin(
39
): BabelCore.PluginObj {
40
let hasForgetCompiledCode: boolean = false;
41
42
+ function visitFn(
43
+ fn: BabelCore.NodePath<t.FunctionDeclaration>,
44
+ pass: BabelPluginPass
45
+ ): void {
46
+ if (pass.opts.enableOnlyOnUseForgetDirective) {
47
+ if (!hasUseForgetDirective(fn.node.body.directives)) {
48
+ return;
49
+ }
50
+ }
51
+
52
+ if (fn.scope.getProgramParent() !== fn.scope.parent) {
53
+ return;
54
+ }
55
+
56
+ hasForgetCompiledCode = true;
57
+ const compiled = compile(fn, pass.opts.environment);
58
+
59
+ if (pass.opts.gatingModule) {
60
+ // Rename existing function
61
+ invariant(fn.node.id, "FunctionDeclaration must have a name");
62
+ const original = fn.node.id;
63
+ fn.node.id = addSuffix(fn.node.id, "_uncompiled");
64
+
65
+ // Rename and append compiled function
66
+ invariant(compiled.id, "FunctionDeclaration must produce a name");
67
+ compiled.id = addSuffix(compiled.id, "_forget");
68
+ const compiledFn = fn.insertAfter(compiled)[0];
69
+ compiledFn.skip();
70
+
71
+ // Build and append gating test
72
+ compiledFn.insertAfter(buildGatingTest(fn, compiled.id, original));
73
+ } else {
74
+ fn.replaceWith(compiled);
75
+ }
76
+
77
+ // We are generating a new FunctionDeclaration node, so we must skip over it or this
78
+ // traversal will loop infinitely.
79
+ fn.skip();
80
+ }
81
+
82
const visitor = {
83
FunctionDeclaration(
84
fn: BabelCore.NodePath<t.FunctionDeclaration>,
85
pass: BabelPluginPass
86
): void {
47
- if (pass.opts.enableOnlyOnUseForgetDirective) {
48
- if (!hasUseForgetDirective(fn.node.body.directives)) {
49
- return;
50
- }
51
- }
52
-
53
- if (fn.scope.getProgramParent() !== fn.scope.parent) {
54
- return;
55
- }
56
-
57
- hasForgetCompiledCode = true;
58
- const compiled = compile(fn, pass.opts.environment);
59
-
60
- if (pass.opts.gatingModule) {
61
- // Rename existing function
62
- invariant(fn.node.id, "FunctionDeclaration must have a name");
63
- const original = fn.node.id;
64
- fn.node.id = addSuffix(fn.node.id, "_uncompiled");
65
-
66
- // Rename and append compiled function
67
- invariant(compiled.id, "FunctionDeclaration must produce a name");
68
- compiled.id = addSuffix(compiled.id, "_forget");
69
- const compiledFn = fn.insertAfter(compiled)[0];
70
- compiledFn.skip();
71
-
72
- // Build and append gating test
73
- compiledFn.insertAfter(buildGatingTest(fn, compiled.id, original));
74
- } else {
75
- fn.replaceWith(compiled);
76
- }
77
-
78
- // We are generating a new FunctionDeclaration node, so we must skip over it or this
79
- // traversal will loop infinitely.
80
- fn.skip();
87
+ visitFn(fn, pass);
88
},
89
};
90