From 317ca24cfeb8fbe1ad32af93c937d0edaf28ee84 Mon Sep 17 00:00:00 2001 From: Andrew Morris Date: Mon, 24 Jul 2023 17:30:34 +1000 Subject: [PATCH] Support functions and classes in static expressions --- inputs/passing/specialStaticExpressions.ts | 15 ++++++++++++++ valuescript_compiler/src/module_compiler.rs | 23 +++++++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 inputs/passing/specialStaticExpressions.ts diff --git a/inputs/passing/specialStaticExpressions.ts b/inputs/passing/specialStaticExpressions.ts new file mode 100644 index 0000000..6d1277c --- /dev/null +++ b/inputs/passing/specialStaticExpressions.ts @@ -0,0 +1,15 @@ +//! test_output(105) + +export default () => { + return [ + new stuff[0]().x, + stuff[1](), + stuff[2](), + ].reduce((a, b) => a * b); +}; + +const stuff = [ + class Foo { x = 3; }, + function bar() { return 5 }, + () => 7, +] as const; diff --git a/valuescript_compiler/src/module_compiler.rs b/valuescript_compiler/src/module_compiler.rs index e5b2b79..0691b53 100644 --- a/valuescript_compiler/src/module_compiler.rs +++ b/valuescript_compiler/src/module_compiler.rs @@ -1021,7 +1021,6 @@ impl ModuleCompiler { Value::Object(Box::new(Object { properties })) } swc_ecma_ast::Expr::This(_) - | swc_ecma_ast::Expr::Fn(_) | swc_ecma_ast::Expr::Update(_) | swc_ecma_ast::Expr::Assign(_) | swc_ecma_ast::Expr::SuperProp(_) @@ -1046,6 +1045,24 @@ impl ModuleCompiler { Value::String("(error)".to_string()) } }, + swc_ecma_ast::Expr::Fn(fn_) => { + let fn_name = fn_.ident.clone().map(|ident| ident.sym.to_string()); + + let p = match &fn_name { + Some(name) => self.allocate_defn(name), + None => self.allocate_defn_numbered("_anon"), + }; + + let mut fn_defns = self.compile_fn( + p.clone(), + fn_name, + Functionish::Fn(fn_.ident.clone(), fn_.function.clone()), + ); + + self.module.definitions.append(&mut fn_defns); + + Value::Pointer(p) + } swc_ecma_ast::Expr::Arrow(arrow) => { let p = self.allocate_defn_numbered("_anon"); let mut fn_defns = self.compile_fn(p.clone(), None, Functionish::Arrow(arrow.clone())); @@ -1053,8 +1070,10 @@ impl ModuleCompiler { Value::Pointer(p) } + swc_ecma_ast::Expr::Class(class) => { + Value::Pointer(self.compile_class(None, class.ident.as_ref(), &class.class)) + } swc_ecma_ast::Expr::TaggedTpl(_) - | swc_ecma_ast::Expr::Class(_) | swc_ecma_ast::Expr::Yield(_) | swc_ecma_ast::Expr::MetaProp(_) | swc_ecma_ast::Expr::Await(_)