From 8f22bc738a3e4179658c3146e735146673270a45 Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa Date: Sat, 29 Jun 2024 12:53:50 +0900 Subject: [PATCH] fix: support FunctionExpression --- oxc-rsc/src/hoist.rs | 31 ++++++++++++++++---- oxc-rsc/tests/hoist/function-expression.snap | 8 ++--- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/oxc-rsc/src/hoist.rs b/oxc-rsc/src/hoist.rs index 3fc6edb2..8b2e9ad9 100644 --- a/oxc-rsc/src/hoist.rs +++ b/oxc-rsc/src/hoist.rs @@ -179,16 +179,12 @@ fn ast_hoist_declaration<'a>( } impl<'a> Traverse<'a> for HoistTransformer<'a> { - // Expression::ArrowFunctionExpression fn exit_expression( &mut self, expr: &mut Expression<'a>, ctx: &mut oxc_traverse::TraverseCtx<'a>, ) { match expr { - Expression::FunctionExpression(_node) => { - // TODO - } Expression::ArrowFunctionExpression(node) => { if has_directive(&node.body, &self.directive) { // replace function definition with action register and bind @@ -217,11 +213,36 @@ impl<'a> Traverse<'a> for HoistTransformer<'a> { *expr = new_expr; } } + Expression::FunctionExpression(node) => { + if let Some(body) = &node.body { + if has_directive(&body, &self.directive) { + let new_name = format!("$$hoist_{}", self.hoisted_functions.len()); + let bind_vars = get_bind_vars(ctx, node.span); + let new_expr = ast_register_bind_expression( + ctx, + &self.id, + &self.runtime, + &new_name, + &bind_vars, + ); + + self.hoisted_functions.push(ast_hoist_declaration( + ctx, + node.span, + &new_name, + &node.params, + node.body.as_ref().unwrap(), + &bind_vars, + )); + + *expr = new_expr; + } + } + } _ => {} } } - // Statement::FunctionDeclaration fn exit_statement( &mut self, stmt: &mut Statement<'a>, diff --git a/oxc-rsc/tests/hoist/function-expression.snap b/oxc-rsc/tests/hoist/function-expression.snap index a628d3e3..9d56aaa6 100644 --- a/oxc-rsc/tests/hoist/function-expression.snap +++ b/oxc-rsc/tests/hoist/function-expression.snap @@ -6,9 +6,9 @@ let count = 0; export function Counter() { return { type: 'form', - action: function(formData) { - 'use server'; - count += Number(formData.get('name')); - } + action: $$register($$hoist_0, '', '$$hoist_0') }; } +export async function $$hoist_0(formData) { + count += Number(formData.get('name')); +}