Unverified Commit dc0aea54 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix SWC test (#45574)

This PR fixes several test cases related to closure handling. Idents
declared in the module scope shouldn't be included in the closure.

NEXT-456

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 99166f82
......@@ -7,17 +7,15 @@ use next_binding::swc::core::{
},
ecma::{
ast::{
op, ArrayLit, AssignExpr, BlockStmt, CallExpr, ComputedPropName, Decl, ExportDecl,
Expr, ExprStmt, FnDecl, Function, Id, Ident, KeyValueProp, Lit, MemberExpr, MemberProp,
Module, ModuleDecl, ModuleItem, PatOrExpr, Prop, PropName, ReturnStmt, Stmt, Str,
VarDecl, VarDeclKind, VarDeclarator,
op, ArrayLit, AssignExpr, AssignPatProp, BlockStmt, CallExpr, ComputedPropName, Decl,
ExportDecl, Expr, ExprStmt, FnDecl, Function, Id, Ident, KeyValuePatProp, KeyValueProp,
Lit, MemberExpr, MemberProp, Module, ModuleDecl, ModuleItem, ObjectPatProp, Param, Pat,
PatOrExpr, Prop, PropName, RestPat, ReturnStmt, Stmt, Str, VarDecl, VarDeclKind,
VarDeclarator,
},
atoms::JsWord,
utils::{find_pat_ids, private_ident, quote_ident, ExprFactory},
visit::{
as_folder, noop_visit_mut_type, noop_visit_type, visit_obj_and_computed, Fold, Visit,
VisitMut, VisitMutWith, VisitWith,
},
utils::{private_ident, quote_ident, ExprFactory},
visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith},
},
};
use serde::Deserialize;
......@@ -42,7 +40,12 @@ pub fn server_actions<C: Comments>(
in_export_decl: false,
has_action: false,
top_level: false,
closure_candidates: Default::default(),
in_module: true,
in_action_fn: false,
closure_idents: Default::default(),
action_idents: Default::default(),
annotations: Default::default(),
extra_items: Default::default(),
export_actions: Default::default(),
......@@ -61,7 +64,10 @@ struct ServerActions<C: Comments> {
has_action: bool,
top_level: bool,
closure_candidates: Vec<Id>,
in_module: bool,
in_action_fn: bool,
closure_idents: Vec<Id>,
action_idents: Vec<Id>,
annotations: Vec<Stmt>,
extra_items: Vec<ModuleItem>,
......@@ -77,34 +83,41 @@ impl<C: Comments> VisitMut for ServerActions<C> {
}
fn visit_mut_fn_decl(&mut self, f: &mut FnDecl) {
{
let old_len = self.closure_candidates.len();
self.closure_candidates
.extend(find_pat_ids(&f.function.params));
let mut in_action_fn = false;
f.visit_mut_children_with(self);
self.closure_candidates.truncate(old_len);
}
if !(self.in_action_file && self.in_export_decl) {
// Check if the first item is `"use action"`;
if self.in_action_file && self.in_export_decl {
// All export functions in a server file are actions
in_action_fn = true;
} else {
// Check if the first item is `"use server"`
if let Some(body) = &mut f.function.body {
if let Some(Stmt::Expr(first)) = body.stmts.first() {
match &*first.expr {
Expr::Lit(Lit::Str(Str { value, .. })) if value == "use action" => {}
_ => return,
Expr::Lit(Lit::Str(Str { value, .. })) if value == "use server" => {
in_action_fn = true;
body.stmts.remove(0);
}
_ => {}
}
} else {
return;
}
body.stmts.remove(0);
} else {
return;
}
}
{
// Visit children
let old_in_action_fn = self.in_action_fn;
let old_in_module = self.in_module;
self.in_action_fn = in_action_fn;
self.in_module = false;
f.visit_mut_children_with(self);
self.in_action_fn = old_in_action_fn;
self.in_module = old_in_module;
}
if !in_action_fn {
return;
}
if !f.function.is_async {
HANDLER.with(|handler| {
handler
......@@ -123,7 +136,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
self.has_action = true;
self.export_actions.push(action_name.to_string());
// myAction.$$typeof = Symbol.for('react.action.reference');
// myAction.$$typeof = Symbol.for('react.server.reference');
self.annotations.push(annotate(
&f.ident,
"$$typeof",
......@@ -132,7 +145,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
callee: quote_ident!("Symbol")
.make_member(quote_ident!("for"))
.as_callee(),
args: vec!["react.action.reference".as_arg()],
args: vec!["react.server.reference".as_arg()],
type_args: Default::default(),
}
.into(),
......@@ -171,15 +184,14 @@ impl<C: Comments> VisitMut for ServerActions<C> {
} else {
// Hoist the function to the top level.
let mut used_ids = idents_used_by(&f.function.body);
used_ids.retain(|id| self.closure_candidates.contains(id));
let mut ids_from_closure = self.action_idents.clone();
ids_from_closure.retain(|id| self.closure_idents.contains(id));
let closure_arg = private_ident!("closure");
f.function.body.visit_mut_with(&mut ClosureReplacer {
closure_arg: &closure_arg,
used_ids: &used_ids,
used_ids: &ids_from_closure,
});
// myAction.$$closure = [id1, id2]
......@@ -188,7 +200,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
"$$closure",
ArrayLit {
span: DUMMY_SP,
elems: used_ids
elems: ids_from_closure
.iter()
.cloned()
.map(|id| Some(id.as_arg()))
......@@ -248,10 +260,57 @@ impl<C: Comments> VisitMut for ServerActions<C> {
m.visit_mut_children_with(self);
}
fn visit_mut_stmt(&mut self, n: &mut Stmt) {
n.visit_mut_children_with(self);
if self.in_module {
return;
}
let ids = collect_idents_in_stmt(n);
if !self.in_action_fn && !self.in_action_file {
self.closure_idents.extend(ids);
}
}
fn visit_mut_param(&mut self, n: &mut Param) {
n.visit_mut_children_with(self);
if !self.in_action_fn && !self.in_action_file {
match &n.pat {
Pat::Ident(ident) => {
self.closure_idents.push(ident.id.to_id());
}
Pat::Array(array) => {
self.closure_idents
.extend(collect_idents_in_array_pat(&array.elems));
}
Pat::Object(object) => {
self.closure_idents
.extend(collect_idents_in_object_pat(&object.props));
}
Pat::Rest(rest) => {
if let Pat::Ident(ident) = &*rest.arg {
self.closure_idents.push(ident.id.to_id());
}
}
_ => {}
}
}
}
fn visit_mut_ident(&mut self, n: &mut Ident) {
n.visit_mut_children_with(self);
if self.in_action_fn {
self.action_idents.push(n.to_id())
}
}
fn visit_mut_module_items(&mut self, stmts: &mut Vec<ModuleItem>) {
if let Some(ModuleItem::Stmt(Stmt::Expr(first))) = stmts.first() {
match &*first.expr {
Expr::Lit(Lit::Str(Str { value, .. })) if value == "use action" => {
Expr::Lit(Lit::Str(Str { value, .. })) if value == "use server" => {
self.in_action_file = true;
self.has_action = true;
}
......@@ -332,45 +391,98 @@ fn annotate(fn_name: &Ident, field_name: &str, value: Box<Expr>) -> Stmt {
})
}
fn idents_used_by<N>(n: &N) -> Vec<Id>
where
N: VisitWith<IdentUsageCollector>,
{
let mut v = IdentUsageCollector {
..Default::default()
};
n.visit_with(&mut v);
v.ids
}
fn collect_idents_in_array_pat(elems: &[Option<Pat>]) -> Vec<Id> {
let mut ids = Vec::new();
for elem in elems.iter().flatten() {
match elem {
Pat::Ident(ident) => {
ids.push(ident.id.to_id());
}
Pat::Array(array) => {
ids.extend(collect_idents_in_array_pat(&array.elems));
}
Pat::Object(object) => {
ids.extend(collect_idents_in_object_pat(&object.props));
}
Pat::Rest(rest) => {
if let Pat::Ident(ident) = &*rest.arg {
ids.push(ident.id.to_id());
}
}
_ => {}
}
}
#[derive(Default)]
pub(crate) struct IdentUsageCollector {
ids: Vec<Id>,
ids
}
impl Visit for IdentUsageCollector {
noop_visit_type!();
fn collect_idents_in_object_pat(props: &[ObjectPatProp]) -> Vec<Id> {
let mut ids = Vec::new();
visit_obj_and_computed!();
for prop in props {
match prop {
ObjectPatProp::KeyValue(KeyValuePatProp { key, value }) => {
if let PropName::Ident(ident) = key {
ids.push(ident.to_id());
}
fn visit_ident(&mut self, n: &Ident) {
if self.ids.contains(&n.to_id()) {
return;
match &**value {
Pat::Ident(ident) => {
ids.push(ident.id.to_id());
}
Pat::Array(array) => {
ids.extend(collect_idents_in_array_pat(&array.elems));
}
Pat::Object(object) => {
ids.extend(collect_idents_in_object_pat(&object.props));
}
_ => {}
}
}
ObjectPatProp::Assign(AssignPatProp { key, .. }) => {
ids.push(key.to_id());
}
ObjectPatProp::Rest(RestPat { arg, .. }) => {
if let Pat::Ident(ident) = &**arg {
ids.push(ident.id.to_id());
}
}
}
self.ids.push(n.to_id());
}
fn visit_member_prop(&mut self, n: &MemberProp) {
if let MemberProp::Computed(..) = n {
n.visit_children_with(self);
ids
}
fn collect_idents_in_var_decls(decls: &[VarDeclarator]) -> Vec<Id> {
let mut ids = Vec::new();
for decl in decls {
match &decl.name {
Pat::Ident(ident) => {
ids.push(ident.id.to_id());
}
Pat::Array(array) => {
ids.extend(collect_idents_in_array_pat(&array.elems));
}
Pat::Object(object) => {
ids.extend(collect_idents_in_object_pat(&object.props));
}
_ => {}
}
}
fn visit_prop_name(&mut self, n: &PropName) {
if let PropName::Computed(..) = n {
n.visit_children_with(self);
}
ids
}
fn collect_idents_in_stmt(stmt: &Stmt) -> Vec<Id> {
let mut ids = Vec::new();
if let Stmt::Decl(Decl::Var(var)) = &stmt {
ids.extend(collect_idents_in_var_decls(&var.decls));
}
ids
}
pub(crate) struct ClosureReplacer<'a> {
......
......@@ -2,6 +2,7 @@ use next_binding::swc::{
core::{
common::{chain, comments::SingleThreadedComments, FileName, Mark},
ecma::parser::{EsConfig, Syntax},
ecma::transforms::base::resolver,
ecma::transforms::react::jsx,
ecma::transforms::testing::{test, test_fixture},
},
......@@ -305,10 +306,13 @@ fn server_actions_fixture(input: PathBuf) {
test_fixture(
syntax(),
&|_tr| {
server_actions(
&FileName::Real("/app/item.js".into()),
server_actions::Config { is_server: true },
_tr.comments.as_ref().clone(),
chain!(
resolver(Mark::new(), Mark::new(), false),
server_actions(
&FileName::Real("/app/item.js".into()),
server_actions::Config { is_server: true },
_tr.comments.as_ref().clone(),
)
)
},
&input,
......
import deleteFromDb from 'db'
export function Item({ id1, id2 }) {
async function deleteItem() {
"use action";
"use server";
await deleteFromDb(id1);
await deleteFromDb(id2);
}
......
/* __next_internal_action_entry_do_not_use__ $ACTION_deleteItem */ export function Item({ id1 , id2 }) {
/* __next_internal_action_entry_do_not_use__ $ACTION_deleteItem */ import deleteFromDb from 'db'
export function Item({ id1 , id2 }) {
async function deleteItem() {
return $ACTION_deleteItem(deleteItem.$$closure);
}
deleteItem.$$typeof = Symbol.for("react.action.reference");
deleteItem.$$typeof = Symbol.for("react.server.reference");
deleteItem.$$filepath = "/app/item.js";
deleteItem.$$name = "$ACTION_deleteItem";
deleteItem.$$closure = [
......
async function myAction(a, b, c) {
"use action";
"use server";
console.log('a')
}
......
/* __next_internal_action_entry_do_not_use__ $ACTION_myAction */ async function myAction(a, b, c) {
console.log('a');
}
myAction.$$typeof = Symbol.for("react.action.reference");
myAction.$$typeof = Symbol.for("react.server.reference");
myAction.$$filepath = "/app/item.js";
myAction.$$name = "$ACTION_myAction";
export const $ACTION_myAction = myAction;
......
// app/send.ts
"use action";
"use server";
export async function myAction(a, b, c) {
console.log('a')
}
\ No newline at end of file
......@@ -2,6 +2,6 @@
/* __next_internal_action_entry_do_not_use__ myAction */ export async function myAction(a, b, c) {
console.log('a');
}
myAction.$$typeof = Symbol.for("react.action.reference");
myAction.$$typeof = Symbol.for("react.server.reference");
myAction.$$filepath = "/app/item.js";
myAction.$$name = "myAction";
"use action";
"use server";
export async function a() {}
export async function b() {}
export async function c() {}
......@@ -7,6 +7,6 @@ function d() {}
function Foo() {
async function e() {
"use action"
"use server"
}
}
/* __next_internal_action_entry_do_not_use__ a,b,c,$ACTION_e */ export async function a() {}
a.$$typeof = Symbol.for("react.action.reference");
a.$$typeof = Symbol.for("react.server.reference");
a.$$filepath = "/app/item.js";
a.$$name = "a";
export async function b() {}
b.$$typeof = Symbol.for("react.action.reference");
b.$$typeof = Symbol.for("react.server.reference");
b.$$filepath = "/app/item.js";
b.$$name = "b";
export async function c() {}
c.$$typeof = Symbol.for("react.action.reference");
c.$$typeof = Symbol.for("react.server.reference");
c.$$filepath = "/app/item.js";
c.$$name = "c";
function d() {}
......@@ -15,7 +15,7 @@ function Foo() {
async function e() {
return $ACTION_e(e.$$closure);
}
e.$$typeof = Symbol.for("react.action.reference");
e.$$typeof = Symbol.for("react.server.reference");
e.$$filepath = "/app/item.js";
e.$$name = "$ACTION_e";
e.$$closure = [];
......
import deleteFromDb from 'db'
const v1 = 'v1';
export function Item({ id1, id2 }) {
const v2 = id2;
async function deleteItem() {
"use server";
await deleteFromDb(id1);
await deleteFromDb(v1);
await deleteFromDb(v2);
}
return <Button action={deleteItem}>Delete</Button>;
}
\ No newline at end of file
/* __next_internal_action_entry_do_not_use__ $ACTION_deleteItem */ import deleteFromDb from 'db';
const v1 = 'v1';
export function Item({ id1 , id2 }) {
const v2 = id2;
async function deleteItem() {
return $ACTION_deleteItem(deleteItem.$$closure);
}
deleteItem.$$typeof = Symbol.for("react.server.reference");
deleteItem.$$filepath = "/app/item.js";
deleteItem.$$name = "$ACTION_deleteItem";
deleteItem.$$closure = [
id1,
v2
];
return <Button action={deleteItem}>Delete</Button>;
}
export async function $ACTION_deleteItem(closure) {
await deleteFromDb(closure[0]);
await deleteFromDb(v1);
await deleteFromDb(closure[1]);
}
\ No newline at end of file
import f, { f1, f2 } from 'foo'
const f3 = 1
var f4
let f5
const [f6, [f7, ...f8], {f9}, { f10, f11: [f12], f13: f14, f15: { f16 }, ...f17 }, ...f18] = []
if (true) {
const g19 = 1;
}
function x() {
const f2 = 1;
const g20 = 1;
}
export function y(p, [p1, { p2 }], ...p3) {
const f2 = 1
const f11 = 1
const f19 = 1
if (true) {
const f8 = 1
}
async function action() {
"use server";
const f17 = 1
if (true) {
const f18 = 1
const f19 = 1
}
console.log(
f,
f1,
f2,
f3,
f4,
f5,
f6,
f7,
f8,
f2(f9),
f12,
f11,
f16.x,
f17,
f18,
p,
p1,
p2,
p3,
g19,
g20,
globalThis
)
}
return <Button action={action}>Delete</Button>
}
/* __next_internal_action_entry_do_not_use__ $ACTION_action */ import f, { f1, f2 } from 'foo';
const f3 = 1;
var f4;
let f5;
const [f6, [f7, ...f8], { f9 }, { f10 , f11: [f12] , f13: f14 , f15: { f16 } , ...f17 }, ...f18] = [];
if (true) {
const g191 = 1;
}
function x() {
const f2 = 1;
const g201 = 1;
}
export function y(p, [p1, { p2 }], ...p3) {
const f2 = 1;
const f11 = 1;
const f19 = 1;
if (true) {
const f8 = 1;
}
async function action() {
return $ACTION_action(action.$$closure);
}
action.$$typeof = Symbol.for("react.server.reference");
action.$$filepath = "/app/item.js";
action.$$name = "$ACTION_action";
action.$$closure = [
f2,
f2,
f11,
p,
p1,
p2,
p3
];
return <Button action={action}>Delete</Button>;
}
export async function $ACTION_action(closure) {
const f17 = 1;
if (true) {
const f18 = 1;
const f19 = 1;
}
console.log(f, f1, closure[0], f3, f4, f5, f6, f7, f8, closure[0](f9), f12, closure[2], f16.x, f17, f18, closure[3], closure[4], closure[5], closure[6], g19, g20, globalThis);
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment