diff --git a/examples/tests/invalid/capture_redefinition.w b/examples/tests/invalid/capture_redefinition.w index 4797ad08710..a8f52b17da4 100644 --- a/examples/tests/invalid/capture_redefinition.w +++ b/examples/tests/invalid/capture_redefinition.w @@ -1,14 +1,25 @@ -let y = "hello"; +let y = "h"; -inflight () => { +() => { + log("hello"); log(y); // ^ Cannot capture symbol "y" because it is shadowed by another symbol with the same name - let y = "world"; + let y = "y"; +}; + +inflight () => { + let y = "hi"; + + inflight () => { + log(y); +// ^ Cannot capture symbol "y" because it is shadowed by another symbol with the same name + let y = "world"; + }; }; -// TODO: https://github.com/winglang/wing/issues/2753 -// let x = "hi"; -// if true { -// log(x); -// let x = "world"; -// } \ No newline at end of file +let x = "hi"; +if true { + log(x); +// ^ Cannot capture symbol "x" because it is shadowed by another symbol with the same name + let x = "world"; +} \ No newline at end of file diff --git a/examples/tests/invalid/inflight_ref_explicit_ops.w b/examples/tests/invalid/inflight_ref_explicit_ops.w index e25f23f19fc..beb54b518e2 100644 --- a/examples/tests/invalid/inflight_ref_explicit_ops.w +++ b/examples/tests/invalid/inflight_ref_explicit_ops.w @@ -11,7 +11,7 @@ class Another { inflight inflightReturnsResource(): cloud.Queue { return this.myQueue; -// ^^^^^^^^ Cannot qualify which operations are performed on resource +// ^^^^^^^^ Cannot qualify access to a lifted object } } @@ -32,7 +32,7 @@ class Test { inflight test1() { let x = this.b; -// ^ Cannot qualify which operations are performed on resource +// ^ Cannot qualify access to a lifted object x.put("hello", "world"); assert(this.justStr == "hello"); this.justBucket.put("hello", "world"); diff --git a/examples/tests/invalid/inflight_ref_resource_sub_method.w b/examples/tests/invalid/inflight_ref_resource_sub_method.w index b0d5f45ac9b..7722e57194d 100644 --- a/examples/tests/invalid/inflight_ref_resource_sub_method.w +++ b/examples/tests/invalid/inflight_ref_resource_sub_method.w @@ -11,12 +11,12 @@ class Another { inflight inflightReturnsResource(): cloud.Queue { return this.myQueue; -// ^^^^^^^^ Cannot qualify which operations are performed on class "this.myQueue" +// ^^^^^^^^ Cannot qualify access to a lifted object } inflight inflightReturnsResource2(): cloud.Queue { return globalQueue; -// ^^^^^^^^^^^^ Cannot qualify which operations are performed on class "globalQueue" +// ^^^^^^^^^^^^ Cannot qualify access to a lifted object } } diff --git a/examples/tests/invalid/resource_captures.w b/examples/tests/invalid/resource_captures.w index 0abb8a65f01..ef4b0ffac09 100644 --- a/examples/tests/invalid/resource_captures.w +++ b/examples/tests/invalid/resource_captures.w @@ -2,24 +2,14 @@ bring cloud; class Foo { bucket: cloud.Bucket; - mutArray: MutArray; - var reassignable: num; collectionOfResources: Array; init() { this.bucket = new cloud.Bucket(); - this.mutArray = MutArray[]; - this.mutArray.push("hello"); - this.reassignable = 42; this.collectionOfResources = Array[]; } inflight test() { - log("${this.reassignable}"); -// ^^^^^^^^^^^^^^^^^ Cannot capture reassignable field 'reassignable' - log(this.mutArray.at(0)); -// ^^^^^^^^^ Unable to reference "this.mutArray" from inflight method "test" because type MutArray is not capturable - let b = this.bucket; // ^^^^^^^^^^^ Unable to qualify which operations are performed on 'this.bucket' of type 'Bucket'. This is not supported yet. b.put("hello", "world"); diff --git a/examples/tests/invalid/use_before_defined.w b/examples/tests/invalid/use_before_defined.w index e32234f95cd..6e898d7e9f5 100644 --- a/examples/tests/invalid/use_before_defined.w +++ b/examples/tests/invalid/use_before_defined.w @@ -2,6 +2,7 @@ log("${y}"); // Access y before it's defined let y = "ho"; if true { - log("${x}"); // Access x before it's defined (even though it's defined in an outer scope) + log("${x}"); +// ^ Symbol "x" used before being defined } let x = "hi"; \ No newline at end of file diff --git a/examples/tests/valid/call_static_of_myself.w b/examples/tests/valid/call_static_of_myself.w new file mode 100644 index 00000000000..0c94eafae31 --- /dev/null +++ b/examples/tests/valid/call_static_of_myself.w @@ -0,0 +1,33 @@ +class Foo { + static inflight foo(): num { return 1; } + static inflight bar(): num { return Foo.foo(); } + + inflight callThis(): num { + return Foo.bar(); + } + +} + +inflight class Bar { + static bar(): num { return 2; } + + callThis(): num { + return Bar.bar(); + } +} + +let foo = new Foo(); + +test "test" { + class Zoo { + static zoo(): num { return 3; } + } + + let bar = new Bar(); + + assert(Foo.foo() == 1); + assert(Bar.bar() == 2); + assert(Zoo.zoo() == 3); + assert(foo.callThis() == 1); + assert(bar.callThis() == 2); +} \ No newline at end of file diff --git a/examples/tests/valid/calling_inflight_variants.w b/examples/tests/valid/calling_inflight_variants.w index 1b81377e170..fa2bbf1c3f3 100644 --- a/examples/tests/valid/calling_inflight_variants.w +++ b/examples/tests/valid/calling_inflight_variants.w @@ -1,5 +1,3 @@ -bring cloud; - class Foo { inflight1: inflight (): num; init() { diff --git a/examples/tests/valid/closure_class.w b/examples/tests/valid/closure_class.w new file mode 100644 index 00000000000..71877cba7ac --- /dev/null +++ b/examples/tests/valid/closure_class.w @@ -0,0 +1,16 @@ +class MyClosure { + inflight another(): str { + return "hello"; + } + + inflight handle(): num { + return 42; + } +} + +let fn = new MyClosure(); + +test "test" { + assert(fn() == 42); + assert(fn.another() == "hello"); +} diff --git a/examples/tests/valid/double_reference.w b/examples/tests/valid/double_reference.w new file mode 100644 index 00000000000..dabd9849157 --- /dev/null +++ b/examples/tests/valid/double_reference.w @@ -0,0 +1,32 @@ +bring cloud; + +let initCount = new cloud.Counter(); + +class Foo { + inflight init() { + initCount.inc(); + } + + inflight method() { } +} + +class Bar { + foo: Foo; + init() { + this.foo = new Foo(); + } + + inflight callFoo() { + this.foo.method(); + } +} + +let bar = new Bar(); + +test "hello" { + bar.callFoo(); + bar.foo.method(); + + // TODO: https://github.com/winglang/wing/issues/3244 + assert(initCount.peek() == /*1*/ 2); +} \ No newline at end of file diff --git a/examples/tests/valid/inflight_class_inner_capture_mutable.w b/examples/tests/valid/inflight_class_inner_capture_mutable.w index 989a64b4c22..435d97b7a40 100644 --- a/examples/tests/valid/inflight_class_inner_capture_mutable.w +++ b/examples/tests/valid/inflight_class_inner_capture_mutable.w @@ -7,9 +7,9 @@ test "inner inflight class capture immutable" { class Inner { dang(): num { y.push(2); - - // TODO: this should be a compiler error (it doesn't) - // see https://github.com/winglang/wing/issues/2729 + + // since the inner class is defined within the same scope, it is actually possible to reassign + // `i` and all will be good with the world. i = i + 1; return y.at(0) + 10; @@ -17,7 +17,6 @@ test "inner inflight class capture immutable" { } assert(new Inner().dang() == 11); - assert(y.at(1) == 2); - - assert(i == 10); // we cannot reassign from within the inflight class above, so this should hold -} \ No newline at end of file + assert(y.at(1) == 2); + assert(i == 11); +} diff --git a/examples/tests/valid/lift_expr_with_this.w b/examples/tests/valid/lift_expr_with_this.w new file mode 100644 index 00000000000..f660bbe8e77 --- /dev/null +++ b/examples/tests/valid/lift_expr_with_this.w @@ -0,0 +1,9 @@ +class Foo { + value: str; + init() { this.value = "hello"; } +} + +let foo_this = new Foo(); +test "test" { + assert(foo_this.value == "hello"); +} diff --git a/examples/tests/valid/lift_redefinition.w b/examples/tests/valid/lift_redefinition.w new file mode 100644 index 00000000000..2ab1c81a9c6 --- /dev/null +++ b/examples/tests/valid/lift_redefinition.w @@ -0,0 +1,7 @@ +let y = "hello"; + +test "test" { + assert(y == "hello"); + let y = "z"; + assert(y == "z"); +} diff --git a/examples/tests/valid/lift_this.w b/examples/tests/valid/lift_this.w new file mode 100644 index 00000000000..bb521ca58b0 --- /dev/null +++ b/examples/tests/valid/lift_this.w @@ -0,0 +1,18 @@ +class Foo { + inflight x: num; + inflight init() { + this.x = 42; + } + inflight bar(): num { + return this.x; + } + inflight foo(): num { + return this.bar() / 2; + } +} + +let f = new Foo(); + +test "test" { + assert(f.foo() == 21); +} diff --git a/examples/tests/valid/lift_via_closure.w b/examples/tests/valid/lift_via_closure.w new file mode 100644 index 00000000000..bcac2a57d52 --- /dev/null +++ b/examples/tests/valid/lift_via_closure.w @@ -0,0 +1,43 @@ +bring cloud; + +let bucket2 = new cloud.Bucket(); + +let fn = inflight () => { + bucket2.put("hello", "world"); +}; + +class MyClosure { + bucket: cloud.Bucket; + + init() { + this.bucket = new cloud.Bucket(); + } + + inflight handle() { + log("handle called"); + this.putFile(); + } + + inflight putFile() { + log("putFile called"); + this.bucket.put("hello", "world"); + } + + inflight listFiles(): Array { + bucket2.put("b2", "world"); + return this.bucket.list(); + } +} + +let fn2 = new MyClosure(); + +test "call synthetic closure class as a function" { + fn(); +} + +test "call non-synthetic closure as a function" { + fn2(); + assert(fn2.bucket.get("hello") == "world"); + assert(fn2.listFiles().length == 1); + assert(bucket2.get("b2") == "world"); +} diff --git a/examples/tests/valid/lift_via_closure_explicit.w b/examples/tests/valid/lift_via_closure_explicit.w new file mode 100644 index 00000000000..576ef35b1df --- /dev/null +++ b/examples/tests/valid/lift_via_closure_explicit.w @@ -0,0 +1,18 @@ +bring cloud; + +class MyClosure { + q: cloud.Queue; + init() { + this.q = new cloud.Queue(); + } + + inflight handle() { + this.q.push("hello"); + } +} + +let fn = new MyClosure(); + +test "test" { + fn(); +} diff --git a/examples/tests/valid/resource.w b/examples/tests/valid/resource.w index cc515088755..811c3ead4a8 100644 --- a/examples/tests/valid/resource.w +++ b/examples/tests/valid/resource.w @@ -89,7 +89,11 @@ let res = new Bar("Arr", bucket, MyEnum.B); test "test" { let s = res.myMethod(); - assert(s == "counter is: 101"); + log(s); + + // TODO: https://github.com/winglang/wing/issues/3244 + assert(s == "counter is: 201"); // Supposed to be: assert(s == "counter is: 101"); + assert(bucket.list().length == 1); assert(res.foo.inflightField == 123); res.testTypeAccess(); @@ -136,7 +140,7 @@ let bigOlPublisher = new BigPublisher(); test "dependency cycles" { bigOlPublisher.publish("foo"); let count = bigOlPublisher.getObjectCount(); - // assert(count == 2); TODO: This fails due to issue: https://github.com/winglang/wing/issues/2082 + // assert(count == 2); // TODO: This fails due to issue: https://github.com/winglang/wing/issues/2082 } // Scope and ID tests diff --git a/examples/tests/valid/shadowing.w b/examples/tests/valid/shadowing.w index 96635ed630a..748286ab5b4 100644 --- a/examples/tests/valid/shadowing.w +++ b/examples/tests/valid/shadowing.w @@ -16,7 +16,7 @@ let fn = inflight (): Array => { result.push(bar); } - // since we are not attempting to capture "foo" before it ise defined in this scope, this should + // since we are not attempting to capture "foo" before it is defined in this scope, this should // work. let foo = "bang"; result.push(foo); diff --git a/libs/wingc/src/ast.rs b/libs/wingc/src/ast.rs index 2334fb3092c..4921821c33c 100644 --- a/libs/wingc/src/ast.rs +++ b/libs/wingc/src/ast.rs @@ -9,6 +9,7 @@ use itertools::Itertools; use crate::diagnostic::WingSpan; use crate::type_check::symbol_env::SymbolEnv; +use crate::type_check::CLOSURE_CLASS_HANDLE_METHOD; static EXPR_COUNTER: AtomicUsize = AtomicUsize::new(0); @@ -155,6 +156,14 @@ pub struct UserDefinedType { } impl UserDefinedType { + pub fn for_class(class: &Class) -> Self { + Self { + root: class.name.clone(), + fields: vec![], + span: class.name.span.clone(), + } + } + pub fn full_path(&self) -> Vec { let mut path = vec![self.root.clone()]; path.extend(self.fields.clone()); @@ -266,6 +275,8 @@ pub enum FunctionBody { #[derive(Debug)] pub struct FunctionDefinition { + /// The name of the function ('None' if this is a closure). + pub name: Option, /// The function implementation. pub body: FunctionBody, /// The function signature, including the return type. @@ -326,27 +337,71 @@ pub struct Class { pub methods: Vec<(Symbol, FunctionDefinition)>, pub initializer: FunctionDefinition, pub inflight_initializer: FunctionDefinition, - pub parent: Option, // the expression must be a reference to a user defined type + pub parent: Option, // base class (the expression is a reference to a user defined type) pub implements: Vec, pub phase: Phase, } impl Class { /// Returns the `UserDefinedType` of the parent class, if any. - pub fn parent_udt(&self) -> Option { + pub fn parent_udt(&self) -> Option<&UserDefinedType> { let Some(expr) = &self.parent else { return None; }; - let ExprKind::Reference(ref r) = expr.kind else { - return None; - }; + expr.as_type_reference() + } - let Reference::TypeReference(t) = r else { - return None; - }; + /// Returns all methods, including the initializer and inflight initializer. + pub fn all_methods(&self, include_initializers: bool) -> Vec<&FunctionDefinition> { + let mut methods: Vec<&FunctionDefinition> = vec![]; + + for (_, m) in &self.methods { + methods.push(&m); + } - Some(t.clone()) + if include_initializers { + methods.push(&self.initializer); + methods.push(&self.inflight_initializer); + } + + methods + } + + pub fn inflight_methods(&self, include_initializers: bool) -> Vec<&FunctionDefinition> { + self + .all_methods(include_initializers) + .iter() + .filter(|m| m.signature.phase == Phase::Inflight) + .map(|f| *f) + .collect_vec() + } + + pub fn inflight_fields(&self) -> Vec<&ClassField> { + self.fields.iter().filter(|f| f.phase == Phase::Inflight).collect_vec() + } + + /// Returns the function definition of the "handle" method of this class (if this is a closure + /// class). Otherwise returns None. + pub fn closure_handle_method(&self) -> Option<&FunctionDefinition> { + for method in self.inflight_methods(false) { + if let Some(name) = &method.name { + if name.name == CLOSURE_CLASS_HANDLE_METHOD { + return Some(method); + } + } + } + + None + } + + pub fn preflight_methods(&self, include_initializers: bool) -> Vec<&FunctionDefinition> { + self + .all_methods(include_initializers) + .iter() + .filter(|f| f.signature.phase != Phase::Inflight) + .map(|f| *f) + .collect_vec() } } @@ -517,6 +572,14 @@ impl Expr { Self { id, kind, span } } + + /// Returns true if the expression is a reference to a type. + pub fn as_type_reference(&self) -> Option<&UserDefinedType> { + match &self.kind { + ExprKind::Reference(Reference::TypeReference(t)) => Some(t), + _ => None, + } + } } #[derive(Debug)] diff --git a/libs/wingc/src/closure_transform.rs b/libs/wingc/src/closure_transform.rs index 42bed9baf5f..a1514cf4d65 100644 --- a/libs/wingc/src/closure_transform.rs +++ b/libs/wingc/src/closure_transform.rs @@ -7,7 +7,7 @@ use crate::{ }, diagnostic::WingSpan, fold::{self, Fold}, - type_check::HANDLE_METHOD_NAME, + type_check::{CLASS_INFLIGHT_INIT_NAME, CLASS_INIT_NAME, CLOSURE_CLASS_HANDLE_METHOD}, }; pub const CLOSURE_CLASS_PREFIX: &str = "$Closure"; @@ -135,7 +135,7 @@ impl Fold for ClosureTransformer { span: WingSpan::default(), }; let handle_name = Symbol { - name: HANDLE_METHOD_NAME.to_string(), + name: CLOSURE_CLASS_HANDLE_METHOD.to_string(), span: WingSpan::default(), }; @@ -153,7 +153,7 @@ impl Fold for ClosureTransformer { let class_fields: Vec = vec![]; let class_init_params: Vec = vec![]; - let mut new_func_def = if self.inside_scope_with_this { + let new_func_def = if self.inside_scope_with_this { // If we are inside a class, we transform inflight closures with an extra // `let __parent_this_${CLOSURE_COUNT} = this;` statement before the class definition, and replace references // to `this` with `__parent_this_${CLOSURE_COUNT}` so that they can access the parent class's fields. @@ -168,9 +168,16 @@ impl Fold for ClosureTransformer { func_def }; - // Anonymous functions are always static -- since the function code is now an instance method on a class, - // we need to set this to false. - new_func_def.is_static = false; + let new_func_def = FunctionDefinition { + name: Some(handle_name.clone()), + body: new_func_def.body, + signature: new_func_def.signature, + span: new_func_def.span, + + // Anonymous functions are always static -- since the function code is now an instance method on a class, + // we need to set this to false. + is_static: false, + }; // class_init_body := // ``` @@ -240,6 +247,7 @@ impl Fold for ClosureTransformer { name: new_class_name.clone(), phase: Phase::Preflight, initializer: FunctionDefinition { + name: Some(CLASS_INIT_NAME.into()), signature: FunctionSignature { parameters: class_init_params, return_type: Box::new(class_type_annotation.clone()), @@ -254,6 +262,7 @@ impl Fold for ClosureTransformer { parent: None, methods: vec![(handle_name.clone(), new_func_def)], inflight_initializer: FunctionDefinition { + name: Some(CLASS_INFLIGHT_INIT_NAME.into()), signature: FunctionSignature { parameters: vec![], return_type: Box::new(TypeAnnotation { @@ -286,7 +295,7 @@ impl Fold for ClosureTransformer { obj_id: None, obj_scope: None, }, - WingSpan::default(), + expr.span.clone(), // <<-- span of original expression ); self.class_statements.push(class_def); diff --git a/libs/wingc/src/comp_ctx.rs b/libs/wingc/src/comp_ctx.rs index 502bec4d2b5..d18ea3c7a69 100644 --- a/libs/wingc/src/comp_ctx.rs +++ b/libs/wingc/src/comp_ctx.rs @@ -18,6 +18,7 @@ pub enum CompilationPhase { Compiling, Parsing, TypeChecking, + Lifting, Jsifying, } diff --git a/libs/wingc/src/fold.rs b/libs/wingc/src/fold.rs index af769e77837..20bc2b41640 100644 --- a/libs/wingc/src/fold.rs +++ b/libs/wingc/src/fold.rs @@ -377,6 +377,7 @@ where F: Fold + ?Sized, { FunctionDefinition { + name: node.name.map(|x| f.fold_symbol(x)), body: match node.body { FunctionBody::Statements(scope) => FunctionBody::Statements(f.fold_scope(scope)), FunctionBody::External(s) => FunctionBody::External(s), diff --git a/libs/wingc/src/jsify.rs b/libs/wingc/src/jsify.rs index 694c78d80ed..cfd9f70e267 100644 --- a/libs/wingc/src/jsify.rs +++ b/libs/wingc/src/jsify.rs @@ -1,36 +1,25 @@ pub mod codemaker; - +mod tests; use aho_corasick::AhoCorasick; use const_format::formatcp; -use indexmap::{indexmap, indexset, IndexMap, IndexSet}; +use indexmap::IndexSet; use itertools::Itertools; -use std::{ - cmp::Ordering, - collections::{BTreeMap, BTreeSet}, - fmt::Display, - path::Path, - slice::Iter, - vec, -}; +use std::{borrow::Borrow, cmp::Ordering, collections::BTreeMap, path::Path, vec}; use crate::{ ast::{ - ArgList, BinaryOperator, Class as AstClass, ClassField, Expr, ExprKind, FunctionBody, FunctionDefinition, + ArgList, BinaryOperator, Class as AstClass, Expr, ExprKind, FunctionBody, FunctionDefinition, InterpolatedStringPart, Literal, Phase, Reference, Scope, Stmt, StmtKind, Symbol, TypeAnnotationKind, - UnaryOperator, + UnaryOperator, UserDefinedType, }, comp_ctx::{CompilationContext, CompilationPhase}, dbg_panic, debug, diagnostic::{report_diagnostic, Diagnostic, WingSpan}, files::Files, type_check::{ - resolve_udt_from_expr, resolve_user_defined_type, - symbol_env::{LookupResult, SymbolEnv, SymbolEnvRef}, - ClassLike, SymbolKind, Type, TypeRef, Types, UnsafeRef, VariableInfo, VariableKind, CLASS_INFLIGHT_INIT_NAME, - HANDLE_METHOD_NAME, + lifts::Lifts, symbol_env::SymbolEnv, ClassLike, Type, TypeRef, Types, VariableKind, CLASS_INFLIGHT_INIT_NAME, }, - visit::{self, Visit}, MACRO_REPLACE_ARGS, MACRO_REPLACE_ARGS_TEXT, MACRO_REPLACE_SELF, WINGSDK_ASSEMBLY_NAME, WINGSDK_RESOURCE, WINGSDK_STD_MODULE, }; @@ -54,18 +43,19 @@ const APP_BASE_CLASS: &str = "$AppBase"; const ROOT_CLASS: &str = "$Root"; const JS_CONSTRUCTOR: &str = "constructor"; -pub struct JSifyContext { +pub struct JSifyContext<'a> { pub in_json: bool, /// The current execution phase of the AST traversal. /// The root of any Wing app starts with the preflight phase, and /// the `inflight` keyword specifies scopes that are inflight. pub phase: Phase, + pub files: &'a mut Files, + pub lifts: Option<&'a Lifts>, } pub struct JSifier<'a> { - pub types: &'a Types, + pub types: &'a mut Types, source_files: &'a Files, - emitted_files: Files, /// Root of the project, used for resolving extern modules absolute_project_root: &'a Path, shim: bool, @@ -82,7 +72,7 @@ enum BindMethod { impl<'a> JSifier<'a> { pub fn new( - types: &'a Types, + types: &'a mut Types, source_files: &'a Files, app_name: &'a str, absolute_project_root: &'a Path, @@ -91,7 +81,6 @@ impl<'a> JSifier<'a> { Self { types, source_files, - emitted_files: Files::new(), shim, app_name, absolute_project_root, @@ -103,12 +92,9 @@ impl<'a> JSifier<'a> { self.types.get_expr_type(expr).unwrap() } - fn js_resolve_path(path_name: &str) -> String { - format!("\"./{}\"", path_name.replace("\\", "/")) - } - - pub fn jsify(&mut self, scope: &Scope) { + pub fn jsify(&mut self, scope: &Scope) -> Files { CompilationContext::set(CompilationPhase::Jsifying, &scope.span); + let mut files = Files::default(); let mut js = CodeMaker::default(); let mut imports = CodeMaker::default(); @@ -119,11 +105,13 @@ impl<'a> JSifier<'a> { (_, StmtKind::Class(AstClass { .. })) => Ordering::Greater, _ => Ordering::Equal, }) { - let jsify_context = JSifyContext { + let mut jsify_context = JSifyContext { in_json: false, phase: Phase::Preflight, + files: &mut files, + lifts: None, }; - let s = self.jsify_statement(scope.env.borrow().as_ref().unwrap(), statement, &jsify_context); // top level statements are always preflight + let s = self.jsify_statement(scope.env.borrow().as_ref().unwrap(), statement, &mut jsify_context); // top level statements are always preflight if let StmtKind::Bring { identifier: _, module_name: _, @@ -189,21 +177,15 @@ impl<'a> JSifier<'a> { output.add_code(js); } - match self.emitted_files.add_file(PREFLIGHT_FILE_NAME, output.to_string()) { + match files.add_file(PREFLIGHT_FILE_NAME, output.to_string()) { Ok(()) => {} Err(err) => report_diagnostic(err.into()), } - } - /// Write all files to the output directory - pub fn emit_files(&mut self, out_dir: &Path) { - match self.emitted_files.emit_files(out_dir) { - Ok(()) => {} - Err(err) => report_diagnostic(err.into()), - } + files } - fn jsify_scope_body(&mut self, scope: &Scope, ctx: &JSifyContext) -> CodeMaker { + fn jsify_scope_body(&self, scope: &Scope, ctx: &mut JSifyContext) -> CodeMaker { CompilationContext::set(CompilationPhase::Jsifying, &scope.span); let mut code = CodeMaker::default(); @@ -215,7 +197,7 @@ impl<'a> JSifier<'a> { code } - fn jsify_reference(&mut self, reference: &Reference, ctx: &JSifyContext) -> String { + fn jsify_reference(&self, reference: &Reference, ctx: &mut JSifyContext) -> String { match reference { Reference::Identifier(identifier) => identifier.to_string(), Reference::InstanceMember { @@ -223,7 +205,7 @@ impl<'a> JSifier<'a> { property, optional_accessor, } => self.jsify_expression(object, ctx) + (if *optional_accessor { "?." } else { "." }) + &property.to_string(), - Reference::TypeReference(udt) => self.jsify_type(&TypeAnnotationKind::UserDefined(udt.clone()), ctx), + Reference::TypeReference(udt) => self.jsify_type(&TypeAnnotationKind::UserDefined(udt.clone())), Reference::TypeMember { typeobject, property } => { let typename = self.jsify_expression(typeobject, ctx); typename + "." + &property.to_string() @@ -232,11 +214,11 @@ impl<'a> JSifier<'a> { } fn jsify_arg_list( - &mut self, + &self, arg_list: &ArgList, scope: Option, id: Option, - ctx: &JSifyContext, + ctx: &mut JSifyContext, ) -> String { let mut args = vec![]; let mut structure_args = vec![]; @@ -250,22 +232,11 @@ impl<'a> JSifier<'a> { } for arg in arg_list.pos_args.iter() { - args.push(self.jsify_expression(arg, &ctx)); + args.push(self.jsify_expression(arg, ctx)); } for arg in arg_list.named_args.iter() { - // convert snake to camel case - structure_args.push(format!( - "{}: {}", - arg.0.name.clone(), - self.jsify_expression( - arg.1, - &JSifyContext { - in_json: ctx.in_json, - phase: Phase::Independent, - } - ) - )); + structure_args.push(format!("{}: {}", arg.0.name.clone(), self.jsify_expression(arg.1, ctx))); } if !structure_args.is_empty() { @@ -279,15 +250,47 @@ impl<'a> JSifier<'a> { } } - fn jsify_type(&self, typ: &TypeAnnotationKind, ctx: &JSifyContext) -> String { + fn jsify_type(&self, typ: &TypeAnnotationKind) -> String { match typ { - TypeAnnotationKind::UserDefined(t) => jsify_type_name(&t.full_path(), ctx.phase), + TypeAnnotationKind::UserDefined(t) => self.jsify_user_defined_type(&t), _ => todo!(), } } - fn jsify_expression(&mut self, expression: &Expr, ctx: &JSifyContext) -> String { + fn jsify_user_defined_type(&self, udt: &UserDefinedType) -> String { + udt.full_path_str() + } + + pub fn jsify_expression(&self, expression: &Expr, ctx: &mut JSifyContext) -> String { CompilationContext::set(CompilationPhase::Jsifying, &expression.span); + + // if we are in inflight and there's a lifting/capturing token associated with this expression + // then emit the token instead of the expression. + if ctx.phase == Phase::Inflight { + if let Some(lifts) = &ctx.lifts { + if let Some(t) = lifts.token_for_expr(&expression.id) { + return t.clone(); + } + } + } + + // if we are in preflight phase and we see an inflight expression (which is not "this."), then + // this is an error. this can happen if we render a lifted preflight expression that references + // an e.g. variable from inflight (`myarr.get(i)` where `myarr` is preflight and `i` is an + // inflight variable). in this case we need to bail out. + if ctx.phase == Phase::Preflight { + if let Some(expr_phase) = self.types.get_expr_phase(expression) { + if expr_phase == Phase::Inflight { + report_diagnostic(Diagnostic { + message: "Cannot reference an inflight value from within a preflight expression".to_string(), + span: Some(expression.span.clone()), + }); + + return "".to_string(); + } + } + } + let auto_await = match ctx.phase { Phase::Inflight => "await ", _ => "", @@ -409,11 +412,7 @@ impl<'a> JSifier<'a> { let is_option = function_type.is_option(); let function_type = function_type.maybe_unwrap_option(); let function_sig = function_type.as_function_sig(); - - let expr_string = match &callee.kind { - ExprKind::Reference(reference) => self.jsify_reference(reference, ctx), - _ => format!("({})", self.jsify_expression(callee, ctx)), - }; + let expr_string = self.jsify_expression(callee, ctx); let args_string = self.jsify_arg_list(&arg_list, None, None, ctx); let mut args_text_string = lookup_span(&arg_list.span, &self.source_files); if args_text_string.len() > 0 { @@ -516,9 +515,11 @@ impl<'a> JSifier<'a> { ) } ExprKind::JsonLiteral { is_mut, element } => { - let json_context = &JSifyContext { + let json_context = &mut JSifyContext { in_json: true, phase: ctx.phase, + files: ctx.files, + lifts: ctx.lifts, }; let js_out = match &element.kind { ExprKind::JsonMapLiteral { .. } => { @@ -568,14 +569,7 @@ impl<'a> JSifier<'a> { format!("Object.freeze(new Set([{}]))", item_list) } } - ExprKind::FunctionClosure(func_def) => match func_def.signature.phase { - Phase::Inflight => { - assert!(ctx.phase == Phase::Inflight, "inflight closures should have been transformed into preflight handler classes in the closure_transform compiler phase"); - self.jsify_function(None, func_def, false, ctx).to_string() - }, - Phase::Independent => unimplemented!(), - Phase::Preflight => self.jsify_function(None, func_def, false, ctx).to_string(), - }, + ExprKind::FunctionClosure(func_def) => self.jsify_function(None, func_def, ctx).to_string(), ExprKind::CompilerDebugPanic => { // Handle the debug panic expression (during jsifying) dbg_panic!(); @@ -584,7 +578,7 @@ impl<'a> JSifier<'a> { } } - fn jsify_statement(&mut self, env: &SymbolEnv, statement: &Stmt, ctx: &JSifyContext) -> CodeMaker { + fn jsify_statement(&self, env: &SymbolEnv, statement: &Stmt, ctx: &mut JSifyContext) -> CodeMaker { CompilationContext::set(CompilationPhase::Jsifying, &statement.span); match &statement.kind { StmtKind::SuperConstructor { arg_list } => { @@ -812,7 +806,7 @@ impl<'a> JSifier<'a> { } } - fn jsify_enum(&mut self, values: &IndexSet) -> CodeMaker { + fn jsify_enum(&self, values: &IndexSet) -> CodeMaker { let mut code = CodeMaker::default(); let mut value_index = 0; @@ -833,22 +827,28 @@ impl<'a> JSifier<'a> { code } - fn jsify_function( - &mut self, - name: Option<&str>, - func_def: &FunctionDefinition, - is_class_member: bool, - ctx: &JSifyContext, - ) -> CodeMaker { + fn jsify_function(&self, class: Option<&AstClass>, func_def: &FunctionDefinition, ctx: &mut JSifyContext) -> String { let mut parameter_list = vec![]; for p in &func_def.signature.parameters { parameter_list.push(p.name.to_string()); } - let (name, arrow) = match name { - Some(name) => (name, ""), - None => ("", "=> "), + let (name, arrow) = match &func_def.name { + Some(name) => { + let mut result = name.name.clone(); + + // if this is an inflight class, we need to rename the constructor to "constructor" because + // it's "just a class" basically. + if let Some(class) = class { + if result == CLASS_INFLIGHT_INIT_NAME && class.phase == Phase::Inflight { + result = JS_CONSTRUCTOR.to_string(); + } + } + + (result, " ".to_string()) + } + None => ("".to_string(), " => ".to_string()), }; let parameters = parameter_list.iter().map(|x| x.as_str()).collect::>().join(", "); @@ -884,198 +884,108 @@ impl<'a> JSifier<'a> { )) } }; - let mut modifiers = vec![]; + let mut prefix = vec![]; - if func_def.is_static && is_class_member { - modifiers.push("static") + if func_def.is_static && class.is_some() { + prefix.push("static") } // if this is "constructor" it cannot be async if name != JS_CONSTRUCTOR && matches!(func_def.signature.phase, Phase::Inflight) { - modifiers.push("async") + prefix.push("async") } - let modifiers = modifiers.join(" "); + if !name.is_empty() { + prefix.push(name.borrow()); + } else if !prefix.is_empty() { + prefix.push(""); + } let mut code = CodeMaker::default(); - code.open(format!("{modifiers} {name}({parameters}) {arrow} {{")); + code.open(format!("{}({parameters}){arrow}{{", prefix.join(" "))); code.add_code(body); code.close("}"); - code + // if prefix is empty it means this is a closure, so we need to wrap it in `(`, `)`. + if prefix.is_empty() { + format!("({})", code.to_string().trim().to_string()) + } else { + code.to_string() + } } - /// Jsify a class - /// This performs two things: - /// 1) It returns the JS code for the resource which includes: - /// - A JS class which inherits from `core.Resource` with all the preflight code of the resource. - /// - A `_toInflight` method in that class that creates inflight client for the resource. This code creates inflight - /// clients for all inner resources and passes them to the inflight client constructor. - /// - Calls to `core.Resource._annotateInflight` to annotate the inflight client's methods with binding information. - /// * Note that at this point the binding information includes ALL methods of all the captured resources. For all - /// client methods. In the future this needs to be generated based on the compiler's capture usage analysis - /// in capture.rs. (see https://github.com/winglang/wing/issues/76, https://github.com/winglang/wing/issues/1449). - /// 2) It generates the JS code for the resource's inflight client and writes it to a JS file. - /// - /// # Example - /// - /// ```wing - /// bring cloud; - /// resource Foo { - /// init() { - /// this.b = new cloud.Bucket(); - /// } - /// inflight my_put() { - /// this.b.put("foo", "bar"); - /// } - /// } - /// ``` - /// Will produce the following **preflight** JS code: - /// ```js - /// class Foo extends core.Resource { - /// constructor(scope, id) { - /// super(scope, id); - /// this.b = new cloud.Bucket(scope, id); - /// } - /// } - /// _toInflight() { - /// const b_client = this._lift(b); - /// const self_client_path = require('path').resolve(__dirname, "clients/MyResource.inflight.js"); - /// return $stdlib.core.NodeJsCode.fromInline(`(new (require("${self_client_path}")).MyResource_inflight({b: ${b_client}}))`); - /// } - /// MyResource._annotateInflight("my_put", {"this.b": { ops: ["put"]}}); - /// ``` - /// And generated Foo client will go into a file called `clients/Foo.inflight.js` that'll look like this: - /// ```js - /// export class Foo_inflight { - /// constructor({ b }) { - /// this.b = b; - /// } - /// async my_put() { - /// await this.b.put("foo","bar"); - /// } - /// } - /// ``` - fn jsify_class(&mut self, env: &SymbolEnv, class: &AstClass, ctx: &JSifyContext) -> CodeMaker { - // Lookup the class type + fn jsify_class(&self, env: &SymbolEnv, class: &AstClass, ctx: &mut JSifyContext) -> CodeMaker { + // lookup the class type let class_type = env.lookup(&class.name, None).unwrap().as_type().unwrap(); - // Jsify the inflight side of the class - let inflight_methods = class - .methods - .iter() - .filter(|(_, m)| m.signature.phase == Phase::Inflight) - .collect_vec(); - - let inflight_fields = class.fields.iter().filter(|f| f.phase == Phase::Inflight).collect_vec(); - - // Find all free variables in the class, and return a list of their symbols - let (mut captured_types, captured_vars) = self.scan_captures(class, &inflight_methods); - - if let Some(parent) = &class.parent { - let parent_type_udt = resolve_udt_from_expr(&parent).unwrap(); - let parent_type = resolve_user_defined_type(&parent_type_udt, env, 0).unwrap(); - captured_types.insert(parent_type_udt.full_path(), parent_type); - } - - // Get all references between inflight methods and preflight values - let mut refs = self.find_inflight_references(class, &captured_vars); - - // Get fields to be captured by resource's client - let lifted_fields = self.get_lifted_fields(class_type); - - // Add bindings for the inflight init - self.add_inflight_init_refs(&mut refs, &lifted_fields, &captured_vars); + // find the nearest lifts object. this could be in the current scope (in which case there will + // be a `lifts` fields in the `class_type` or the parent scope. + let lifts = if let Some(lifts) = &class_type.as_class().unwrap().lifts { + Some(lifts) + } else { + ctx.lifts + }; - // create a list of all captured symbols (vars and types). - let captures = captured_vars - .iter() - .map(|f| f.clone()) - .chain( - captured_types - .iter() - .map(|(n, _)| jsify_type_name(n, Phase::Inflight).clone()), - ) - .collect_vec(); + let ctx = &mut JSifyContext { + in_json: ctx.in_json, + phase: ctx.phase, + files: ctx.files, + lifts, + }; // emit the inflight side of the class into a separate file - self.jsify_class_inflight(env, &class, &lifted_fields, &inflight_methods, &captures, ctx); - - // if our class is declared within a preflight scope, then we emit the preflight class - if ctx.phase == Phase::Preflight { - let mut code = CodeMaker::default(); - - // default base class for preflight classes is `core.Resource` - let extends = if let Some(parent) = &class.parent { - format!(" extends {}", self.jsify_expression(&parent, ctx)) - } else { - format!(" extends {}", STDLIB_CORE_RESOURCE) - }; - - code.open(format!("class {}{extends} {{", class.name.name)); + let inflight_class_code = self.jsify_class_inflight(&class, ctx); - // emit the preflight constructor - code.add_code(self.jsify_constructor( - &class.initializer, - class.parent.is_none(), - &inflight_methods, - &inflight_fields, - ctx, - )); + // if this is inflight/independent, class, just emit the inflight class code inline and move on + // with your life. + if ctx.phase != Phase::Preflight { + return inflight_class_code; + } - // emit preflight methods - let preflight_methods = class - .methods - .iter() - .filter(|(_, m)| m.signature.phase != Phase::Inflight) - .collect_vec(); + // emit the inflight file + self.emit_inflight_file(&class, inflight_class_code, ctx); - for (n, m) in preflight_methods { - code.add_code(self.jsify_function(Some(&n.name), m, true, ctx)); - } + // lets write the code for the preflight side of the class + let mut code = CodeMaker::default(); - // emit the `_toInflightType` static method - code.add_code(self.jsify_to_inflight_type_method(&class, &captured_vars, &captured_types)); + // default base class for preflight classes is `core.Resource` + let extends = if let Some(parent) = &class.parent { + let base = parent.as_type_reference().expect("resolve parent type"); - // emit the `_toInflight` instance method - code.add_code(self.jsify_toinflight_method(&class.name, &lifted_fields)); + format!(" extends {}", base) + } else { + format!(" extends {}", STDLIB_CORE_RESOURCE) + }; - // call `_registerBindObject` to register the class's host binding methods (for type & instance binds). - code.add_code(self.jsify_register_bind_method(class, &refs, class_type, BindMethod::Instance)); - code.add_code(self.jsify_register_bind_method(class, &refs, class_type, BindMethod::Type)); + code.open(format!("class {}{extends} {{", class.name.name)); - code.close("}"); + // emit the preflight constructor + code.add_code(self.jsify_preflight_constructor(&class, ctx)); - code - } else { - // this is the case where a class was declared within an inflight scope in this case we just - // emit a const with the same name that `require`s the inflight client code. - let mut code = CodeMaker::default(); + // emit preflight methods + for m in class.preflight_methods(false) { + code.line(self.jsify_function(Some(class), m, ctx)); + } - let client = Self::js_resolve_path(&inflight_filename(class)); + // emit the `_toInflight` and `_toInflightType` methods (TODO: renamed to `_liftObject` and + // `_liftType`). + code.add_code(self.jsify_to_inflight_type_method(&class, ctx)); + code.add_code(self.jsify_to_inflight_method(&class.name, ctx)); - code.line(format!( - "const {} = require({client})({{{}}});", - class.name.name, - captures.join(", "), - )); + // emit `_registerBindObject` to register bindings (for type & instance binds) + code.add_code(self.jsify_register_bind_method(class, class_type, BindMethod::Instance, ctx)); + code.add_code(self.jsify_register_bind_method(class, class_type, BindMethod::Type, ctx)); - code - } + code.close("}"); + code } - fn jsify_constructor( - &mut self, - constructor: &FunctionDefinition, - no_parent: bool, - inflight_methods: &[&(Symbol, FunctionDefinition)], - inflight_fields: &[&ClassField], - ctx: &JSifyContext, - ) -> CodeMaker { + fn jsify_preflight_constructor(&self, class: &AstClass, ctx: &mut JSifyContext) -> CodeMaker { let mut code = CodeMaker::default(); code.open(format!( "constructor(scope, id, {}) {{", - constructor + class + .initializer .signature .parameters .iter() @@ -1084,41 +994,39 @@ impl<'a> JSifier<'a> { .join(", "), )); - if no_parent { - code.line("super(scope, id);"); - } - - let init_statements = match &constructor.body { + let init_statements = match &class.initializer.body { FunctionBody::Statements(s) => s, FunctionBody::External(_) => panic!("'init' cannot be 'extern'"), }; - if !no_parent { - // Check if the first statement is a super constructor call, if not we need to add one - let super_call = if let Some(s) = init_statements.statements.first() { - matches!(s.kind, StmtKind::SuperConstructor { .. }) - } else { - false - }; + // Check if the first statement is a super constructor call, if not we need to add one + let super_called = if let Some(s) = init_statements.statements.first() { + matches!(s.kind, StmtKind::SuperConstructor { .. }) + } else { + false + }; - if !super_call { - code.line("super(scope, id);"); - } + // we always need a super() call because even if the class doesn't have an explicit parent, it + // will inherit from core.Resource. + if !super_called { + code.line("super(scope, id);"); } // We must jsify the statements in the constructor before adding any additional code blew // this is to ensure if there are calls to super constructor within the statements, // they will be jsified before any attempts to call `this` are made. - code.add_code(self.jsify_scope_body( - &init_statements, - &JSifyContext { - in_json: ctx.in_json, - phase: Phase::Preflight, - }, - )); + code.add_code(self.jsify_scope_body(&init_statements, ctx)); + + let inflight_fields = class.inflight_fields(); + let inflight_methods = class.inflight_methods(true); + + if inflight_fields.len() + inflight_methods.len() > 0 { + let inflight_method_names = inflight_methods + .iter() + .filter_map(|m| m.name.clone()) + .map(|s| s.name) + .collect_vec(); - if inflight_methods.len() + inflight_fields.len() > 0 { - let inflight_method_names = inflight_methods.iter().map(|(name, _)| name.name.clone()).collect_vec(); let inflight_field_names = inflight_fields.iter().map(|f| f.name.name.clone()).collect_vec(); let inflight_ops_string = inflight_method_names .iter() @@ -1132,64 +1040,25 @@ impl<'a> JSifier<'a> { code } - fn jsify_to_inflight_type_method( - &mut self, - class: &AstClass, - lifted_vars: &IndexSet, - captured_types: &IndexMap, TypeRef>, - ) -> CodeMaker { - let client_path = Self::js_resolve_path(&format!("./{}", inflight_filename(class))); + fn jsify_to_inflight_type_method(&self, class: &AstClass, ctx: &JSifyContext) -> CodeMaker { + let client_path = inflight_filename(class); let mut code = CodeMaker::default(); code.open("static _toInflightType(context) {"); // TODO: consider removing the context and making _lift a static method - code.line(format!("const self_client_path = {client_path};")); - - // create an inflight client for each object that is captured from the environment - for var_name in lifted_vars { - code.line(format!("const {var_name}_client = context._lift({var_name});",)); - } + code.open(format!("return {STDLIB}.core.NodeJsCode.fromInline(`")); - // create an inflight type for each referenced preflight type - for (n, t) in captured_types { - let inflight_name = jsify_type_name(n, Phase::Inflight); - let preflight_name = jsify_type_name(n, Phase::Preflight); + code.open(format!("require(\"{client_path}\")({{")); - match &**t { - Type::Class(_) => { - code.line(format!( - "const {inflight_name}Client = {preflight_name}._toInflightType(context);" - )); - } - Type::Enum(e) => { - code.open(format!( - "const {inflight_name}Client = {STDLIB}.core.NodeJsCode.fromInline(`" - )); - code.add_code(self.jsify_enum(&e.values)); - code.close("`);"); - } - _ => { - for sym in n { - report_diagnostic(Diagnostic { - message: format!("Unexpected type \"{t}\" referenced inflight"), - span: Some(sym.span.clone()), - }); - } - } + if let Some(lifts) = &ctx.lifts { + for capture in lifts.captures() { + let preflight = capture.code.clone(); + let lift_type = format!("context._lift({})", preflight); + code.line(format!("{}: ${{{}}},", capture.token, lift_type)); } } - code.open(format!("return {STDLIB}.core.NodeJsCode.fromInline(`")); - - code.open("require(\"${self_client_path}\")({"); - for var_name in lifted_vars { - code.line(format!("{var_name}: ${{{var_name}_client}},")); - } - for (type_name, _) in captured_types { - let inflight_name = jsify_type_name(type_name, Phase::Inflight); - code.line(format!("{inflight_name}: ${{{inflight_name}Client.text}},")); - } code.close("})"); code.close("`);"); @@ -1198,19 +1067,11 @@ impl<'a> JSifier<'a> { code } - fn jsify_toinflight_method(&mut self, resource_name: &Symbol, captured_fields: &[String]) -> CodeMaker { + fn jsify_to_inflight_method(&self, resource_name: &Symbol, ctx: &JSifyContext) -> CodeMaker { let mut code = CodeMaker::default(); code.open("_toInflight() {"); - // create an inflight client for each "child" object - for inner_member_name in captured_fields { - code.line(format!( - "const {}_client = this._lift(this.{});", - inner_member_name, inner_member_name, - )); - } - code.open(format!("return {STDLIB}.core.NodeJsCode.fromInline(`")); code.open("(await (async () => {"); @@ -1222,8 +1083,10 @@ impl<'a> JSifier<'a> { code.open(format!("const client = new {}Client({{", resource_name.name)); - for inner_member_name in captured_fields { - code.line(format!("{inner_member_name}: ${{{inner_member_name}_client}},")); + if let Some(lifts) = &ctx.lifts { + for (token, obj) in lifts.lifted_fields() { + code.line(format!("{token}: ${{this._lift({obj})}},")); + } } code.close("});"); @@ -1241,56 +1104,14 @@ impl<'a> JSifier<'a> { code } - /// Scan all inflight methods in a class and extract the names of all the types and variables that - /// are defined outside of this method. - fn scan_captures( - &mut self, - class: &AstClass, - inflight_methods: &[&(Symbol, FunctionDefinition)], - ) -> (IndexMap, TypeRef>, IndexSet) { - let mut types = indexmap![]; - let mut vars = indexset![]; - - for (_, m) in inflight_methods { - if let FunctionBody::Statements(scope) = &m.body { - let mut visitor = CaptureScanner::new(scope); - visitor.scan(); - - types.extend(visitor.captured_types); - vars.extend(visitor.captured_vars); - } - } - // Remove myself from the list of referenced preflight types because I don't need to import myself - types.remove(&vec![class.name.clone()]); - - (types, vars) - } - // Write a class's inflight to a file - fn jsify_class_inflight( - &mut self, - env: &SymbolEnv, - class: &AstClass, - lifted_fields: &[String], - inflight_methods: &[&(Symbol, FunctionDefinition)], - captures: &[String], - ctx: &JSifyContext, - ) { - // Handle parent class: Need to call super and pass its captured fields (we assume the parent client is already written) - let mut lifted_by_parent = vec![]; - if let Some(parent) = &class.parent { - let parent_udt = resolve_udt_from_expr(parent).unwrap(); - if let Ok(parent_type) = resolve_user_defined_type(&parent_udt, env, 0) { - lifted_by_parent.extend(self.get_lifted_fields(parent_type)); - } - } - - // Get the fields that are lifted by this class but not by its parent, they will be initialized - // in the generated constructor - let my_captures = lifted_fields - .iter() - .filter(|name| !lifted_by_parent.iter().any(|n| n == *name)) - .collect_vec(); + fn jsify_class_inflight(&self, class: &AstClass, ctx: &mut JSifyContext) -> CodeMaker { + let mut ctx = JSifyContext { + phase: Phase::Inflight, + in_json: false, + files: ctx.files, + lifts: ctx.lifts, + }; let mut class_code = CodeMaker::default(); @@ -1298,7 +1119,7 @@ impl<'a> JSifier<'a> { class_code.open(format!( "class {name}{} {{", if let Some(parent) = &class.parent { - format!(" extends {}", self.jsify_expression(&parent, ctx)) + format!(" extends {}", self.jsify_expression(&parent, &mut ctx)) } else { "".to_string() } @@ -1306,141 +1127,104 @@ impl<'a> JSifier<'a> { // if this is a preflight class, emit the binding constructor if class.phase == Phase::Preflight { - class_code.open(format!( - "{JS_CONSTRUCTOR}({{ {} }}) {{", - lifted_fields - .iter() - .map(|name| { name.clone() }) - .collect_vec() - .join(", ") - )); + self.jsify_inflight_binding_constructor(class, &mut class_code, &ctx); + } - if class.parent.is_some() { - class_code.line(format!( - "super({{{}}});", - lifted_by_parent - .iter() - .map(|name| name.clone()) - .collect_vec() - .join(", ") - )); - } + for def in class.inflight_methods(false) { + class_code.line(self.jsify_function(Some(class), def, &mut ctx)); + } - for name in &my_captures { - class_code.line(format!("this.{} = {};", name, name)); + // emit the $inflight_init function (if it has a body). + if let FunctionBody::Statements(s) = &class.inflight_initializer.body { + if !s.statements.is_empty() { + class_code.line(self.jsify_function(Some(class), &class.inflight_initializer, &mut ctx)); } + } - // if this class has a "handle" method, we are going to turn it into a callable function - // so that instances of this class can also be called like regular functions - if inflight_methods.iter().any(|(name, _)| name.name == HANDLE_METHOD_NAME) { - class_code.line(format!("const $obj = (...args) => this.{HANDLE_METHOD_NAME}(...args);")); - class_code.line("Object.setPrototypeOf($obj, this);"); - class_code.line("return $obj;"); - } + class_code.close("}"); + class_code + } - class_code.close("}"); - } + fn emit_inflight_file(&self, class: &AstClass, inflight_class_code: CodeMaker, ctx: &mut JSifyContext) { + let name = &class.name.name; + let mut code = CodeMaker::default(); - let inflight_init_name = if class.phase == Phase::Preflight { - CLASS_INFLIGHT_INIT_NAME + let inputs = if let Some(lifts) = &ctx.lifts { + lifts.captures().iter().map(|c| c.token.clone()).join(", ") } else { - JS_CONSTRUCTOR + Default::default() }; - class_code.add_code(self.jsify_function( - Some(inflight_init_name), - &class.inflight_initializer, - true, - &JSifyContext { - in_json: ctx.in_json, - phase: class.inflight_initializer.signature.phase, - }, - )); - - for (name, def) in inflight_methods { - class_code.add_code(self.jsify_function( - Some(&name.name), - def, - true, - &JSifyContext { - in_json: ctx.in_json, - phase: def.signature.phase, - }, - )); - } - - class_code.close("}"); - - // export the main class from this file - let mut code = CodeMaker::default(); - let inputs = captures.join(", "); code.open(format!("module.exports = function({{ {inputs} }}) {{")); - code.add_code(class_code); + code.add_code(inflight_class_code); code.line(format!("return {name};")); code.close("}"); - match self.emitted_files.add_file(inflight_filename(class), code.to_string()) { + // emit the inflight class to a file + match ctx.files.add_file(inflight_filename(class), code.to_string()) { Ok(()) => {} Err(err) => report_diagnostic(err.into()), } } - /// Get the type and capture info for fields that are captured in the client of the given resource - /// Returns a map from method name to a map from field name to a set of operations - fn find_inflight_references( - &mut self, - resource_class: &AstClass, - free_vars: &IndexSet, - ) -> BTreeMap>> { - let inflight_methods = resource_class - .methods - .iter() - .filter(|(_, m)| m.signature.phase == Phase::Inflight); + fn jsify_inflight_binding_constructor(&self, class: &AstClass, class_code: &mut CodeMaker, ctx: &JSifyContext) { + // Get the fields that are lifted by this class but not by its parent, they will be initialized + // in the generated constructor + let lifted_fields = if let Some(lifts) = &ctx.lifts { + lifts.lifted_fields().keys().map(|f| f.clone()).collect_vec() + } else { + vec![] + }; - let mut result = BTreeMap::new(); + let parent_fields = if let Some(parent) = &class.parent { + let parent_type = self.get_expr_type(parent); + if let Some(parent_lifts) = &parent_type.as_class().unwrap().lifts { + parent_lifts.lifted_fields().keys().map(|f| f.clone()).collect_vec() + } else { + vec![] + } + } else { + vec![] + }; - for (method_name, function_def) in inflight_methods { - // visit statements of method and find all references to fields ("this.xxx") - let visitor = FieldReferenceVisitor::new(self.types, &function_def, free_vars); - let refs = visitor.find_refs(); + class_code.open(format!( + "{JS_CONSTRUCTOR}({{ {} }}) {{", + lifted_fields + .iter() + .merge(parent_fields.iter()) + .map(|token| { token.clone() }) + .collect_vec() + .join(", ") + )); - // add the references to the result - result.insert(method_name.name.clone(), refs); + if class.parent.is_some() { + class_code.line(format!("super({{ {} }});", parent_fields.join(", "))); } - // Also add field rerferences from the inflight initializer - let visitor = FieldReferenceVisitor::new(self.types, &resource_class.inflight_initializer, free_vars); - let refs = visitor.find_refs(); - - result.insert(CLASS_INFLIGHT_INIT_NAME.to_string(), refs); - - return result; - } + for token in &lifted_fields { + class_code.line(format!("this.{} = {};", token, token)); + } - // Get the type and capture info for fields that are captured in the client of the given resource - fn get_lifted_fields(&self, resource_type: TypeRef) -> Vec { - if let Some(resource_class) = resource_type.as_class() { - resource_class - .env - .iter(true) - .filter(|(_, kind, _)| { - let var = kind.as_variable().unwrap(); - // We capture preflight non-reassignable fields - var.phase != Phase::Inflight && var.type_.is_capturable() - }) - .map(|(name, ..)| name) - .collect_vec() - } else { - vec![] + // if this class has a "handle" method, we are going to turn it into a callable function + // so that instances of this class can also be called like regular functions + if let Some(handle) = class.closure_handle_method() { + class_code.line(format!( + "const $obj = (...args) => this.{}(...args);", + handle.name.clone().unwrap() + )); + class_code.line("Object.setPrototypeOf($obj, this);"); + class_code.line("return $obj;"); } + + class_code.close("}"); } fn jsify_register_bind_method( &self, class: &AstClass, - refs: &BTreeMap>>, class_type: TypeRef, bind_method_kind: BindMethod, + ctx: &JSifyContext, ) -> CodeMaker { let mut bind_method = CodeMaker::default(); let (modifier, bind_method_name) = match bind_method_kind { @@ -1449,30 +1233,39 @@ impl<'a> JSifier<'a> { }; let class_name = class.name.to_string(); - let refs = refs + + let lifts_per_method = if let Some(lifts) = &ctx.lifts { + lifts.lifts_per_method() + } else { + BTreeMap::default() + }; + + let lifts = lifts_per_method .iter() .filter(|(m, _)| { let var_kind = class_type .as_class() .unwrap() .get_method(&m.as_str().into()) - .expect(&format!("method {m} doesn't exist in {class_name}")) + .expect(&format!("method \"{m}\" doesn't exist in {class_name}")) .kind; let is_static = matches!(var_kind, VariableKind::StaticMember); (*m == CLASS_INFLIGHT_INIT_NAME || !is_static) ^ (matches!(bind_method_kind, BindMethod::Type)) }) .collect_vec(); - // Skip jsifying this method if there are no references (in this case we'll use super's register bind method) - if refs.is_empty() { + // Skip jsifying this method if there are no lifts (in this case we'll use super's register bind method) + if lifts.is_empty() { return bind_method; } bind_method.open(format!("{modifier}{bind_method_name}(host, ops) {{")); - for (method_name, method_refs) in refs { + for (method_name, method_lifts) in lifts { bind_method.open(format!("if (ops.includes(\"{method_name}\")) {{")); - for (field, ops) in method_refs { - let ops_strings = ops.iter().map(|op| format!("\"{}\"", op)).join(", "); + for lift in method_lifts { + let ops_strings = lift.ops.iter().map(|op| format!("\"{}\"", op)).join(", "); + let field = lift.code.clone(); + bind_method.line(format!( "{class_name}._registerBindObject({field}, host, [{ops_strings}]);", )); @@ -1483,554 +1276,10 @@ impl<'a> JSifier<'a> { bind_method.close("}"); bind_method } - - fn add_inflight_init_refs( - &self, - refs: &mut BTreeMap>>, - lifted_fields: &[String], - free_vars: &IndexSet, - ) { - let init_refs_entry = refs.entry(CLASS_INFLIGHT_INIT_NAME.to_string()).or_default(); - - // All "lifted" fields are needed in the inflight init method - for field in lifted_fields { - init_refs_entry.entry(format!("this.{field}")).or_default(); - } - - // All free variables are needed in the inflight init method - for free_var in free_vars { - init_refs_entry.entry(free_var.clone()).or_default(); - } - } -} - -/// Analysizes a resource inflight method and returns a list of fields that are referenced from the -/// method and which operations are performed on them. -struct FieldReferenceVisitor<'a> { - types: &'a Types, - - /// The key is field name, value is a list of operations performed on this field - references: BTreeMap>, - - /// The resource type's symbol env (used to resolve field types) - function_def: &'a FunctionDefinition, - - /// A list of free variables preloaded into the visitor. Whenever the visitor encounters a - /// reference to a free variable, it will be added to list of references since the - /// resource needs to bind to it. - free_vars: &'a IndexSet, - - /// The current symbol env, option just so we can initialize it to None - env: Option, - - /// The current statement index - statement_index: usize, -} - -impl<'a> FieldReferenceVisitor<'a> { - pub fn new(types: &'a Types, function_def: &'a FunctionDefinition, free_vars: &'a IndexSet) -> Self { - Self { - types, - references: BTreeMap::new(), - function_def, - env: None, - free_vars, - statement_index: 0, - } - } - - pub fn find_refs(mut self) -> BTreeMap> { - if let FunctionBody::Statements(statements) = &self.function_def.body { - self.visit_scope(statements); - } - self.references - } -} - -impl<'ast> Visit<'ast> for FieldReferenceVisitor<'ast> { - fn visit_scope(&mut self, node: &'ast Scope) { - let backup_env = self.env; - self.env = Some(node.env.borrow().as_ref().unwrap().get_ref()); - visit::visit_scope(self, node); - self.env = backup_env; - } - - fn visit_stmt(&mut self, node: &'ast Stmt) { - self.statement_index = node.idx; - visit::visit_stmt(self, node); - } - - fn visit_expr(&mut self, node: &'ast Expr) { - let parts = self.analyze_expr(node); - - let is_field_reference = match parts.first() { - Some(first) => first.text == "this" && parts.len() > 1, - None => false, - }; - - let is_free_var = match parts.first() { - // TODO: chnge this "==" to make sure first.symbol is the same variable definition as something in free_vars - // todo this i'll need to have a "unique id" on the variable definition stored in the environment and then - // do a lookup for first.symbol and compare the id's - Some(first) => self.free_vars.iter().any(|v| *v == first.text), - None => false, - }; - - let is_type_reference = match parts.first() { - Some(first) => matches!(first.kind, ComponentKind::ClassType(_)), - None => false, - }; - - if !is_field_reference && !is_free_var && !is_type_reference { - visit::visit_expr(self, node); - return; - } - - let mut index = if is_field_reference { - // we know i[0] is "this" and that we have at least 2 parts - 1 - } else { - 0 - }; - - // iterate over the components of the expression and determine - // what are we capturing from preflight. - let mut capture = vec![]; - - while index < parts.len() { - let curr = parts.get(index).unwrap(); - - match &curr.kind { - ComponentKind::Member(variable) => { - // we have lift off (reached an inflight component)! break our search. - if variable.phase == Phase::Inflight { - break; - } - - // now we need to verify that the component can be captured. - // (2) capturable type (immutable/resource). - - // if this type is not capturable, bail out - if !variable.type_.is_capturable() { - report_diagnostic(Diagnostic { - message: format!( - "Cannot capture field '{curr}' with non-capturable type '{}'", - variable.type_ - ), - span: Some(curr.span.clone()), - }); - - return; - } - - // okay, so we have a non-reassignable, capturable type. - // one more special case is collections. we currently only support - // collections which do not include resources because we cannot - // qualify the capture. - if let Some(inner_type) = variable.type_.collection_item_type() { - if inner_type.is_preflight_class() { - report_diagnostic(Diagnostic { - message: format!( - "Capturing collection of preflight classes is not supported yet (type is '{}')", - variable.type_, - ), - span: Some(curr.span.clone()), - }); - - return; - } - } - - // accumulate "curr" into capture - capture.push(curr); - index = index + 1; - - // if "curr" is a collection, break here because the following - // components are going to be simple identifiers (TODO: is this a bug in - // how we model the API of collections?) - if variable.type_.collection_item_type().is_some() { - break; - } - } - ComponentKind::ClassType(_) => { - capture.push(curr); - index = index + 1; - } - ComponentKind::Unsupported => { - report_diagnostic(Diagnostic { - message: format!("Unsupported component \"{}\"", curr.text), - span: Some(curr.span.clone()), - }); - return; - } - } - } - - // if capture is empty, it means this is a reference to an inflight field, so we can just move - // on - if capture.is_empty() { - return; - } - - // now that we have "capture", the rest of the expression - // is the "qualification" of the capture - let binding = parts.iter().collect::>(); - let qualification = binding.split_at(index).1.iter(); - - let fmt = |x: Iter<&Component>| x.map(|f| f.text.to_string()).collect_vec(); - let mut key = fmt(capture.iter()).join("."); - if is_field_reference { - key = format!("this.{}", key); - } - - if let Some(c) = capture.last() { - if let ComponentKind::Member(v) = &c.kind { - // if our last captured component is a non-handler preflight class and we don't have a - // qualification for it, it's currently an error. - if v.type_.is_preflight_class() && !v.type_.is_handler_preflight_class() && qualification.len() == 0 { - report_diagnostic(Diagnostic { - message: format!( - "Unable to qualify which operations are performed on '{}' of type '{}'. This is not supported yet.", - key, v.type_, - ), - span: Some(node.span.clone()), - }); - - return; - } - - // if this reference refers to an inflight function or handler resource, - // we need to give permission to the "handle" operation - if v.type_.is_inflight_function() || v.type_.is_handler_preflight_class() { - self - .references - .entry(key) - .or_default() - .insert(HANDLE_METHOD_NAME.to_string()); - return; - } - } - } - - let ops = fmt(qualification); - - self.references.entry(key).or_default().extend(ops); - } -} - -#[derive(Clone, Debug)] -struct Component { - text: String, - span: WingSpan, - kind: ComponentKind, -} - -#[derive(Clone, Debug)] -enum ComponentKind { - Member(VariableInfo), - ClassType(TypeRef), - Unsupported, -} - -impl Display for Component { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.text) - } -} - -impl<'a> FieldReferenceVisitor<'a> { - fn analyze_expr(&self, node: &'a Expr) -> Vec { - let ExprKind::Reference(ref_expr) = &node.kind else { - return vec![]; - }; - - match ref_expr { - Reference::Identifier(x) => { - let env = self.env.unwrap(); - - let lookup = env.lookup_ext(&x, Some(self.statement_index)); - - // if the reference is already defined later in this scope, skip it - if matches!(lookup, LookupResult::DefinedLater) { - return vec![]; - } - - let id_name = x.name.clone(); - let id_span = x.span.clone(); - - let LookupResult::Found(kind, _) = lookup else { - return vec![Component { - text: id_name, - span: id_span, - kind: ComponentKind::Unsupported, - }]; - }; - - let Some(var) = kind.as_variable() else { - return vec![Component { - text: id_name, - span: id_span, - kind: ComponentKind::Unsupported, - }]; - }; - - // If the reference isn't a preflight (lifted) variable then skip it - if var.phase != Phase::Preflight { - return vec![]; - } - - return vec![Component { - text: id_name, - span: id_span, - kind: ComponentKind::Member(var), - }]; - } - Reference::TypeReference(type_) => { - let env = self.env.unwrap(); - - // Get the type we're accessing a member of - let Ok(t) = resolve_user_defined_type(type_, &env, self.statement_index) else { - return vec![]; - }; - - // If the type we're referencing isn't a preflight class then skip it - if t.as_preflight_class().is_none() { - return vec![]; - }; - - return vec![Component { - text: format!("{type_}"), - span: type_.span.clone(), - kind: ComponentKind::ClassType(t), - }]; - } - Reference::InstanceMember { - object, - property, - optional_accessor: _optional_chain, - } => { - let obj_type = self.types.get_expr_type(object).unwrap(); - let prop = if let Some(component_kind) = Self::determine_component_kind_from_type(obj_type, property) { - vec![Component { - text: property.name.clone(), - span: property.span.clone(), - kind: component_kind, - }] - } else { - vec![] - }; - - let obj = self.analyze_expr(&object); - return [obj, prop].concat(); - } - Reference::TypeMember { typeobject, property } => { - let obj = self.analyze_expr(&typeobject); - - let Some(first) = obj.first() else { - return vec![]; - }; - - let ComponentKind::ClassType(t) = first.kind else { - return vec![]; - }; - - // If the type we're referencing isn't a preflight class then skip it - let Some(class) = t.as_preflight_class() else { - return vec![]; - }; - - // To obtain information about the variable we're referencing (like its type and - // whether it's reassignable), we look it up in the class's env. - let var = class - .env - .lookup(&property, None) - .expect("lookup") - .as_variable() - .expect("variable"); - - let prop = vec![Component { - text: property.name.clone(), - span: property.span.clone(), - kind: ComponentKind::Member(var), - }]; - - [obj, prop].concat() - } - } - } - - fn determine_component_kind_from_type(obj_type: UnsafeRef, property: &Symbol) -> Option { - match &*obj_type { - // Invalid cases, should be caught by typechecker - Type::Void | Type::Function(_) | Type::Unresolved => None, - - // all fields / methods / values of these types are phase-independent so we can skip them - Type::Anything - | Type::Number - | Type::String - | Type::Duration - | Type::Boolean - | Type::Json - | Type::MutJson - | Type::Nil - | Type::Enum(_) => None, - - Type::Optional(t) => Self::determine_component_kind_from_type(*t, property), - - // TODO: collection types are unsupported for now - Type::Array(_) | Type::MutArray(_) | Type::Map(_) | Type::MutMap(_) | Type::Set(_) | Type::MutSet(_) => { - Some(ComponentKind::Unsupported) - } - - Type::Class(cls) => Some(ComponentKind::Member(cls.env.lookup(&property, None)?.as_variable()?)), - Type::Interface(iface) => Some(ComponentKind::Member(iface.env.lookup(&property, None)?.as_variable()?)), - Type::Struct(st) => Some(ComponentKind::Member(st.env.lookup(&property, None)?.as_variable()?)), - } - } -} - -/// Visitor that finds all the types and variables used within an inflight method but defined in its -/// parent environment -struct CaptureScanner<'a> { - /// Set of user types referenced inside the method - captured_types: IndexMap, TypeRef>, - - /// The set of free variables referenced by the method - captured_vars: IndexSet, - - /// The root scope of the function we're analyzing - function_scope: &'a Scope, - - /// The method env, used to lookup the type - method_env: SymbolEnvRef, - - /// The current environment (tracked via the visitor) - current_env: SymbolEnvRef, - - /// The index of the last visited statement. - current_index: usize, -} - -impl<'a> CaptureScanner<'a> { - pub fn new(function_scope: &'a Scope) -> Self { - let env = function_scope.env.borrow().as_ref().unwrap().get_ref(); - Self { - captured_types: IndexMap::new(), - captured_vars: IndexSet::new(), - function_scope, - method_env: env, - current_env: env, - current_index: 0, - } - } - - pub fn scan(&mut self) { - self.visit_scope(self.function_scope); - } - - fn consider_reference(&mut self, path: &Vec) { - let fullname = path.iter().map(|s| s.name.clone()).collect_vec().join("."); - - let lookup = self - .current_env - .lookup_nested(&path.iter().collect_vec(), Some(self.current_index)); - - // if the symbol is defined later in the current environment, it means we can't capture a - // reference to a symbol with the same name from a parent so bail out. - if let LookupResult::DefinedLater = lookup { - let sym = path.first().unwrap(); - - report_diagnostic(Diagnostic { - span: Some(sym.span.clone()), - message: format!( - "Cannot capture symbol \"{fullname}\" because it is shadowed by another symbol with the same name" - ), - }); - - return; - } - - // any other lookup failure is likely a an invalid reference so we can skip it - let LookupResult::Found(kind, symbol_info) = lookup else { - return; - }; - - // now, we need to determine if the environment this symbol is defined in is a parent of the - // method's environment. if it is, we need to capture it. - if symbol_info.env.is_same(&self.method_env) || symbol_info.env.is_child_of(&self.method_env) { - return; - } - - match kind { - SymbolKind::Type(t) => { - self.captured_types.insert(path.clone(), *t); - } - SymbolKind::Variable(var) => { - // skip macro functions (like "log" and "assert") - if let Type::Function(f) = &*var.type_ { - if f.js_override.is_some() { - return; - } - } - - self.captured_vars.insert(fullname); - } - // Namespaces are not captured as they are not actually valid references - // The existence of this reference will have already caused an error in the type checker - SymbolKind::Namespace(_) => {} - } - } -} - -impl<'ast> Visit<'ast> for CaptureScanner<'ast> { - fn visit_reference(&mut self, node: &'ast Reference) { - match node { - Reference::Identifier(symb) => { - // skip "this" - if symb.name == "this" { - return; - } - - self.consider_reference(&vec![symb.clone()]); - } - - Reference::TypeReference(t) => self.consider_reference(&t.full_path()), - - // this is the case of "object.property" (or `Type.property`). if we need to capture "object", - // it will be captured as an identifier, so we can skip it here. - Reference::TypeMember { .. } => {} - Reference::InstanceMember { .. } => {} - } - - visit::visit_reference(self, node); - } - - fn visit_scope(&mut self, node: &'ast Scope) { - let backup_env = self.current_env; - self.current_env = node.env.borrow().as_ref().unwrap().get_ref(); - visit::visit_scope(self, node); - self.current_env = backup_env; - } - - fn visit_stmt(&mut self, node: &'ast Stmt) { - self.current_index = node.idx; - visit::visit_stmt(self, node); - } } fn inflight_filename(class: &AstClass) -> String { - format!("inflight.{}.js", class.name.name) -} - -fn jsify_type_name(t: &Vec, phase: Phase) -> String { - // if we are inside an inflight context, we need to mangle the type name so we can capture it - let p = t.iter().map(|f| f.name.clone()).collect_vec(); - - if phase == Phase::Inflight { - p.join("_") - } else { - p.join(".") - } + format!("./inflight.{}.js", class.name.name) } fn lookup_span(span: &WingSpan, files: &Files) -> String { @@ -2084,20 +1333,3 @@ fn escape_javascript_string(s: &str) -> String { result } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_escape_javascript_string() { - assert_eq!(escape_javascript_string("hello"), String::from("hello")); - assert_eq!(escape_javascript_string("hello\nworld"), String::from("hello\\nworld")); - assert_eq!(escape_javascript_string("hello\rworld"), String::from("hello\\rworld")); - assert_eq!(escape_javascript_string("hello\tworld"), String::from("hello\\tworld")); - assert_eq!(escape_javascript_string("hello\\world"), String::from("hello\\\\world")); - assert_eq!(escape_javascript_string("hello'world"), String::from("hello\\'world")); - assert_eq!(escape_javascript_string("hello\"world"), String::from("hello\\\"world")); - assert_eq!(escape_javascript_string("hello\0world"), String::from("hello\\0world")); - } -} diff --git a/libs/wingc/src/jsify/snapshots/access_methods_and_properties_on_collections.snap b/libs/wingc/src/jsify/snapshots/access_methods_and_properties_on_collections.snap new file mode 100644 index 00000000000..dec2178068f --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/access_methods_and_properties_on_collections.snap @@ -0,0 +1,103 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let x = [1,2,3]; + let y = ["hello"]; + + test "test" { + assert(x.length == 3); + assert(y.at(0) == "hello"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $_y_at_0__, $x_length }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: x.length == 3")})(($x_length === 3))}; + {((cond) => {if (!cond) throw new Error("assertion failed: y.at(0) == \"hello\"")})(($_y_at_0__ === "hello"))}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $_y_at_0__: ${context._lift((y.at(0)))}, + $x_length: ${context._lift(x.length)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject((y.at(0)), host, []); + $Closure1._registerBindObject(x.length, host, []); + } + super._registerBind(host, ops); + } + } + const x = Object.freeze([1, 2, 3]); + const y = Object.freeze(["hello"]); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/access_property_on_primitive.snap b/libs/wingc/src/jsify/snapshots/access_property_on_primitive.snap new file mode 100644 index 00000000000..c720b29e44c --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/access_property_on_primitive.snap @@ -0,0 +1,97 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let s = "hello"; + + test "test" { + assert(s.length == 5); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $s_length }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: s.length == 5")})(($s_length === 5))}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $s_length: ${context._lift(s.length)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(s.length, host, []); + } + super._registerBind(host, ops); + } + } + const s = "hello"; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/access_property_on_value_returned_from_collection.snap b/libs/wingc/src/jsify/snapshots/access_property_on_value_returned_from_collection.snap new file mode 100644 index 00000000000..bc386b7479b --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/access_property_on_value_returned_from_collection.snap @@ -0,0 +1,97 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let s = { "hello" => "123" }; + + test "test" { + assert(s.get("hello").length == 3); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $_s___hello___length }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: s.get(\"hello\").length == 3")})(($_s___hello___length === 3))}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $_s___hello___length: ${context._lift((s)["hello"].length)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject((s)["hello"].length, host, []); + } + super._registerBind(host, ops); + } + } + const s = Object.freeze({"hello":"123"}); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/base_class.snap b/libs/wingc/src/jsify/snapshots/base_class.snap new file mode 100644 index 00000000000..0f2d60783d0 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/base_class.snap @@ -0,0 +1,115 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class A {} + class B extends A {} + +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + constructor({ }) { + } + } + return A; +} +``` + +## inflight.B.js + +```js +module.exports = function({ $A }) { + class B extends A { + constructor({ }) { + super({}); + } + } + return B; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class B extends A { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.B.js")({ + $A: ${context._lift(A)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BClient = ${B._toInflightType(this).text}; + const client = new BClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/base_class_captures_inflight.snap b/libs/wingc/src/jsify/snapshots/base_class_captures_inflight.snap new file mode 100644 index 00000000000..8e2a25490c2 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/base_class_captures_inflight.snap @@ -0,0 +1,146 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let x = "hello"; + + class Base { + inflight bar() { + log(x); + } + } + + class Derived extends Base { + inflight foo() { + this.bar(); + } + } + +``` + +## inflight.Base.js + +```js +module.exports = function({ $x }) { + class Base { + constructor({ }) { + } + async bar() { + {console.log($x)}; + } + } + return Base; +} +``` + +## inflight.Derived.js + +```js +module.exports = function({ $Base }) { + class Derived extends $Base { + constructor({ }) { + super({ }); + } + async foo() { + (await this.bar()); + } + } + return Derived; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Base extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("bar", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Base.js")({ + $x: ${context._lift(x)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BaseClient = ${Base._toInflightType(this).text}; + const client = new BaseClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("bar")) { + Base._registerBindObject(x, host, []); + } + super._registerBind(host, ops); + } + } + class Derived extends Base { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Derived.js")({ + $Base: ${context._lift(Base)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const DerivedClient = ${Derived._toInflightType(this).text}; + const client = new DerivedClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foo")) { + Derived._registerBindObject(this, host, ["bar"]); + } + super._registerBind(host, ops); + } + } + const x = "hello"; + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/base_class_captures_preflight.snap b/libs/wingc/src/jsify/snapshots/base_class_captures_preflight.snap new file mode 100644 index 00000000000..8510a18c995 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/base_class_captures_preflight.snap @@ -0,0 +1,133 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let x = "hello"; + + class Base { + bar() { + log(x); + } + } + + class Derived extends Base { + foo() { + this.bar(); + } + } + +``` + +## inflight.Base.js + +```js +module.exports = function({ }) { + class Base { + constructor({ }) { + } + } + return Base; +} +``` + +## inflight.Derived.js + +```js +module.exports = function({ $Base }) { + class Derived extends $Base { + constructor({ }) { + super({ }); + } + } + return Derived; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Base extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + bar() { + {console.log(x)}; + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Base.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BaseClient = ${Base._toInflightType(this).text}; + const client = new BaseClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class Derived extends Base { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + foo() { + (this.bar()); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Derived.js")({ + $Base: ${context._lift(Base)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const DerivedClient = ${Derived._toInflightType(this).text}; + const client = new DerivedClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + const x = "hello"; + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/base_class_lift_indirect.snap b/libs/wingc/src/jsify/snapshots/base_class_lift_indirect.snap new file mode 100644 index 00000000000..931c36ee9c0 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/base_class_lift_indirect.snap @@ -0,0 +1,155 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + class Base { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + + inflight put() { + this.b.put("hello", "world"); + this.b.list(); + } + } + + class Derived extends Base { + inflight foo() { + this.put(); + } + } + +``` + +## inflight.Base.js + +```js +module.exports = function({ }) { + class Base { + constructor({ $this_b }) { + this.$this_b = $this_b; + } + async put() { + (await this.$this_b.put("hello","world")); + (await this.$this_b.list()); + } + } + return Base; +} +``` + +## inflight.Derived.js + +```js +module.exports = function({ $Base }) { + class Derived extends $Base { + constructor({ $this_b }) { + super({ $this_b }); + } + async foo() { + (await this.put()); + } + } + return Derived; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Base extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("put", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Base.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BaseClient = ${Base._toInflightType(this).text}; + const client = new BaseClient({ + $this_b: ${this._lift(this.b)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("put")) { + Base._registerBindObject(this.b, host, ["list", "put"]); + } + super._registerBind(host, ops); + } + } + class Derived extends Base { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Derived.js")({ + $Base: ${context._lift(Base)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const DerivedClient = ${Derived._toInflightType(this).text}; + const client = new DerivedClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foo")) { + Derived._registerBindObject(this, host, ["put"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/base_class_with_fields_inflight.snap b/libs/wingc/src/jsify/snapshots/base_class_with_fields_inflight.snap new file mode 100644 index 00000000000..1566fdc03fe --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/base_class_with_fields_inflight.snap @@ -0,0 +1,156 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Base { + inflight f: str; + inflight init() { + this.f = "hello"; + } + } + + class Derived extends Base { + inflight g: str; + inflight init() { + this.g = "world"; + } + + inflight foo() { + this.f; + this.g; + } + } + +``` + +## inflight.Base.js + +```js +module.exports = function({ }) { + class Base { + constructor({ }) { + } + async $inflight_init() { + this.f = "hello"; + } + } + return Base; +} +``` + +## inflight.Derived.js + +```js +module.exports = function({ $Base }) { + class Derived extends $Base { + constructor({ }) { + super({ }); + } + async foo() { + this.f; + this.g; + } + async $inflight_init() { + this.g = "world"; + } + } + return Derived; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Base extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init", "f"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Base.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BaseClient = ${Base._toInflightType(this).text}; + const client = new BaseClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + Base._registerBindObject(this, host, ["f"]); + } + super._registerBind(host, ops); + } + } + class Derived extends Base { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init", "g"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Derived.js")({ + $Base: ${context._lift(Base)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const DerivedClient = ${Derived._toInflightType(this).text}; + const client = new DerivedClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + Derived._registerBindObject(this, host, ["g"]); + } + if (ops.includes("foo")) { + Derived._registerBindObject(this, host, ["f", "g"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/base_class_with_fields_preflight.snap b/libs/wingc/src/jsify/snapshots/base_class_with_fields_preflight.snap new file mode 100644 index 00000000000..79090ab9627 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/base_class_with_fields_preflight.snap @@ -0,0 +1,137 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Base { + f: str; + init() { + this.f = "hello"; + } + } + + class Derived extends Base { + g: str; + init() { + this.g = "world"; + } + + foo() { + this.f; + this.g; + } + } + +``` + +## inflight.Base.js + +```js +module.exports = function({ }) { + class Base { + constructor({ }) { + } + } + return Base; +} +``` + +## inflight.Derived.js + +```js +module.exports = function({ $Base }) { + class Derived extends $Base { + constructor({ }) { + super({ }); + } + } + return Derived; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Base extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.f = "hello"; + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Base.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BaseClient = ${Base._toInflightType(this).text}; + const client = new BaseClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class Derived extends Base { + constructor(scope, id, ) { + super(scope, id); + this.g = "world"; + this._addInflightOps("$inflight_init"); + } + foo() { + this.f; + this.g; + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Derived.js")({ + $Base: ${context._lift(Base)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const DerivedClient = ${Derived._toInflightType(this).text}; + const client = new DerivedClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/base_class_with_lifted_field_object.snap b/libs/wingc/src/jsify/snapshots/base_class_with_lifted_field_object.snap new file mode 100644 index 00000000000..6a0fb4361e1 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/base_class_with_lifted_field_object.snap @@ -0,0 +1,140 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + class Base { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + } + + class Derived extends Base { + inflight foo() { + this.b.put("hello", "world"); + } + } + +``` + +## inflight.Base.js + +```js +module.exports = function({ }) { + class Base { + constructor({ }) { + } + } + return Base; +} +``` + +## inflight.Derived.js + +```js +module.exports = function({ $Base }) { + class Derived extends $Base { + constructor({ $this_b }) { + super({ }); + this.$this_b = $this_b; + } + async foo() { + (await this.$this_b.put("hello","world")); + } + } + return Derived; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Base extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Base.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BaseClient = ${Base._toInflightType(this).text}; + const client = new BaseClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class Derived extends Base { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Derived.js")({ + $Base: ${context._lift(Base)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const DerivedClient = ${Derived._toInflightType(this).text}; + const client = new DerivedClient({ + $this_b: ${this._lift(this.b)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foo")) { + Derived._registerBindObject(this.b, host, ["put"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/base_class_with_lifted_fields.snap b/libs/wingc/src/jsify/snapshots/base_class_with_lifted_fields.snap new file mode 100644 index 00000000000..5646d6886ed --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/base_class_with_lifted_fields.snap @@ -0,0 +1,140 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let x = "hello"; + + class Base { + f: str; + init() { + this.f = x; + } + } + + class Derived extends Base { + inflight foo() { + this.f; + } + } + +``` + +## inflight.Base.js + +```js +module.exports = function({ }) { + class Base { + constructor({ }) { + } + } + return Base; +} +``` + +## inflight.Derived.js + +```js +module.exports = function({ $Base }) { + class Derived extends $Base { + constructor({ $this_f }) { + super({ }); + this.$this_f = $this_f; + } + async foo() { + this.$this_f; + } + } + return Derived; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Base extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.f = x; + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Base.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BaseClient = ${Base._toInflightType(this).text}; + const client = new BaseClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class Derived extends Base { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Derived.js")({ + $Base: ${context._lift(Base)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const DerivedClient = ${Derived._toInflightType(this).text}; + const client = new DerivedClient({ + $this_f: ${this._lift(this.f)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foo")) { + Derived._registerBindObject(this.f, host, []); + } + super._registerBind(host, ops); + } + } + const x = "hello"; + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/builtins.snap b/libs/wingc/src/jsify/snapshots/builtins.snap new file mode 100644 index 00000000000..329f86b923b --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/builtins.snap @@ -0,0 +1,87 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + log("hello"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log("hello")}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/call_static_inflight_from_static_inflight.snap b/libs/wingc/src/jsify/snapshots/call_static_inflight_from_static_inflight.snap new file mode 100644 index 00000000000..dd982c432cf --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/call_static_inflight_from_static_inflight.snap @@ -0,0 +1,131 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class A { + static inflight foo() { log("hello"); } + } + + inflight class B { + static bar() { + A.foo(); + } + } + +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + constructor({ }) { + } + static async foo() { + {console.log("hello")}; + } + } + return A; +} +``` + +## inflight.B.js + +```js +module.exports = function({ $A }) { + class B { + static async bar() { + (await $A.foo()); + } + } + return B; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class B extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("bar", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.B.js")({ + $A: ${context._lift(A)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BClient = ${B._toInflightType(this).text}; + const client = new BClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + static _registerTypeBind(host, ops) { + if (ops.includes("bar")) { + B._registerBindObject(A, host, ["foo"]); + } + super._registerTypeBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/calls_methods_on_preflight_object.snap b/libs/wingc/src/jsify/snapshots/calls_methods_on_preflight_object.snap new file mode 100644 index 00000000000..a3afefb8b67 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/calls_methods_on_preflight_object.snap @@ -0,0 +1,101 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let b = new cloud.Bucket(); + + test "test" { + b.put("hello", "world"); + b.list(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $b }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $b.put("hello","world")); + (await $b.list()); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(b, host, ["list", "put"]); + } + super._registerBind(host, ops); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_from_inside_an_inflight_closure.snap b/libs/wingc/src/jsify/snapshots/capture_from_inside_an_inflight_closure.snap new file mode 100644 index 00000000000..6645fd7c9bf --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_from_inside_an_inflight_closure.snap @@ -0,0 +1,102 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring util; + + let foo = "test"; + + test "my test" { + let r = (): str => { return foo; }; + } +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $foo }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const r = async () => { + return $foo; + } + ; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const util = require('@winglang/sdk').util; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $foo: ${context._lift(foo)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(foo, host, []); + } + super._registerBind(host, ops); + } + } + const foo = "test"; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:my test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_identifier_closure_from_preflight_scope.snap b/libs/wingc/src/jsify/snapshots/capture_identifier_closure_from_preflight_scope.snap new file mode 100644 index 00000000000..244b6d62c37 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_identifier_closure_from_preflight_scope.snap @@ -0,0 +1,137 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let foo = inflight () => {}; + test "test" { + foo(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + } + } + return $Closure1; +} +``` + +## inflight.$Closure2.js + +```js +module.exports = function({ $foo }) { + class $Closure2 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $foo()); + } + } + return $Closure2; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure2 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure2.js")({ + $foo: ${context._lift(foo)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure2Client = ${$Closure2._toInflightType(this).text}; + const client = new $Closure2Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure2._registerBindObject(foo, host, ["handle"]); + } + super._registerBind(host, ops); + } + } + const foo = new $Closure1(this,"$Closure1"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure2(this,"$Closure2")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope.snap b/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope.snap new file mode 100644 index 00000000000..172b15d6903 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope.snap @@ -0,0 +1,96 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let x = "hello"; + test "test" { + log(x); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $x }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log($x)}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $x: ${context._lift(x)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(x, host, []); + } + super._registerBind(host, ops); + } + } + const x = "hello"; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope_with_method_call.snap b/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope_with_method_call.snap new file mode 100644 index 00000000000..f8092d4217a --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope_with_method_call.snap @@ -0,0 +1,137 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Foo { + inflight bar() {} + } + + let f = new Foo(); + test "test" { + f.bar(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $f }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $f.bar()); + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + async bar() { + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("bar", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $f: ${context._lift(f)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(f, host, ["bar"]); + } + super._registerBind(host, ops); + } + } + const f = new Foo(this,"Foo"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope_with_nested_object.snap b/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope_with_nested_object.snap new file mode 100644 index 00000000000..f9409533fbf --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope_with_nested_object.snap @@ -0,0 +1,142 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + class Foo { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + } + + let f = new Foo(); + test "test" { + f.b.put("hello", "world"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $f_b }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $f_b.put("hello","world")); + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $f_b: ${context._lift(f.b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(f.b, host, ["put"]); + } + super._registerBind(host, ops); + } + } + const f = new Foo(this,"Foo"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope_with_property.snap b/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope_with_property.snap new file mode 100644 index 00000000000..2613c7f7b41 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_identifier_from_preflight_scope_with_property.snap @@ -0,0 +1,96 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let x = "hello"; + test "test" { + assert(x.length > 0); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $x_length }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: x.length > 0")})(($x_length > 0))}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $x_length: ${context._lift(x.length)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(x.length, host, []); + } + super._registerBind(host, ops); + } + } + const x = "hello"; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_in_keyword_args.snap b/libs/wingc/src/jsify/snapshots/capture_in_keyword_args.snap new file mode 100644 index 00000000000..9e2dd2273ab --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_in_keyword_args.snap @@ -0,0 +1,103 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring util; + + let x = 1s; + + test "test" { + util.waitUntil((): bool => {}, interval: x); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $util_Util, $x }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $util_Util.waitUntil(async () => { + } + ,{ interval: $x })); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const util = require('@winglang/sdk').util; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $util_Util: ${context._lift(util.Util)}, + $x: ${context._lift(x)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(x, host, []); + } + super._registerBind(host, ops); + } + } + const x = (std.Duration.fromSeconds(1)); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_object_with_this_in_name.snap b/libs/wingc/src/jsify/snapshots/capture_object_with_this_in_name.snap new file mode 100644 index 00000000000..37ab9324308 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_object_with_this_in_name.snap @@ -0,0 +1,98 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let bucket_this = new cloud.Bucket(); + let fn = inflight () => { + bucket_this.put("this", "is not a field"); + }; + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $bucket_this }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $bucket_this.put("this","is not a field")); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $bucket_this: ${context._lift(bucket_this)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(bucket_this, host, ["put"]); + } + super._registerBind(host, ops); + } + } + const bucket_this = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + const fn = new $Closure1(this,"$Closure1"); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_token.snap b/libs/wingc/src/jsify/snapshots/capture_token.snap new file mode 100644 index 00000000000..7ef44dd4dc0 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_token.snap @@ -0,0 +1,97 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let api = new cloud.Api(); + test "test" { + log(api.url); + } +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $api_url }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log($api_url)}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $api_url: ${context._lift(api.url)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(api.url, host, []); + } + super._registerBind(host, ops); + } + } + const api = this.node.root.newAbstract("@winglang/sdk.cloud.Api",this,"cloud.Api"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_type_inflight_class_sibling_from_init.snap b/libs/wingc/src/jsify/snapshots/capture_type_inflight_class_sibling_from_init.snap new file mode 100644 index 00000000000..8996123e314 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_type_inflight_class_sibling_from_init.snap @@ -0,0 +1,110 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + class Foo { } + let x = 12; + class Bar { + init() { + x; + new Foo(); + } + func() { + x; + new Foo(); + } + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + class Foo { + } + const x = 12; + class Bar { + async func() { + x; + new Foo(); + } + constructor() { + x; + new Foo(); + } + } + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_type_inflight_class_sibling_from_method.snap b/libs/wingc/src/jsify/snapshots/capture_type_inflight_class_sibling_from_method.snap new file mode 100644 index 00000000000..aabca701bd9 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_type_inflight_class_sibling_from_method.snap @@ -0,0 +1,98 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + class Foo { } + class Bar { + myMethod() { + new Foo(); + } + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + class Foo { + } + class Bar { + async myMethod() { + new Foo(); + } + } + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_type_new_inflight_class_inner_no_capture.snap b/libs/wingc/src/jsify/snapshots/capture_type_new_inflight_class_inner_no_capture.snap new file mode 100644 index 00000000000..4fa2d747b61 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_type_new_inflight_class_inner_no_capture.snap @@ -0,0 +1,90 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + class Foo { } + new Foo(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + class Foo { + } + new Foo(); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_type_new_inflight_class_outer.snap b/libs/wingc/src/jsify/snapshots/capture_type_new_inflight_class_outer.snap new file mode 100644 index 00000000000..87c03e838f4 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_type_new_inflight_class_outer.snap @@ -0,0 +1,123 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + inflight class Foo { } + + test "test" { + new Foo(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $Foo }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + new $Foo(); + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $Foo: ${context._lift(Foo)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_type_static_method.snap b/libs/wingc/src/jsify/snapshots/capture_type_static_method.snap new file mode 100644 index 00000000000..1d660f6031e --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_type_static_method.snap @@ -0,0 +1,136 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Foo { + static inflight bars(): str { return "bar"; } + } + + test "test" { + Foo.bars(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $Foo }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $Foo.bars()); + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + static async bars() { + return "bar"; + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("bars", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $Foo: ${context._lift(Foo)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(Foo, host, ["bars"]); + } + super._registerBind(host, ops); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_type_static_method_inflight_class.snap b/libs/wingc/src/jsify/snapshots/capture_type_static_method_inflight_class.snap new file mode 100644 index 00000000000..a2e08fa42b6 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_type_static_method_inflight_class.snap @@ -0,0 +1,128 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + inflight class Foo { + static bar(): str { return "bar"; } + } + + test "test" { + Foo.bar(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $Foo }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $Foo.bar()); + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + static async bar() { + return "bar"; + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("bar", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $Foo: ${context._lift(Foo)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/capture_var_from_method_inflight.snap b/libs/wingc/src/jsify/snapshots/capture_var_from_method_inflight.snap new file mode 100644 index 00000000000..736e0cf084b --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/capture_var_from_method_inflight.snap @@ -0,0 +1,95 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + let x = 12; + class Foo { + getX(): num { return x; } + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const x = 12; + class Foo { + async getX() { + return x; + } + } + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/chain_functions.snap b/libs/wingc/src/jsify/snapshots/chain_functions.snap new file mode 100644 index 00000000000..b12851d6548 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/chain_functions.snap @@ -0,0 +1,167 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + class Foo { + b: cloud.Bucket; + + init() { + this.b = new cloud.Bucket(); + } + + inflight getBucket(): cloud.Bucket { + return this.b; + } + } + + let f = new Foo(); + let b = new cloud.Bucket(); + + test "test" { + f.getBucket().put("hello", "world"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $f }) { + class $Closure1 { + async handle() { + (await (await $f.getBucket()).put("hello","world")); + } + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + async getBucket() { + return this.$this_b; + } + constructor({ $this_b }) { + this.$this_b = $this_b; + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("getBucket", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + $this_b: ${this._lift(this.b)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("getBucket")) { + Foo._registerBindObject(this.b, host, []); + } + super._registerBind(host, ops); + } + static _registerTypeBind(host, ops) { + super._registerTypeBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $f: ${context._lift(f)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(f, host, ["getBucket"]); + } + super._registerBind(host, ops); + } + static _registerTypeBind(host, ops) { + super._registerTypeBind(host, ops); + } + } + const f = new Foo(this,"Foo"); + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/closed_inflight_class_extends_outer_inflight_class.snap b/libs/wingc/src/jsify/snapshots/closed_inflight_class_extends_outer_inflight_class.snap new file mode 100644 index 00000000000..07cb86ab6bd --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/closed_inflight_class_extends_outer_inflight_class.snap @@ -0,0 +1,126 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + inflight class Base { } + + test "test" { + inflight class Derived extends Base { } + new Derived(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $Base }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + class Derived extends $Base { + } + new Derived(); + } + } + return $Closure1; +} +``` + +## inflight.Base.js + +```js +module.exports = function({ }) { + class Base { + } + return Base; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Base extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Base.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BaseClient = ${Base._toInflightType(this).text}; + const client = new BaseClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $Base: ${context._lift(Base)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/closure_field.snap b/libs/wingc/src/jsify/snapshots/closure_field.snap new file mode 100644 index 00000000000..b2ab71c88cf --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/closure_field.snap @@ -0,0 +1,217 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let globalBucket = new cloud.Bucket(); + + class MyResource { + closure: inflight (str): str; + + init() { + this.closure = inflight (s: str): str => { + globalBucket.list(); + return "hello"; + }; + } + + inflight foo(): str { + return this.closure("anything"); + } + } + + let x = new MyResource(); + + test "variable can be an inflight closure" { + let val = x.foo(); + assert(val == "hello"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $globalBucket }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle(s) { + (await $globalBucket.list()); + return "hello"; + } + } + return $Closure1; +} +``` + +## inflight.$Closure2.js + +```js +module.exports = function({ $x }) { + class $Closure2 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const val = (await $x.foo()); + {((cond) => {if (!cond) throw new Error("assertion failed: val == \"hello\"")})((val === "hello"))}; + } + } + return $Closure2; +} +``` + +## inflight.MyResource.js + +```js +module.exports = function({ }) { + class MyResource { + constructor({ $this_closure }) { + this.$this_closure = $this_closure; + } + async foo() { + return (await this.$this_closure("anything")); + } + } + return MyResource; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyResource extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + const __parent_this_1 = this; + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $globalBucket: ${context._lift(globalBucket)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(globalBucket, host, ["list"]); + } + super._registerBind(host, ops); + } + } + this.closure = new $Closure1(this,"$Closure1"); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyResource.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyResourceClient = ${MyResource._toInflightType(this).text}; + const client = new MyResourceClient({ + $this_closure: ${this._lift(this.closure)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foo")) { + MyResource._registerBindObject(this.closure, host, ["handle"]); + } + super._registerBind(host, ops); + } + } + class $Closure2 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure2.js")({ + $x: ${context._lift(x)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure2Client = ${$Closure2._toInflightType(this).text}; + const client = new $Closure2Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure2._registerBindObject(x, host, ["foo"]); + } + super._registerBind(host, ops); + } + } + const globalBucket = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + const x = new MyResource(this,"MyResource"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:variable can be an inflight closure",new $Closure2(this,"$Closure2")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/enum_value.snap b/libs/wingc/src/jsify/snapshots/enum_value.snap new file mode 100644 index 00000000000..c98d2bf90f4 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/enum_value.snap @@ -0,0 +1,108 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + enum MyEnum { B, C } + let x = MyEnum.C; + + test "test" { + assert(MyEnum.B != MyEnum.C); + assert(x == MyEnum.C); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $MyEnum, $x }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: MyEnum.B != MyEnum.C")})(($MyEnum.B !== $MyEnum.C))}; + {((cond) => {if (!cond) throw new Error("assertion failed: x == MyEnum.C")})(($x === $MyEnum.C))}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $MyEnum: ${context._lift(MyEnum)}, + $x: ${context._lift(x)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(x, host, []); + } + super._registerBind(host, ops); + } + } + const MyEnum = + Object.freeze((function (tmp) { + tmp[tmp["B"] = 0] = "B"; + tmp[tmp["C"] = 1] = "C"; + return tmp; + })({})) + ; + const x = MyEnum.C; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/fail_unqualified_lift.snap b/libs/wingc/src/jsify/snapshots/fail_unqualified_lift.snap new file mode 100644 index 00000000000..3dfd4e255c4 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fail_unqualified_lift.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Cannot qualify access to a lifted object of type "Queue" (see https://github.com/winglang/wing/issues/76 for more details) 6:6 diff --git a/libs/wingc/src/jsify/snapshots/fail_unqualified_lift_element_from_collection_of_objects.snap b/libs/wingc/src/jsify/snapshots/fail_unqualified_lift_element_from_collection_of_objects.snap new file mode 100644 index 00000000000..f5624b6639f --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fail_unqualified_lift_element_from_collection_of_objects.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Cannot qualify access to a lifted object of type "Bucket" (see https://github.com/winglang/wing/issues/76 for more details) 5:6 diff --git a/libs/wingc/src/jsify/snapshots/fails_base_class_with_lifted_field_object_unqualified.snap b/libs/wingc/src/jsify/snapshots/fails_base_class_with_lifted_field_object_unqualified.snap new file mode 100644 index 00000000000..0a014c0fb8e --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fails_base_class_with_lifted_field_object_unqualified.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Cannot qualify access to a lifted object of type "Bucket" (see https://github.com/winglang/wing/issues/76 for more details) 12:8 diff --git a/libs/wingc/src/jsify/snapshots/fails_if_referencing_unknown_field.snap b/libs/wingc/src/jsify/snapshots/fails_if_referencing_unknown_field.snap new file mode 100644 index 00000000000..ec1c17df827 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fails_if_referencing_unknown_field.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Unknown symbol "b" 3:13 diff --git a/libs/wingc/src/jsify/snapshots/fails_invalid_closure_type.snap b/libs/wingc/src/jsify/snapshots/fails_invalid_closure_type.snap new file mode 100644 index 00000000000..b2b210e87c2 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fails_invalid_closure_type.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Expected type to be "inflight (event: str): void", but got "inflight (s: num): void" instead 2:23 diff --git a/libs/wingc/src/jsify/snapshots/fails_lift_collection_of_objects.snap b/libs/wingc/src/jsify/snapshots/fails_lift_collection_of_objects.snap new file mode 100644 index 00000000000..d4cea83b53e --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fails_lift_collection_of_objects.snap @@ -0,0 +1,104 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let a = [new cloud.Bucket()]; + + test "test" { + let i = 0; + a.at(i).put("hello", "world"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $_a_at_i__ }) { + class $Closure1 { + async handle() { + const i = 0; + (await $_a_at_i__.put("hello","world")); + } + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $_a_at_i__: ${context._lift((a.at(i)))}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject((a.at(i)), host, ["put"]); + } + super._registerBind(host, ops); + } + static _registerTypeBind(host, ops) { + super._registerTypeBind(host, ops); + } + } + const a = Object.freeze([this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket")]); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/fails_lift_with_inflight_arguments.snap b/libs/wingc/src/jsify/snapshots/fails_lift_with_inflight_arguments.snap new file mode 100644 index 00000000000..3365b84f4ec --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fails_lift_with_inflight_arguments.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Cannot reference an inflight value from within a preflight expression 5:11 diff --git a/libs/wingc/src/jsify/snapshots/fails_on_preflight_static.snap b/libs/wingc/src/jsify/snapshots/fails_on_preflight_static.snap new file mode 100644 index 00000000000..d0946e458d3 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fails_on_preflight_static.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Cannot call into preflight phase while inflight 6:10 diff --git a/libs/wingc/src/jsify/snapshots/fails_when_inflight_class_tries_to_extend_preflight_class.snap b/libs/wingc/src/jsify/snapshots/fails_when_inflight_class_tries_to_extend_preflight_class.snap new file mode 100644 index 00000000000..67184370974 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fails_when_inflight_class_tries_to_extend_preflight_class.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Class "Derived" is an inflight class and cannot extend preflight class "Base" 2:35 diff --git a/libs/wingc/src/jsify/snapshots/fails_when_preflight_class_tries_to_extend_inflight_class.snap b/libs/wingc/src/jsify/snapshots/fails_when_preflight_class_tries_to_extend_inflight_class.snap new file mode 100644 index 00000000000..5cda3afbb50 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fails_when_preflight_class_tries_to_extend_inflight_class.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Class "Derived" is an preflight class and cannot extend inflight class "Base" 2:26 diff --git a/libs/wingc/src/jsify/snapshots/fails_when_reassigning_preflight_variable.snap b/libs/wingc/src/jsify/snapshots/fails_when_reassigning_preflight_variable.snap new file mode 100644 index 00000000000..196b925c845 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fails_when_reassigning_preflight_variable.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Variable cannot be reassigned from inflight 3:6 diff --git a/libs/wingc/src/jsify/snapshots/fails_when_referencing_this_from_static.snap b/libs/wingc/src/jsify/snapshots/fails_when_referencing_this_from_static.snap new file mode 100644 index 00000000000..175bb0c025a --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/fails_when_referencing_this_from_static.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Unknown symbol "this" 3:8 diff --git a/libs/wingc/src/jsify/snapshots/foo.snap b/libs/wingc/src/jsify/snapshots/foo.snap new file mode 100644 index 00000000000..f57f1b3f496 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/foo.snap @@ -0,0 +1,138 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Foo { + value: str; + init() { this.value = "hello"; } + } + + let foo_this = new Foo(); + test "test" { + assert(foo_this.value == "hello"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: foo_this.value == \"hello\"")})((this.$foo_this_value === "hello"))}; + } + constructor({ $foo_this_value }) { + this.$foo_this_value = $foo_this_value; + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.value = "hello"; + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + $foo_this_value: ${this._lift(foo_this.value)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(foo_this.value, host, []); + } + super._registerBind(host, ops); + } + } + const foo_this = new Foo(this,"Foo"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/free_inflight_obj_from_inflight.snap b/libs/wingc/src/jsify/snapshots/free_inflight_obj_from_inflight.snap new file mode 100644 index 00000000000..5f3524f4d68 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/free_inflight_obj_from_inflight.snap @@ -0,0 +1,98 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + let y = "hello"; + + class A { + init() { + log(y); + } + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const y = "hello"; + class A { + constructor() { + {console.log(y)}; + } + } + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/free_preflight_object_from_preflight.snap b/libs/wingc/src/jsify/snapshots/free_preflight_object_from_preflight.snap new file mode 100644 index 00000000000..258e448d9fc --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/free_preflight_object_from_preflight.snap @@ -0,0 +1,85 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let x = "hello"; + + class A { + foo() { log(x); } + } + +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + constructor({ }) { + } + } + return A; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + foo() { + {console.log(x)}; + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + const x = "hello"; + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/func_returns_func.snap b/libs/wingc/src/jsify/snapshots/func_returns_func.snap new file mode 100644 index 00000000000..a9c1f1b9ee4 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/func_returns_func.snap @@ -0,0 +1,97 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + (s: str): (): bool => { + (): bool => { + s; + }; + }; + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + async (s) => { + async () => { + s; + } + ; + } + ; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/identify_field.snap b/libs/wingc/src/jsify/snapshots/identify_field.snap new file mode 100644 index 00000000000..9028c2e5f0b --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/identify_field.snap @@ -0,0 +1,99 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + class A { + bucket_this: cloud.Bucket; + + init() { this.bucket_this = new cloud.Bucket(); } + + inflight foo() { + (this.bucket_this).put("hello", "world"); + } + } + +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + constructor({ $this_bucket_this }) { + this.$this_bucket_this = $this_bucket_this; + } + async foo() { + (await this.$this_bucket_this.put("hello","world")); + } + } + return A; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.bucket_this = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + $this_bucket_this: ${this._lift(this.bucket_this)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foo")) { + A._registerBindObject(this.bucket_this, host, ["put"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/identify_field_in_brackets.snap b/libs/wingc/src/jsify/snapshots/identify_field_in_brackets.snap new file mode 100644 index 00000000000..9bbdae39277 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/identify_field_in_brackets.snap @@ -0,0 +1,99 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + class A { + bucket: cloud.Bucket; + + init() { this.bucket = new cloud.Bucket(); } + + inflight foo() { + (this.bucket).put("hello", "world"); + } + } + +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + async foo() { + (await this.$this_bucket.put("hello","world")); + } + constructor({ $this_bucket }) { + this.$this_bucket = $this_bucket; + } + } + return A; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.bucket = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + $this_bucket: ${this._lift(this.bucket)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foo")) { + A._registerBindObject(this.bucket, host, ["put"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/identify_field_inside_expression.snap b/libs/wingc/src/jsify/snapshots/identify_field_inside_expression.snap new file mode 100644 index 00000000000..9bbdae39277 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/identify_field_inside_expression.snap @@ -0,0 +1,99 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + class A { + bucket: cloud.Bucket; + + init() { this.bucket = new cloud.Bucket(); } + + inflight foo() { + (this.bucket).put("hello", "world"); + } + } + +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + async foo() { + (await this.$this_bucket.put("hello","world")); + } + constructor({ $this_bucket }) { + this.$this_bucket = $this_bucket; + } + } + return A; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.bucket = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + $this_bucket: ${this._lift(this.bucket)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foo")) { + A._registerBindObject(this.bucket, host, ["put"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/indirect_capture.snap b/libs/wingc/src/jsify/snapshots/indirect_capture.snap new file mode 100644 index 00000000000..c962c23f086 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/indirect_capture.snap @@ -0,0 +1,166 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let b = new cloud.Bucket(); + + class Capture { + q: cloud.Queue; + init() { this.q = new cloud.Queue(); } + + inflight foo() { + b.list(); + } + + inflight goo() { + this.foo(); + } + } + + let f = new Capture(); + test "test" { + f.goo(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $f }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $f.goo()); + } + } + return $Closure1; +} +``` + +## inflight.Capture.js + +```js +module.exports = function({ $b }) { + class Capture { + constructor({ }) { + } + async foo() { + (await $b.list()); + } + async goo() { + (await this.foo()); + } + } + return Capture; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Capture extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.q = this.node.root.newAbstract("@winglang/sdk.cloud.Queue",this,"cloud.Queue"); + this._addInflightOps("foo", "goo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Capture.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const CaptureClient = ${Capture._toInflightType(this).text}; + const client = new CaptureClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foo")) { + Capture._registerBindObject(b, host, ["list"]); + } + if (ops.includes("goo")) { + Capture._registerBindObject(this, host, ["foo"]); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $f: ${context._lift(f)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(f, host, ["goo"]); + } + super._registerBind(host, ops); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + const f = new Capture(this,"Capture"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/inflight_class_extends_both_inside_inflight_closure.snap b/libs/wingc/src/jsify/snapshots/inflight_class_extends_both_inside_inflight_closure.snap new file mode 100644 index 00000000000..9b0ef204723 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/inflight_class_extends_both_inside_inflight_closure.snap @@ -0,0 +1,91 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + class A {} + class B extends A {} + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + class A { + } + class B extends A { + } + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/inflight_class_extends_inflight_class.snap b/libs/wingc/src/jsify/snapshots/inflight_class_extends_inflight_class.snap new file mode 100644 index 00000000000..633aabbc83d --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/inflight_class_extends_inflight_class.snap @@ -0,0 +1,110 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + inflight class A {} + inflight class B extends A {} + +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + } + return A; +} +``` + +## inflight.B.js + +```js +module.exports = function({ $A }) { + class B extends $A { + } + return B; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class B extends A { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.B.js")({ + $A: ${context._lift(A)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BClient = ${B._toInflightType(this).text}; + const client = new BClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/inflight_class_extends_inflight_class_inside_inflight_closure.snap b/libs/wingc/src/jsify/snapshots/inflight_class_extends_inflight_class_inside_inflight_closure.snap new file mode 100644 index 00000000000..dcdab88a374 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/inflight_class_extends_inflight_class_inside_inflight_closure.snap @@ -0,0 +1,109 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + class A {} + class B extends A {} + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + async handle() { + const A = require("./inflight.A.js")({}); + const B = require("./inflight.B.js")({}); + } + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + } + return $Closure1; +} +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + } + return A; +} +``` + +## inflight.B.js + +```js +module.exports = function({ }) { + class B extends A { + } + return B; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/inflight_constructor.snap b/libs/wingc/src/jsify/snapshots/inflight_constructor.snap new file mode 100644 index 00000000000..3ffc5f8679a --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/inflight_constructor.snap @@ -0,0 +1,102 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Foo { + inflight x: str; + + inflight init() { + this.x = "hello"; + } + + inflight foo() { + this.x; + } + } + +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + async foo() { + this.x; + } + async $inflight_init() { + this.x = "hello"; + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init", "x"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + Foo._registerBindObject(this, host, ["x"]); + } + if (ops.includes("foo")) { + Foo._registerBindObject(this, host, ["x"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/inflight_field.snap b/libs/wingc/src/jsify/snapshots/inflight_field.snap new file mode 100644 index 00000000000..b3ef07f127a --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/inflight_field.snap @@ -0,0 +1,101 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class A { + inflight x: str; + inflight init() { + this.x = "hello"; + } + + inflight method() { + log(this.x); + } + } + +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + constructor({ }) { + } + async method() { + {console.log(this.x)}; + } + async $inflight_init() { + this.x = "hello"; + } + } + return A; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("method", "$inflight_init", "x"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + A._registerBindObject(this, host, ["x"]); + } + if (ops.includes("method")) { + A._registerBindObject(this, host, ["x"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/inflight_field_from_inflight.snap b/libs/wingc/src/jsify/snapshots/inflight_field_from_inflight.snap new file mode 100644 index 00000000000..6f0bdf59d9c --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/inflight_field_from_inflight.snap @@ -0,0 +1,100 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class MyType { + inflight s: str; + inflight init() { + this.s = "hey there!"; + } + inflight foo() { + log(this.s); + } + } + +``` + +## inflight.MyType.js + +```js +module.exports = function({ }) { + class MyType { + constructor({ }) { + } + async foo() { + {console.log(this.s)}; + } + async $inflight_init() { + this.s = "hey there!"; + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init", "s"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + MyType._registerBindObject(this, host, ["s"]); + } + if (ops.includes("foo")) { + MyType._registerBindObject(this, host, ["s"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/inflight_field_from_inflight_class.snap b/libs/wingc/src/jsify/snapshots/inflight_field_from_inflight_class.snap new file mode 100644 index 00000000000..7fd9cb24012 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/inflight_field_from_inflight_class.snap @@ -0,0 +1,97 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + inflight class MyType { + field: str; + init() { this.field = "hi"; } + + getField(): str { + return this.field; + } + } + +``` + +## inflight.MyType.js + +```js +module.exports = function({ }) { + class MyType { + async getField() { + return this.field; + } + constructor() { + this.field = "hi"; + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("getField", "$inflight_init", "field"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + MyType._registerBindObject(this, host, ["field"]); + } + if (ops.includes("getField")) { + MyType._registerBindObject(this, host, ["field"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/inflight_inner_class_captures_variable.snap b/libs/wingc/src/jsify/snapshots/inflight_inner_class_captures_variable.snap new file mode 100644 index 00000000000..d2c2dfaca38 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/inflight_inner_class_captures_variable.snap @@ -0,0 +1,107 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + let var i = 10; + + class Inner { + dang(): num { + i = i + 1; + } + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + async handle() { + let i = 10; + const Inner = require("./inflight.Inner.js")({$i}); + } + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + } + return $Closure1; +} +``` + +## inflight.Inner.js + +```js +module.exports = function({ $i }) { + class Inner { + async dang() { + $i = ($i + 1); + } + } + return Inner; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/inline_inflight_class.snap b/libs/wingc/src/jsify/snapshots/inline_inflight_class.snap new file mode 100644 index 00000000000..762539b0256 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/inline_inflight_class.snap @@ -0,0 +1,144 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + class Foo { + b: cloud.Bucket; + q: cloud.Queue; + + init() { + this.b = new cloud.Bucket(); + this.q = new cloud.Queue(); + + this.q.setConsumer(inflight () => { + this.b.put("in", "bucket"); + }); + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $__parent_this_1_b }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $__parent_this_1_b.put("in","bucket")); + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this.q = this.node.root.newAbstract("@winglang/sdk.cloud.Queue",this,"cloud.Queue"); + const __parent_this_1 = this; + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $__parent_this_1_b: ${context._lift(__parent_this_1.b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(__parent_this_1.b, host, ["put"]); + } + super._registerBind(host, ops); + } + } + (this.q.setConsumer(new $Closure1(this,"$Closure1"))); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/json_object.snap b/libs/wingc/src/jsify/snapshots/json_object.snap new file mode 100644 index 00000000000..cbe124d212a --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/json_object.snap @@ -0,0 +1,98 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let jsonObj1 = Json { key1: "value1" }; + + test "test" { + log(Json.stringify(jsonObj1)); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $jsonObj1, $std_Json }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log(((args) => { return JSON.stringify(args[0], null, args[1]) })([$jsonObj1]))}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $jsonObj1: ${context._lift(jsonObj1)}, + $std_Json: ${context._lift(std.Json)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(jsonObj1, host, []); + } + super._registerBind(host, ops); + } + } + const jsonObj1 = Object.freeze({"key1":"value1"}); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_binary_preflight_and_inflight_expression.snap b/libs/wingc/src/jsify/snapshots/lift_binary_preflight_and_inflight_expression.snap new file mode 100644 index 00000000000..772ee1af04e --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_binary_preflight_and_inflight_expression.snap @@ -0,0 +1,98 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let x = 1; + test "test" { + let y = 2; + x + y; + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $x }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const y = 2; + ($x + y); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $x: ${context._lift(x)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(x, host, []); + } + super._registerBind(host, ops); + } + } + const x = 1; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_binary_preflight_expression.snap b/libs/wingc/src/jsify/snapshots/lift_binary_preflight_expression.snap new file mode 100644 index 00000000000..271efd0aded --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_binary_preflight_expression.snap @@ -0,0 +1,100 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let x = 1; + let y = 2; + test "test" { + x + y; + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $x, $y }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + ($x + $y); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $x: ${context._lift(x)}, + $y: ${context._lift(y)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(x, host, []); + $Closure1._registerBindObject(y, host, []); + } + super._registerBind(host, ops); + } + } + const x = 1; + const y = 2; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_element_from_collection_as_field.snap b/libs/wingc/src/jsify/snapshots/lift_element_from_collection_as_field.snap new file mode 100644 index 00000000000..b1a433e199a --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_element_from_collection_as_field.snap @@ -0,0 +1,100 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + class Foo { + arr: Array; + init() { + this.arr = [new cloud.Bucket()]; + } + + inflight foo() { + this.arr.at(0).put("hello", "world"); + } + } + +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ $_this_arr_at_0__ }) { + this.$_this_arr_at_0__ = $_this_arr_at_0__; + } + async foo() { + (await this.$_this_arr_at_0__.put("hello","world")); + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.arr = Object.freeze([this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket")]); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + $_this_arr_at_0__: ${this._lift((this.arr.at(0)))}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foo")) { + Foo._registerBindObject((this.arr.at(0)), host, ["put"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_element_from_collection_of_objects.snap b/libs/wingc/src/jsify/snapshots/lift_element_from_collection_of_objects.snap new file mode 100644 index 00000000000..548454edfbf --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_element_from_collection_of_objects.snap @@ -0,0 +1,99 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let a = [new cloud.Bucket()]; + + test "test" { + a.at(0).put("hello", "world"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $_a_at_0__ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $_a_at_0__.put("hello","world")); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $_a_at_0__: ${context._lift((a.at(0)))}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject((a.at(0)), host, ["put"]); + } + super._registerBind(host, ops); + } + } + const a = Object.freeze([this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket")]); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_inflight_closure.snap b/libs/wingc/src/jsify/snapshots/lift_inflight_closure.snap new file mode 100644 index 00000000000..b79249fd73d --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_inflight_closure.snap @@ -0,0 +1,138 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let f = inflight () => {}; + + inflight () => { + f(); + }; + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + } + } + return $Closure1; +} +``` + +## inflight.$Closure2.js + +```js +module.exports = function({ $f }) { + class $Closure2 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $f()); + } + } + return $Closure2; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure2 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure2.js")({ + $f: ${context._lift(f)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure2Client = ${$Closure2._toInflightType(this).text}; + const client = new $Closure2Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure2._registerBindObject(f, host, ["handle"]); + } + super._registerBind(host, ops); + } + } + const f = new $Closure1(this,"$Closure1"); + new $Closure2(this,"$Closure2"); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_inside_preflight_method.snap b/libs/wingc/src/jsify/snapshots/lift_inside_preflight_method.snap new file mode 100644 index 00000000000..3bbfae65c51 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_inside_preflight_method.snap @@ -0,0 +1,148 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + class Foo { + defineBucket(name: str) { + let b = new cloud.Bucket() as name; + inflight () => { + b.put("dirty","x"); + }; + } + + init() { + this.defineBucket("b1"); + this.defineBucket("b2"); + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $b }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $b.put("dirty","x")); + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + (this.defineBucket("b1")); + (this.defineBucket("b2")); + this._addInflightOps("$inflight_init"); + } + defineBucket(name) { + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,name); + const __parent_this_1 = this; + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(b, host, ["put"]); + } + super._registerBind(host, ops); + } + } + new $Closure1(this,"$Closure1"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_string.snap b/libs/wingc/src/jsify/snapshots/lift_string.snap new file mode 100644 index 00000000000..95d46cc3ad7 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_string.snap @@ -0,0 +1,96 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let b = "hello"; + test "test" { + log(b); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $b }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log($b)}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(b, host, []); + } + super._registerBind(host, ops); + } + } + const b = "hello"; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_this.snap b/libs/wingc/src/jsify/snapshots/lift_this.snap new file mode 100644 index 00000000000..879df73695f --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_this.snap @@ -0,0 +1,166 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Foo { + inflight x: num; + inflight init() { + this.x = 42; + } + inflight bar(): num { + return this.x; + } + inflight foo(): num { + return this.bar() / 2; + } + } + + let f = new Foo(); + + test "test" { + assert(f.foo() == 21); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $f }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: f.foo() == 21")})(((await $f.foo()) === 21))}; + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + async bar() { + return this.x; + } + async foo() { + return ((await this.bar()) / 2); + } + async $inflight_init() { + this.x = 42; + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("bar", "foo", "$inflight_init", "x"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + Foo._registerBindObject(this, host, ["x"]); + } + if (ops.includes("bar")) { + Foo._registerBindObject(this, host, ["x"]); + } + if (ops.includes("foo")) { + Foo._registerBindObject(this, host, ["bar"]); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $f: ${context._lift(f)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(f, host, ["foo"]); + } + super._registerBind(host, ops); + } + } + const f = new Foo(this,"Foo"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_var_with_this.snap b/libs/wingc/src/jsify/snapshots/lift_var_with_this.snap new file mode 100644 index 00000000000..0714af9f1cc --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_var_with_this.snap @@ -0,0 +1,138 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Foo { + value: str; + init() { this.value = "hello"; } + } + + let foo_this = new Foo(); + test "test" { + assert(foo_this.value == "hello"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ $foo_this_value }) { + this.$foo_this_value = $foo_this_value; + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: foo_this.value == \"hello\"")})((this.$foo_this_value === "hello"))}; + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.value = "hello"; + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + $foo_this_value: ${this._lift(foo_this.value)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(foo_this.value, host, []); + } + super._registerBind(host, ops); + } + } + const foo_this = new Foo(this,"Foo"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_via_closure.snap b/libs/wingc/src/jsify/snapshots/lift_via_closure.snap new file mode 100644 index 00000000000..0f61d91e658 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_via_closure.snap @@ -0,0 +1,154 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + let bucket = new cloud.Bucket(); + + let fn = inflight () => { + bucket.put("hello", "world"); + }; + + test "test" { + fn(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $bucket }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $bucket.put("hello","world")); + } + } + return $Closure1; +} +``` + +## inflight.$Closure2.js + +```js +module.exports = function({ $fn }) { + class $Closure2 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $fn()); + } + } + return $Closure2; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $bucket: ${context._lift(bucket)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(bucket, host, ["put"]); + } + super._registerBind(host, ops); + } + } + class $Closure2 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure2.js")({ + $fn: ${context._lift(fn)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure2Client = ${$Closure2._toInflightType(this).text}; + const client = new $Closure2Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure2._registerBindObject(fn, host, ["handle"]); + } + super._registerBind(host, ops); + } + } + const bucket = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + const fn = new $Closure1(this,"$Closure1"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure2(this,"$Closure2")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/lift_via_closure_class_explicit.snap b/libs/wingc/src/jsify/snapshots/lift_via_closure_class_explicit.snap new file mode 100644 index 00000000000..c2488dbd983 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/lift_via_closure_class_explicit.snap @@ -0,0 +1,171 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + class MyClosure { + q: cloud.Queue; + init() { + this.q = new cloud.Queue(); + } + + inflight handle() { + this.another(); + } + + inflight another() { + this.q.push("hello"); + } + } + + let fn = new MyClosure(); + + test "test" { + fn(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $fn }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $fn()); + } + } + return $Closure1; +} +``` + +## inflight.MyClosure.js + +```js +module.exports = function({ }) { + class MyClosure { + constructor({ $this_q }) { + this.$this_q = $this_q; + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await this.another()); + } + async another() { + (await this.$this_q.push("hello")); + } + } + return MyClosure; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyClosure extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.q = this.node.root.newAbstract("@winglang/sdk.cloud.Queue",this,"cloud.Queue"); + this._addInflightOps("handle", "another", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyClosure.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyClosureClient = ${MyClosure._toInflightType(this).text}; + const client = new MyClosureClient({ + $this_q: ${this._lift(this.q)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("another")) { + MyClosure._registerBindObject(this.q, host, ["push"]); + } + if (ops.includes("handle")) { + MyClosure._registerBindObject(this, host, ["another"]); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $fn: ${context._lift(fn)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(fn, host, ["handle"]); + } + super._registerBind(host, ops); + } + } + const fn = new MyClosure(this,"MyClosure"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/namespaced_static_from_inflight.snap b/libs/wingc/src/jsify/snapshots/namespaced_static_from_inflight.snap new file mode 100644 index 00000000000..fa109bdc07e --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/namespaced_static_from_inflight.snap @@ -0,0 +1,90 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring util; + test "test" { + util.tryEnv("PATH"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $util_Util }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $util_Util.tryEnv("PATH")); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const util = require('@winglang/sdk').util; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $util_Util: ${context._lift(util.Util)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/nested_inflight_after_preflight_operation.snap b/libs/wingc/src/jsify/snapshots/nested_inflight_after_preflight_operation.snap new file mode 100644 index 00000000000..7000fa5a13a --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/nested_inflight_after_preflight_operation.snap @@ -0,0 +1,150 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + class YourType { + inflight b: str; + inflight init() { + this.b = "hello"; + } + } + + let y = new YourType(); + + test "test" { + log(y.b); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $y }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log($y.b)}; + } + } + return $Closure1; +} +``` + +## inflight.YourType.js + +```js +module.exports = function({ }) { + class YourType { + constructor({ }) { + } + async $inflight_init() { + this.b = "hello"; + } + } + return YourType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class YourType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init", "b"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.YourType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const YourTypeClient = ${YourType._toInflightType(this).text}; + const client = new YourTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + YourType._registerBindObject(this, host, ["b"]); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $y: ${context._lift(y)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(y, host, ["b"]); + } + super._registerBind(host, ops); + } + } + const y = new YourType(this,"YourType"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/nested_preflight_operation.snap b/libs/wingc/src/jsify/snapshots/nested_preflight_operation.snap new file mode 100644 index 00000000000..533cdfb5337 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/nested_preflight_operation.snap @@ -0,0 +1,184 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + class YourType { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + } + class MyType { + y: YourType; + init() { + this.y = new YourType(); + } + } + + let t = new MyType(); + + test "test" { + t.y.b.put("hello", "world"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $t_y_b }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $t_y_b.put("hello","world")); + } + } + return $Closure1; +} +``` + +## inflight.MyType.js + +```js +module.exports = function({ }) { + class MyType { + constructor({ }) { + } + } + return MyType; +} +``` + +## inflight.YourType.js + +```js +module.exports = function({ }) { + class YourType { + constructor({ }) { + } + } + return YourType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class YourType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.YourType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const YourTypeClient = ${YourType._toInflightType(this).text}; + const client = new YourTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.y = new YourType(this,"YourType"); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $t_y_b: ${context._lift(t.y.b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(t.y.b, host, ["put"]); + } + super._registerBind(host, ops); + } + } + const t = new MyType(this,"MyType"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/new_inflight_object.snap b/libs/wingc/src/jsify/snapshots/new_inflight_object.snap new file mode 100644 index 00000000000..fd75f4c1ed8 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/new_inflight_object.snap @@ -0,0 +1,123 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + inflight class Foo {} + + test "test" { + new Foo(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $Foo }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + new $Foo(); + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $Foo: ${context._lift(Foo)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/no_capture_inside_methods.snap b/libs/wingc/src/jsify/snapshots/no_capture_inside_methods.snap new file mode 100644 index 00000000000..7e23b463408 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/no_capture_inside_methods.snap @@ -0,0 +1,93 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + let start = 12; + if true { + start; + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const start = 12; + if (true) { + start; + } + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/no_capture_of_identifier_from_inner_scope.snap b/libs/wingc/src/jsify/snapshots/no_capture_of_identifier_from_inner_scope.snap new file mode 100644 index 00000000000..877da413203 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/no_capture_of_identifier_from_inner_scope.snap @@ -0,0 +1,93 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + let x = "hello"; + if true { + log(x); + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const x = "hello"; + if (true) { + {console.log(x)}; + } + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/no_capture_of_identifier_from_same_scope.snap b/libs/wingc/src/jsify/snapshots/no_capture_of_identifier_from_same_scope.snap new file mode 100644 index 00000000000..f24a0bd1ccb --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/no_capture_of_identifier_from_same_scope.snap @@ -0,0 +1,89 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + let x = "hello"; + log(x); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const x = "hello"; + {console.log(x)}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/no_capture_shadow_inside_inner_scopes.snap b/libs/wingc/src/jsify/snapshots/no_capture_shadow_inside_inner_scopes.snap new file mode 100644 index 00000000000..986e11c9ac7 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/no_capture_shadow_inside_inner_scopes.snap @@ -0,0 +1,101 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "testing" { + let arr = MutArray [0]; + + let i = 1; + arr.push(i); + + if true { + let i = 2; + arr.push(i); + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const arr = [0]; + const i = 1; + (await arr.push(i)); + if (true) { + const i = 2; + (await arr.push(i)); + } + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:testing",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/no_lift_shadow_inside_inner_scopes.snap b/libs/wingc/src/jsify/snapshots/no_lift_shadow_inside_inner_scopes.snap new file mode 100644 index 00000000000..c451a564977 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/no_lift_shadow_inside_inner_scopes.snap @@ -0,0 +1,107 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let i = 1; + test "testing" { + let arr = MutArray [0]; + arr.push(i); + + if true { + let i = 2; + arr.push(i); + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $i }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const arr = [0]; + (await arr.push($i)); + if (true) { + const i = 2; + (await arr.push(i)); + } + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $i: ${context._lift(i)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(i, host, []); + } + super._registerBind(host, ops); + } + } + const i = 1; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:testing",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/preflight_class_extends_preflight_class.snap b/libs/wingc/src/jsify/snapshots/preflight_class_extends_preflight_class.snap new file mode 100644 index 00000000000..27c28ea69ec --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/preflight_class_extends_preflight_class.snap @@ -0,0 +1,115 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Base {} + class Derived extends Base {} + +``` + +## inflight.Base.js + +```js +module.exports = function({ }) { + class Base { + constructor({ }) { + } + } + return Base; +} +``` + +## inflight.Derived.js + +```js +module.exports = function({ $Base }) { + class Derived extends $Base { + constructor({ }) { + super({ }); + } + } + return Derived; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Base extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Base.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BaseClient = ${Base._toInflightType(this).text}; + const client = new BaseClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class Derived extends Base { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Derived.js")({ + $Base: ${context._lift(Base)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const DerivedClient = ${Derived._toInflightType(this).text}; + const client = new DerivedClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/preflight_collection.snap b/libs/wingc/src/jsify/snapshots/preflight_collection.snap new file mode 100644 index 00000000000..e5f3522ca44 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/preflight_collection.snap @@ -0,0 +1,100 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let a = ["hello", "world"]; + inflight () => { + assert(a.length == 2); + log(a.at(0)); + }; + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $_a_at_0__, $a_length }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: a.length == 2")})(($a_length === 2))}; + {console.log($_a_at_0__)}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $_a_at_0__: ${context._lift((a.at(0)))}, + $a_length: ${context._lift(a.length)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject((a.at(0)), host, []); + $Closure1._registerBindObject(a.length, host, []); + } + super._registerBind(host, ops); + } + } + const a = Object.freeze(["hello", "world"]); + new $Closure1(this,"$Closure1"); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/preflight_collection_of_preflight_objects.snap b/libs/wingc/src/jsify/snapshots/preflight_collection_of_preflight_objects.snap new file mode 100644 index 00000000000..4d43e55ac1e --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/preflight_collection_of_preflight_objects.snap @@ -0,0 +1,105 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let arr = [ + new cloud.Bucket() as "b1", + new cloud.Bucket() as "b2" + ]; + test "test" { + assert(arr.length == 2); + arr.at(0).put("hello", "world"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $_arr_at_0__, $arr_length }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: arr.length == 2")})(($arr_length === 2))}; + (await $_arr_at_0__.put("hello","world")); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $_arr_at_0__: ${context._lift((arr.at(0)))}, + $arr_length: ${context._lift(arr.length)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject((arr.at(0)), host, ["put"]); + $Closure1._registerBindObject(arr.length, host, []); + } + super._registerBind(host, ops); + } + } + const arr = Object.freeze([this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"b1"), this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"b2")]); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/preflight_nested_object_with_operations.snap b/libs/wingc/src/jsify/snapshots/preflight_nested_object_with_operations.snap new file mode 100644 index 00000000000..10dcf94cef8 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/preflight_nested_object_with_operations.snap @@ -0,0 +1,143 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let b = new cloud.Bucket(); + class A { + bucky: cloud.Bucket; + init() { + this.bucky = b; + } + } + + let a = new A(); + test "test" { + a.bucky.list(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $a_bucky }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $a_bucky.list()); + } + } + return $Closure1; +} +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + constructor({ }) { + } + } + return A; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.bucky = b; + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $a_bucky: ${context._lift(a.bucky)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(a.bucky, host, ["list"]); + } + super._registerBind(host, ops); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + const a = new A(this,"A"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/preflight_object.snap b/libs/wingc/src/jsify/snapshots/preflight_object.snap new file mode 100644 index 00000000000..ebfaa6f1aa7 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/preflight_object.snap @@ -0,0 +1,141 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class A { + inflight hello() {} + inflight goodbye() {} + } + let pf_obj = new A(); + test "test" { + pf_obj.hello(); + pf_obj.goodbye(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $pf_obj }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $pf_obj.hello()); + (await $pf_obj.goodbye()); + } + } + return $Closure1; +} +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + constructor({ }) { + } + async hello() { + } + async goodbye() { + } + } + return A; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("hello", "goodbye", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $pf_obj: ${context._lift(pf_obj)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(pf_obj, host, ["goodbye", "hello"]); + } + super._registerBind(host, ops); + } + } + const pf_obj = new A(this,"A"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/preflight_object_through_property.snap b/libs/wingc/src/jsify/snapshots/preflight_object_through_property.snap new file mode 100644 index 00000000000..77e03b08c45 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/preflight_object_through_property.snap @@ -0,0 +1,143 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + class MyType { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + } + + let t = new MyType(); + + test "test" { + t.b.put("hello", "world"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $t_b }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $t_b.put("hello","world")); + } + } + return $Closure1; +} +``` + +## inflight.MyType.js + +```js +module.exports = function({ }) { + class MyType { + constructor({ }) { + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $t_b: ${context._lift(t.b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(t.b, host, ["put"]); + } + super._registerBind(host, ops); + } + } + const t = new MyType(this,"MyType"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/preflight_object_with_operations.snap b/libs/wingc/src/jsify/snapshots/preflight_object_with_operations.snap new file mode 100644 index 00000000000..133e27b7db5 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/preflight_object_with_operations.snap @@ -0,0 +1,100 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let b = new cloud.Bucket(); + test "test" { + b.list(); + b.put("hello", "world"); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $b }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $b.list()); + (await $b.put("hello","world")); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(b, host, ["list", "put"]); + } + super._registerBind(host, ops); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/preflight_object_with_operations_multiple_methods.snap b/libs/wingc/src/jsify/snapshots/preflight_object_with_operations_multiple_methods.snap new file mode 100644 index 00000000000..56433aef49e --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/preflight_object_with_operations_multiple_methods.snap @@ -0,0 +1,106 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let b = new cloud.Bucket(); + + class Foo { + inflight put() { + b.put("hello1", "world"); + } + + inflight list() { + b.list(); + } + } + +``` + +## inflight.Foo.js + +```js +module.exports = function({ $b }) { + class Foo { + constructor({ }) { + } + async put() { + (await $b.put("hello1","world")); + } + async list() { + (await $b.list()); + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("put", "list", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("list")) { + Foo._registerBindObject(b, host, ["list"]); + } + if (ops.includes("put")) { + Foo._registerBindObject(b, host, ["put"]); + } + super._registerBind(host, ops); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/preflight_value_field.snap b/libs/wingc/src/jsify/snapshots/preflight_value_field.snap new file mode 100644 index 00000000000..04604942c10 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/preflight_value_field.snap @@ -0,0 +1,152 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class MyType { + name: str; + last: str; + + init() { + this.name = "hello"; + this.last = "world"; + } + } + + let t = new MyType(); + + test "test" { + log(t.name); + assert(t.name.length > 0); + log(t.last); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $t_last, $t_name, $t_name_length }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log($t_name)}; + {((cond) => {if (!cond) throw new Error("assertion failed: t.name.length > 0")})(($t_name_length > 0))}; + {console.log($t_last)}; + } + } + return $Closure1; +} +``` + +## inflight.MyType.js + +```js +module.exports = function({ }) { + class MyType { + constructor({ }) { + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.name = "hello"; + this.last = "world"; + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $t_last: ${context._lift(t.last)}, + $t_name: ${context._lift(t.name)}, + $t_name_length: ${context._lift(t.name.length)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(t.last, host, []); + $Closure1._registerBindObject(t.name, host, []); + $Closure1._registerBindObject(t.name.length, host, []); + } + super._registerBind(host, ops); + } + } + const t = new MyType(this,"MyType"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/read_primitive_value.snap b/libs/wingc/src/jsify/snapshots/read_primitive_value.snap new file mode 100644 index 00000000000..fbc2206dc71 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/read_primitive_value.snap @@ -0,0 +1,97 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let x = "my_string"; + + test "test" { + log(x); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $x }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log($x)}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $x: ${context._lift(x)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(x, host, []); + } + super._registerBind(host, ops); + } + } + const x = "my_string"; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reassign_captured_variable.snap b/libs/wingc/src/jsify/snapshots/reassign_captured_variable.snap new file mode 100644 index 00000000000..0bf5482688b --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reassign_captured_variable.snap @@ -0,0 +1,98 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + let var i = 10; + + class Inner { + dang(): num { + i = i + 1; + } + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + let i = 10; + class Inner { + async dang() { + i = (i + 1); + } + } + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reassigned_captured_variable_preflight.snap b/libs/wingc/src/jsify/snapshots/reassigned_captured_variable_preflight.snap new file mode 100644 index 00000000000..1fe37e4b5e5 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reassigned_captured_variable_preflight.snap @@ -0,0 +1,49 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let var i = 10; + () => { + i = 12; + }; + +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + let i = 10; + (() => { + i = 12; + }); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/ref_std_macro.snap b/libs/wingc/src/jsify/snapshots/ref_std_macro.snap new file mode 100644 index 00000000000..5d0fd27635d --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/ref_std_macro.snap @@ -0,0 +1,97 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let arr = [1,2,3]; + + test "test" { + assert(arr.length == 3); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $arr_length }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: arr.length == 3")})(($arr_length === 3))}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $arr_length: ${context._lift(arr.length)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(arr.length, host, []); + } + super._registerBind(host, ops); + } + } + const arr = Object.freeze([1, 2, 3]); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_from_static_inflight.snap b/libs/wingc/src/jsify/snapshots/reference_from_static_inflight.snap new file mode 100644 index 00000000000..68c6d8f6109 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_from_static_inflight.snap @@ -0,0 +1,94 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let s = "hello"; + + class MyType { + static inflight staticMethod(): str { + return s; + } + } + +``` + +## inflight.MyType.js + +```js +module.exports = function({ $s }) { + class MyType { + constructor({ }) { + } + static async staticMethod() { + return $s; + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("staticMethod", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + $s: ${context._lift(s)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + static _registerTypeBind(host, ops) { + if (ops.includes("staticMethod")) { + MyType._registerBindObject(s, host, []); + } + super._registerTypeBind(host, ops); + } + } + const s = "hello"; + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_inflight_class.snap b/libs/wingc/src/jsify/snapshots/reference_inflight_class.snap new file mode 100644 index 00000000000..6db5c10df17 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_inflight_class.snap @@ -0,0 +1,128 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + inflight class Foo { + static a(): str { return "a"; } + } + + test "test" { + log(Foo.a()); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $Foo }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log((await $Foo.a()))}; + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + static async a() { + return "a"; + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("a", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $Foo: ${context._lift(Foo)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_inflight_field.snap b/libs/wingc/src/jsify/snapshots/reference_inflight_field.snap new file mode 100644 index 00000000000..0334dcb8ca5 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_inflight_field.snap @@ -0,0 +1,102 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Foo { + inflight x: str; + + inflight init() { + this.x = "hello"; + } + + inflight method() { + this.x; + } + } + +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + async method() { + this.x; + } + async $inflight_init() { + this.x = "hello"; + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("method", "$inflight_init", "x"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + Foo._registerBindObject(this, host, ["x"]); + } + if (ops.includes("method")) { + Foo._registerBindObject(this, host, ["x"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_inflight_from_inflight.snap b/libs/wingc/src/jsify/snapshots/reference_inflight_from_inflight.snap new file mode 100644 index 00000000000..fc3bb84143e --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_inflight_from_inflight.snap @@ -0,0 +1,148 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + + let s = "hello"; + + inflight class Foo { + foofoo1() { + log(s); + } + } + + test "test" { + let f = new Foo(); + + // class Bar { + // bar() { + // f.foofoo1(); + // } + // } + } + + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $Foo }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const f = new $Foo(); + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ $s }) { + class Foo { + async foofoo1() { + {console.log($s)}; + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foofoo1", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + $s: ${context._lift(s)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("foofoo1")) { + Foo._registerBindObject(s, host, []); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $Foo: ${context._lift(Foo)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + const s = "hello"; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_preflight_field.snap b/libs/wingc/src/jsify/snapshots/reference_preflight_field.snap new file mode 100644 index 00000000000..44ebd49f9fb --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_preflight_field.snap @@ -0,0 +1,99 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Foo { + x: str; + + init() { + this.x = "world"; + } + + inflight method() { + this.x; + } + } + +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ $this_x }) { + this.$this_x = $this_x; + } + async method() { + this.$this_x; + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.x = "world"; + this._addInflightOps("method", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + $this_x: ${this._lift(this.x)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("method")) { + Foo._registerBindObject(this.x, host, []); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_preflight_field_call_independent_method.snap b/libs/wingc/src/jsify/snapshots/reference_preflight_field_call_independent_method.snap new file mode 100644 index 00000000000..53c38812df5 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_preflight_field_call_independent_method.snap @@ -0,0 +1,99 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class Foo { + arr: Array; + + init() { + this.arr = ["hello", "world"]; + } + + inflight method() { + this.arr.at(1); + } + } + +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ $_this_arr_at_1__ }) { + this.$_this_arr_at_1__ = $_this_arr_at_1__; + } + async method() { + this.$_this_arr_at_1__; + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.arr = Object.freeze(["hello", "world"]); + this._addInflightOps("method", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + $_this_arr_at_1__: ${this._lift((this.arr.at(1)))}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("method")) { + Foo._registerBindObject((this.arr.at(1)), host, []); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_preflight_fields.snap b/libs/wingc/src/jsify/snapshots/reference_preflight_fields.snap new file mode 100644 index 00000000000..bd4e86601e1 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_preflight_fields.snap @@ -0,0 +1,122 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + class MyType { + s: str; + b: cloud.Bucket; + + init() { + this.s = "hello"; + this.b = new cloud.Bucket(); + } + + inflight boom() { + assert(this.s.length > 0); + assert(this.b.list().length > 0); + } + + inflight bam() { + this.b.put("hello", "world"); + this.b.get("aaa"); + } + } + +``` + +## inflight.MyType.js + +```js +module.exports = function({ }) { + class MyType { + constructor({ $this_b, $this_s_length }) { + this.$this_b = $this_b; + this.$this_s_length = $this_s_length; + } + async boom() { + {((cond) => {if (!cond) throw new Error("assertion failed: this.s.length > 0")})((this.$this_s_length > 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.b.list().length > 0")})(((await this.$this_b.list()).length > 0))}; + } + async bam() { + (await this.$this_b.put("hello","world")); + (await this.$this_b.get("aaa")); + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.s = "hello"; + this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("boom", "bam", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + $this_b: ${this._lift(this.b)}, + $this_s_length: ${this._lift(this.s.length)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("bam")) { + MyType._registerBindObject(this.b, host, ["get", "put"]); + } + if (ops.includes("boom")) { + MyType._registerBindObject(this.b, host, ["list"]); + MyType._registerBindObject(this.s.length, host, []); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_preflight_free_variable_with_this_in_the_expression.snap b/libs/wingc/src/jsify/snapshots/reference_preflight_free_variable_with_this_in_the_expression.snap new file mode 100644 index 00000000000..02b2d628ad4 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_preflight_free_variable_with_this_in_the_expression.snap @@ -0,0 +1,106 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let b = new cloud.Bucket(); + + class Foo { + name: str; + + init() { + this.name = "my_object"; + } + + inflight method() { + b.put(this.name, "value"); + } + } + +``` + +## inflight.Foo.js + +```js +module.exports = function({ $b }) { + class Foo { + constructor({ $this_name }) { + this.$this_name = $this_name; + } + async method() { + (await $b.put(this.$this_name,"value")); + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.name = "my_object"; + this._addInflightOps("method", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + $this_name: ${this._lift(this.name)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("method")) { + Foo._registerBindObject(b, host, ["put"]); + Foo._registerBindObject(this.name, host, []); + } + super._registerBind(host, ops); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_preflight_object_from_static_inflight.snap b/libs/wingc/src/jsify/snapshots/reference_preflight_object_from_static_inflight.snap new file mode 100644 index 00000000000..ca6c3fe0a7e --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_preflight_object_from_static_inflight.snap @@ -0,0 +1,97 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + let q = new cloud.Queue(); + + class MyType { + static inflight addToQueue(m: str) { + q.push(m); + } + } + +``` + +## inflight.MyType.js + +```js +module.exports = function({ $q }) { + class MyType { + constructor({ }) { + } + static async addToQueue(m) { + (await $q.push(m)); + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("addToQueue", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + $q: ${context._lift(q)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + static _registerTypeBind(host, ops) { + if (ops.includes("addToQueue")) { + MyType._registerBindObject(q, host, ["push"]); + } + super._registerTypeBind(host, ops); + } + } + const q = this.node.root.newAbstract("@winglang/sdk.cloud.Queue",this,"cloud.Queue"); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_static_inflight.snap b/libs/wingc/src/jsify/snapshots/reference_static_inflight.snap new file mode 100644 index 00000000000..94c88883d72 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_static_inflight.snap @@ -0,0 +1,135 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class MyType { + static inflight myStaticMethod(): str {} + } + + test "test" { + log(MyType.myStaticMethod()); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $MyType }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log((await $MyType.myStaticMethod()))}; + } + } + return $Closure1; +} +``` + +## inflight.MyType.js + +```js +module.exports = function({ }) { + class MyType { + constructor({ }) { + } + static async myStaticMethod() { + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("myStaticMethod", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $MyType: ${context._lift(MyType)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(MyType, host, ["myStaticMethod"]); + } + super._registerBind(host, ops); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/reference_static_inflight_which_references_preflight_object.snap b/libs/wingc/src/jsify/snapshots/reference_static_inflight_which_references_preflight_object.snap new file mode 100644 index 00000000000..1294e200245 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/reference_static_inflight_which_references_preflight_object.snap @@ -0,0 +1,153 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + let b = new cloud.Bucket(); + + class MyType { + static inflight staticMethod(): str { + b.list(); + return "foo"; + } + } + + test "test" { + log(MyType.staticMethod()); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $MyType }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log((await $MyType.staticMethod()))}; + } + } + return $Closure1; +} +``` + +## inflight.MyType.js + +```js +module.exports = function({ $b }) { + class MyType { + constructor({ }) { + } + static async staticMethod() { + (await $b.list()); + return "foo"; + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("staticMethod", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + static _registerTypeBind(host, ops) { + if (ops.includes("staticMethod")) { + MyType._registerBindObject(b, host, ["list"]); + } + super._registerTypeBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $MyType: ${context._lift(MyType)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(MyType, host, ["staticMethod"]); + } + super._registerBind(host, ops); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/some_test.snap b/libs/wingc/src/jsify/snapshots/some_test.snap new file mode 100644 index 00000000000..282cf273c04 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/some_test.snap @@ -0,0 +1,150 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + class Foo { + defineBucket(name: str) { + let b = new cloud.Bucket() as name; + + + inflight () => { + b.put("dirty","x"); // <- this is a lift, so we need to know `b` was defined outside of this closure (or is this handled by our closure folding??). + }; + } + + init() { + this.defineBucket("b1"); + this.defineBucket("b2"); + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $b }) { + class $Closure1 { + async handle() { + (await $b.put("dirty","x")); + } + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + } + return $Closure1; +} +``` + +## inflight.Foo.js + +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + } + return Foo; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + (this.defineBucket("b1")); + (this.defineBucket("b2")); + this._addInflightOps("$inflight_init"); + } + defineBucket(name) { + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,name); + const __parent_this_1 = this; + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(b, host, ["put"]); + } + super._registerBind(host, ops); + } + } + new $Closure1(this,"$Closure1"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/static_external_inflight_class.snap b/libs/wingc/src/jsify/snapshots/static_external_inflight_class.snap new file mode 100644 index 00000000000..cc017fc325d --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/static_external_inflight_class.snap @@ -0,0 +1,139 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + inflight class A { + static foo() { log("hello"); } + } + + test "test" { + class B { + callFoo() { + A.foo(); + } + } + + A.foo(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $A }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + class B { + async callFoo() { + (await $A.foo()); + } + } + (await $A.foo()); + } + } + return $Closure1; +} +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + static async foo() { + {console.log("hello")}; + } + } + return A; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $A: ${context._lift(A)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/static_external_preflight_class.snap b/libs/wingc/src/jsify/snapshots/static_external_preflight_class.snap new file mode 100644 index 00000000000..667c9528a49 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/static_external_preflight_class.snap @@ -0,0 +1,144 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class A { + static inflight foo() { log("hello"); } + } + + test "test" { + class B { + foo() { + A.foo(); + } + } + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $A }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + class B { + async foo() { + (await $A.foo()); + } + } + } + } + return $Closure1; +} +``` + +## inflight.A.js + +```js +module.exports = function({ }) { + class A { + constructor({ }) { + } + static async foo() { + {console.log("hello")}; + } + } + return A; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $A: ${context._lift(A)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(A, host, ["foo"]); + } + super._registerBind(host, ops); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/static_inflight_operation.snap b/libs/wingc/src/jsify/snapshots/static_inflight_operation.snap new file mode 100644 index 00000000000..511f99a32f1 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/static_inflight_operation.snap @@ -0,0 +1,150 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let b = new cloud.Bucket(); + + class A { + static inflight myop() { + b.list(); + } + } + + test "test" { + A.myop(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $A }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $A.myop()); + } + } + return $Closure1; +} +``` + +## inflight.A.js + +```js +module.exports = function({ $b }) { + class A { + constructor({ }) { + } + static async myop() { + (await $b.list()); + } + } + return A; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class A extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("myop", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.A.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const AClient = ${A._toInflightType(this).text}; + const client = new AClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + static _registerTypeBind(host, ops) { + if (ops.includes("myop")) { + A._registerBindObject(b, host, ["list"]); + } + super._registerTypeBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $A: ${context._lift(A)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(A, host, ["myop"]); + } + super._registerBind(host, ops); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/static_local_inflight_class.snap b/libs/wingc/src/jsify/snapshots/static_local_inflight_class.snap new file mode 100644 index 00000000000..034183fb51c --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/static_local_inflight_class.snap @@ -0,0 +1,107 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + class A { + static foo() { log("hello"); } + } + + class B { + init() { + A.foo(); + } + } + + A.foo(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + class A { + static async foo() { + {console.log("hello")}; + } + } + class B { + constructor() { + (await A.foo()); + } + } + (await A.foo()); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/static_on_std_type.snap b/libs/wingc/src/jsify/snapshots/static_on_std_type.snap new file mode 100644 index 00000000000..5ffe4e0ee1e --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/static_on_std_type.snap @@ -0,0 +1,91 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + test "test" { + log(str.fromJson("hello")); + assert(Json.values(Json {}).length == 0); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $std_Json, $std_String }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log(((args) => { if (typeof args !== "string") {throw new Error("unable to parse " + typeof args + " " + args + " as a string")}; return JSON.parse(JSON.stringify(args)) })("hello"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: Json.values(Json {}).length == 0")})(((Object.values(Object.freeze({}))).length === 0))}; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $std_Json: ${context._lift(std.Json)}, + $std_String: ${context._lift(std.String)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/top_level_inflight_class_extends_inflight_class.snap b/libs/wingc/src/jsify/snapshots/top_level_inflight_class_extends_inflight_class.snap new file mode 100644 index 00000000000..4ce6479181c --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/top_level_inflight_class_extends_inflight_class.snap @@ -0,0 +1,116 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + inflight class Base {} + inflight class Derived extends Base {} + +``` + +## inflight.Base.js + +```js +module.exports = function({ }) { + class Base { + } + return Base; +} +``` + +## inflight.Derived.js + +```js +module.exports = function({ $Base }) { + class Derived extends $Base { + } + return Derived; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Base extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Base.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BaseClient = ${Base._toInflightType(this).text}; + const client = new BaseClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class Derived extends Base { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Derived.js")({ + $Base: ${context._lift(Base)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const DerivedClient = ${Derived._toInflightType(this).text}; + const client = new DerivedClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + super._registerBind(host, ops); + } + static _registerTypeBind(host, ops) { + super._registerTypeBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/transitive_reference.snap b/libs/wingc/src/jsify/snapshots/transitive_reference.snap new file mode 100644 index 00000000000..731613c2439 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/transitive_reference.snap @@ -0,0 +1,172 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + class MyType { + b: cloud.Bucket; + + init() { + this.b = new cloud.Bucket(); + } + + inflight isEmpty(): bool { + return this.b.list().length == 0; + } + + inflight checkIfEmpty() { + if this.isEmpty() { + log("empty!"); + } + } + } + + let t = new MyType(); + test "test" { + t.checkIfEmpty(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $t }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $t.checkIfEmpty()); + } + } + return $Closure1; +} +``` + +## inflight.MyType.js + +```js +module.exports = function({ }) { + class MyType { + constructor({ $this_b }) { + this.$this_b = $this_b; + } + async isEmpty() { + return ((await this.$this_b.list()).length === 0); + } + async checkIfEmpty() { + if ((await this.isEmpty())) { + {console.log("empty!")}; + } + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("isEmpty", "checkIfEmpty", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + $this_b: ${this._lift(this.b)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("checkIfEmpty")) { + MyType._registerBindObject(this, host, ["isEmpty"]); + } + if (ops.includes("isEmpty")) { + MyType._registerBindObject(this.b, host, ["list"]); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $t: ${context._lift(t)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(t, host, ["checkIfEmpty"]); + } + super._registerBind(host, ops); + } + } + const t = new MyType(this,"MyType"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/transitive_reference_via_inflight_class.snap b/libs/wingc/src/jsify/snapshots/transitive_reference_via_inflight_class.snap new file mode 100644 index 00000000000..faa977a666d --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/transitive_reference_via_inflight_class.snap @@ -0,0 +1,145 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + let b = new cloud.Bucket(); + + inflight class MyInflightClass { + putInBucket() { + b.put("in", "bucket"); + } + } + + test "test" { + let obj = new MyInflightClass(); + obj.putInBucket(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $MyInflightClass }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const obj = new $MyInflightClass(); + (await obj.putInBucket()); + } + } + return $Closure1; +} +``` + +## inflight.MyInflightClass.js + +```js +module.exports = function({ $b }) { + class MyInflightClass { + async putInBucket() { + (await $b.put("in","bucket")); + } + } + return MyInflightClass; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyInflightClass extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("putInBucket", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyInflightClass.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyInflightClassClient = ${MyInflightClass._toInflightType(this).text}; + const client = new MyInflightClassClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("putInBucket")) { + MyInflightClass._registerBindObject(b, host, ["put"]); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $MyInflightClass: ${context._lift(MyInflightClass)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/transitive_reference_via_static.snap b/libs/wingc/src/jsify/snapshots/transitive_reference_via_static.snap new file mode 100644 index 00000000000..09eb4b9d485 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/transitive_reference_via_static.snap @@ -0,0 +1,204 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + + let b = new cloud.Bucket(); + + class MyType { + static inflight putInBucket() { + b.put("in", "bucket"); + } + } + + class YourType { + inflight putIndirect() { + MyType.putInBucket(); + } + } + + let t = new YourType(); + test "test" { + t.putIndirect(); + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $t }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $t.putIndirect()); + } + } + return $Closure1; +} +``` + +## inflight.MyType.js + +```js +module.exports = function({ $b }) { + class MyType { + constructor({ }) { + } + static async putInBucket() { + (await $b.put("in","bucket")); + } + } + return MyType; +} +``` + +## inflight.YourType.js + +```js +module.exports = function({ $MyType }) { + class YourType { + constructor({ }) { + } + async putIndirect() { + (await $MyType.putInBucket()); + } + } + return YourType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("putInBucket", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + static _registerTypeBind(host, ops) { + if (ops.includes("putInBucket")) { + MyType._registerBindObject(b, host, ["put"]); + } + super._registerTypeBind(host, ops); + } + } + class YourType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("putIndirect", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.YourType.js")({ + $MyType: ${context._lift(MyType)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const YourTypeClient = ${YourType._toInflightType(this).text}; + const client = new YourTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("putIndirect")) { + YourType._registerBindObject(MyType, host, ["putInBucket"]); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $t: ${context._lift(t)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(t, host, ["putIndirect"]); + } + super._registerBind(host, ops); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + const t = new YourType(this,"YourType"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/two_identical_lifts.snap b/libs/wingc/src/jsify/snapshots/two_identical_lifts.snap new file mode 100644 index 00000000000..fb19dd58659 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/two_identical_lifts.snap @@ -0,0 +1,107 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring cloud; + let b = new cloud.Bucket(); + + test "test" { + b.put("hello", "world"); + + () => { + b.put("hello", "world"); + }; + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $b }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $b.put("hello","world")); + async () => { + (await $b.put("hello","world")); + } + ; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(b, host, ["put"]); + } + super._registerBind(host, ops); + } + } + const b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/unqualified_lift.snap b/libs/wingc/src/jsify/snapshots/unqualified_lift.snap new file mode 100644 index 00000000000..5f1c16a6066 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/unqualified_lift.snap @@ -0,0 +1,5 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Errors +Cannot qualify access to a lifted object 6:6 diff --git a/libs/wingc/src/jsify/snapshots/unqualified_lift_of_collection.snap b/libs/wingc/src/jsify/snapshots/unqualified_lift_of_collection.snap new file mode 100644 index 00000000000..716a96b23fa --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/unqualified_lift_of_collection.snap @@ -0,0 +1,97 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + let a = [1,2,3]; + + test "test" { + a; + } + +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $a }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + $a; + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $a: ${context._lift(a)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(a, host, []); + } + super._registerBind(host, ops); + } + } + const a = Object.freeze([1, 2, 3]); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/use_util_functions.snap b/libs/wingc/src/jsify/snapshots/use_util_functions.snap new file mode 100644 index 00000000000..3dd906ad5d8 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/use_util_functions.snap @@ -0,0 +1,89 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring util; + test "test" { + util.env("PATH"); + } +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $util_Util }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $util_Util.env("PATH")); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const util = require('@winglang/sdk').util; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $util_Util: ${context._lift(util.Util)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/var_inflight_field_from_inflight.snap b/libs/wingc/src/jsify/snapshots/var_inflight_field_from_inflight.snap new file mode 100644 index 00000000000..83709fadd12 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/var_inflight_field_from_inflight.snap @@ -0,0 +1,102 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + class MyType { + inflight var s: str; + inflight init() { + this.s = "hey there!"; + } + inflight foo() { + log(this.s); + this.s = "hello!"; + } + } + +``` + +## inflight.MyType.js + +```js +module.exports = function({ }) { + class MyType { + constructor({ }) { + } + async foo() { + {console.log(this.s)}; + this.s = "hello!"; + } + async $inflight_init() { + this.s = "hey there!"; + } + } + return MyType; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyType extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "$inflight_init", "s"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyType.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyTypeClient = ${MyType._toInflightType(this).text}; + const client = new MyTypeClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + MyType._registerBindObject(this, host, ["s"]); + } + if (ops.includes("foo")) { + MyType._registerBindObject(this, host, ["s"]); + } + super._registerBind(host, ops); + } + } + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/snapshots/wait_util.snap b/libs/wingc/src/jsify/snapshots/wait_util.snap new file mode 100644 index 00000000000..47214c08e37 --- /dev/null +++ b/libs/wingc/src/jsify/snapshots/wait_util.snap @@ -0,0 +1,98 @@ +--- +source: libs/wingc/src/jsify/tests.rs +--- +## Code + +```w + + bring util; + + let foo = "test"; + + test "returns after some time waiting" { + let r = (): bool => { return true; }; + util.waitUntil(r); + } +``` + +## inflight.$Closure1.js + +```js +module.exports = function({ $util_Util }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + const r = async () => { + return true; + } + ; + (await $util_Util.waitUntil(r)); + } + } + return $Closure1; +} +``` + +## preflight.js + +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const util = require('@winglang/sdk').util; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $util_Util: ${context._lift(util.Util)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + const foo = "test"; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:returns after some time waiting",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "main", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); +``` + diff --git a/libs/wingc/src/jsify/tests.rs b/libs/wingc/src/jsify/tests.rs new file mode 100644 index 00000000000..4f3b0ca4e98 --- /dev/null +++ b/libs/wingc/src/jsify/tests.rs @@ -0,0 +1,1973 @@ +#[cfg(test)] +use crate::jsify::escape_javascript_string; + +#[test] +fn test_escape_javascript_string() { + assert_eq!(escape_javascript_string("hello"), String::from("hello")); + assert_eq!(escape_javascript_string("hello\nworld"), String::from("hello\\nworld")); + assert_eq!(escape_javascript_string("hello\rworld"), String::from("hello\\rworld")); + assert_eq!(escape_javascript_string("hello\tworld"), String::from("hello\\tworld")); + assert_eq!(escape_javascript_string("hello\\world"), String::from("hello\\\\world")); + assert_eq!(escape_javascript_string("hello'world"), String::from("hello\\'world")); + assert_eq!(escape_javascript_string("hello\"world"), String::from("hello\\\"world")); + assert_eq!(escape_javascript_string("hello\0world"), String::from("hello\\0world")); +} + +#[test] +fn free_preflight_object_from_preflight() { + assert_compile_ok!( + r#" + let x = "hello"; + + class A { + foo() { log(x); } + } + "# + ); +} + +#[test] +fn free_inflight_obj_from_inflight() { + assert_compile_ok!( + r#" + test "test" { + let y = "hello"; + + class A { + init() { + log(y); + } + } + } + "# + ); +} + +#[test] +fn call_static_inflight_from_static_inflight() { + assert_compile_ok!( + r#" + class A { + static inflight foo() { log("hello"); } + } + + inflight class B { + static bar() { + A.foo(); + } + } + "# + ); +} + +#[test] +fn static_local_inflight_class() { + assert_compile_ok!( + r#" + test "test" { + class A { + static foo() { log("hello"); } + } + + class B { + init() { + A.foo(); + } + } + + A.foo(); + } + "# + ); +} + +#[test] +fn static_external_inflight_class() { + assert_compile_ok!( + r#" + inflight class A { + static foo() { log("hello"); } + } + + test "test" { + class B { + callFoo() { + A.foo(); + } + } + + A.foo(); + } + "# + ); +} +#[test] +fn static_external_preflight_class() { + assert_compile_ok!( + r#" + class A { + static inflight foo() { log("hello"); } + } + + test "test" { + class B { + foo() { + A.foo(); + } + } + } + "# + ); +} + +#[test] +fn namespaced_static_from_inflight() { + assert_compile_ok!( + r#" + bring util; + test "test" { + util.tryEnv("PATH"); + } + "# + ); +} + +// -------------------------------------------------------------- +// preflight + +#[test] +fn lift_string() { + assert_compile_ok!( + r#" + let b = "hello"; + test "test" { + log(b); + } + "# + ); +} + +#[test] +fn fails_when_reassigning_preflight_variable() { + assert_compile_fail!( + r#" + let var a = "hello"; + inflight () => { + a = "world"; + }; + "# + ); +} + +#[test] +fn preflight_collection() { + assert_compile_ok!( + r#" + let a = ["hello", "world"]; + inflight () => { + assert(a.length == 2); + log(a.at(0)); + }; + "# + ); +} + +#[test] +fn preflight_object() { + assert_compile_ok!( + r#" + class A { + inflight hello() {} + inflight goodbye() {} + } + let pf_obj = new A(); + test "test" { + pf_obj.hello(); + pf_obj.goodbye(); + } + "# + ); +} + +#[test] +fn preflight_collection_of_preflight_objects() { + assert_compile_ok!( + r#" + bring cloud; + let arr = [ + new cloud.Bucket() as "b1", + new cloud.Bucket() as "b2" + ]; + test "test" { + assert(arr.length == 2); + arr.at(0).put("hello", "world"); + } + "# + ); +} + +#[test] +fn preflight_object_with_operations() { + assert_compile_ok!( + r#" + bring cloud; + let b = new cloud.Bucket(); + test "test" { + b.list(); + b.put("hello", "world"); + } + "# + ); +} + +#[test] +fn preflight_object_with_operations_multiple_methods() { + assert_compile_ok!( + r#" + bring cloud; + let b = new cloud.Bucket(); + + class Foo { + inflight put() { + b.put("hello1", "world"); + } + + inflight list() { + b.list(); + } + } + "# + ); +} + +#[test] +fn preflight_nested_object_with_operations() { + assert_compile_ok!( + r#" + bring cloud; + let b = new cloud.Bucket(); + class A { + bucky: cloud.Bucket; + init() { + this.bucky = b; + } + } + + let a = new A(); + test "test" { + a.bucky.list(); + } + "# + ); +} + +#[test] +fn static_inflight_operation() { + assert_compile_ok!( + r#" + bring cloud; + let b = new cloud.Bucket(); + + class A { + static inflight myop() { + b.list(); + } + } + + test "test" { + A.myop(); + } + "# + ); +} + +#[test] +fn inflight_field() { + assert_compile_ok!( + r#" + class A { + inflight x: str; + inflight init() { + this.x = "hello"; + } + + inflight method() { + log(this.x); + } + } + "# + ); +} + +#[test] +fn reference_inflight_field() { + assert_compile_ok!( + r#" + class Foo { + inflight x: str; + + inflight init() { + this.x = "hello"; + } + + inflight method() { + this.x; + } + } + "# + ); +} + +#[test] +fn reference_preflight_field() { + assert_compile_ok!( + r#" + class Foo { + x: str; + + init() { + this.x = "world"; + } + + inflight method() { + this.x; + } + } + "# + ); +} + +#[test] +fn reference_preflight_field_call_independent_method() { + assert_compile_ok!( + r#" + class Foo { + arr: Array; + + init() { + this.arr = ["hello", "world"]; + } + + inflight method() { + this.arr.at(1); + } + } + "# + ); +} + +#[test] +fn reference_preflight_free_variable_with_this_in_the_expression() { + assert_compile_ok!( + r#" + bring cloud; + let b = new cloud.Bucket(); + + class Foo { + name: str; + + init() { + this.name = "my_object"; + } + + inflight method() { + b.put(this.name, "value"); + } + } + "# + ); +} + +#[test] +fn lift_inflight_closure() { + assert_compile_ok!( + r#" + let f = inflight () => {}; + + inflight () => { + f(); + }; + "# + ); +} + +// ----------------------------------------------------------------------------- +// type references + +#[test] +fn capture_type_static_method() { + assert_compile_ok!( + r#" + class Foo { + static inflight bars(): str { return "bar"; } + } + + test "test" { + Foo.bars(); + } + "# + ); +} + +#[test] +fn capture_type_static_method_inflight_class() { + assert_compile_ok!( + r#" + inflight class Foo { + static bar(): str { return "bar"; } + } + + test "test" { + Foo.bar(); + } + "# + ); +} + +#[test] +fn capture_type_new_inflight_class_outer() { + assert_compile_ok!( + r#" + inflight class Foo { } + + test "test" { + new Foo(); + } + "# + ); +} + +#[test] +fn capture_type_new_inflight_class_inner_no_capture() { + assert_compile_ok!( + r#" + test "test" { + class Foo { } + new Foo(); + } + "# + ); +} + +#[test] +fn capture_type_inflight_class_sibling_from_init() { + assert_compile_ok!( + r#" + test "test" { + class Foo { } + let x = 12; + class Bar { + init() { + x; + new Foo(); + } + func() { + x; + new Foo(); + } + } + } + "# + ); +} + +#[test] +fn capture_type_inflight_class_sibling_from_method() { + assert_compile_ok!( + r#" + test "test" { + class Foo { } + class Bar { + myMethod() { + new Foo(); + } + } + } + "# + ); +} + +// --------------------------------------------- +// identifier + +#[test] +fn no_capture_of_identifier_from_same_scope() { + assert_compile_ok!( + r#" + test "test" { + let x = "hello"; + log(x); + } + "# + ); +} + +#[test] +fn no_capture_of_identifier_from_inner_scope() { + assert_compile_ok!( + r#" + test "test" { + let x = "hello"; + if true { + log(x); + } + } + "# + ); +} + +#[test] +fn capture_identifier_from_preflight_scope() { + assert_compile_ok!( + r#" + let x = "hello"; + test "test" { + log(x); + } + "# + ); +} + +#[test] +fn capture_identifier_from_preflight_scope_with_property() { + assert_compile_ok!( + r#" + let x = "hello"; + test "test" { + assert(x.length > 0); + } + "# + ); +} + +#[test] +fn capture_identifier_from_preflight_scope_with_method_call() { + assert_compile_ok!( + r#" + class Foo { + inflight bar() {} + } + + let f = new Foo(); + test "test" { + f.bar(); + } + "# + ); +} + +#[test] +fn capture_identifier_from_preflight_scope_with_nested_object() { + assert_compile_ok!( + r#" + bring cloud; + + class Foo { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + } + + let f = new Foo(); + test "test" { + f.b.put("hello", "world"); + } + "# + ); +} + +#[test] +fn capture_identifier_closure_from_preflight_scope() { + assert_compile_ok!( + r#" + let foo = inflight () => {}; + test "test" { + foo(); + } + "# + ); +} + +// ----------------- + +#[test] +fn read_primitive_value() { + assert_compile_ok!( + r#" + let x = "my_string"; + + test "test" { + log(x); + } + "# + ); +} + +#[test] +fn access_methods_and_properties_on_collections() { + assert_compile_ok!( + r#" + let x = [1,2,3]; + let y = ["hello"]; + + test "test" { + assert(x.length == 3); + assert(y.at(0) == "hello"); + } + "# + ); +} + +#[test] +fn access_property_on_primitive() { + assert_compile_ok!( + r#" + let s = "hello"; + + test "test" { + assert(s.length == 5); + } + "# + ); +} + +#[test] +fn access_property_on_value_returned_from_collection() { + assert_compile_ok!( + r#" + let s = { "hello" => "123" }; + + test "test" { + assert(s.get("hello").length == 3); + } + "# + ); +} + +#[test] +fn calls_methods_on_preflight_object() { + assert_compile_ok!( + r#" + bring cloud; + let b = new cloud.Bucket(); + + test "test" { + b.put("hello", "world"); + b.list(); + } + "# + ); +} + +#[test] +fn enum_value() { + assert_compile_ok!( + r#" + enum MyEnum { B, C } + let x = MyEnum.C; + + test "test" { + assert(MyEnum.B != MyEnum.C); + assert(x == MyEnum.C); + } + "# + ); +} + +#[test] +fn static_on_std_type() { + assert_compile_ok!( + r#" + test "test" { + log(str.fromJson("hello")); + assert(Json.values(Json {}).length == 0); + } + "# + ); +} + +#[test] +fn preflight_value_field() { + assert_compile_ok!( + r#" + class MyType { + name: str; + last: str; + + init() { + this.name = "hello"; + this.last = "world"; + } + } + + let t = new MyType(); + + test "test" { + log(t.name); + assert(t.name.length > 0); + log(t.last); + } + "# + ); +} + +#[test] +fn inflight_field_from_inflight() { + assert_compile_ok!( + r#" + class MyType { + inflight s: str; + inflight init() { + this.s = "hey there!"; + } + inflight foo() { + log(this.s); + } + } + "# + ); +} + +#[test] +fn nested_preflight_operation() { + assert_compile_ok!( + r#" + bring cloud; + class YourType { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + } + class MyType { + y: YourType; + init() { + this.y = new YourType(); + } + } + + let t = new MyType(); + + test "test" { + t.y.b.put("hello", "world"); + } + "# + ); +} + +#[test] +fn nested_inflight_after_preflight_operation() { + assert_compile_ok!( + r#" + bring cloud; + class YourType { + inflight b: str; + inflight init() { + this.b = "hello"; + } + } + + let y = new YourType(); + + test "test" { + log(y.b); + } + "# + ); +} + +#[test] +fn var_inflight_field_from_inflight() { + assert_compile_ok!( + r#" + class MyType { + inflight var s: str; + inflight init() { + this.s = "hey there!"; + } + inflight foo() { + log(this.s); + this.s = "hello!"; + } + } + "# + ); +} + +#[test] +fn preflight_object_through_property() { + assert_compile_ok!( + r#" + bring cloud; + + class MyType { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + } + + let t = new MyType(); + + test "test" { + t.b.put("hello", "world"); + } + "# + ); +} + +#[test] +fn fails_on_preflight_static() { + assert_compile_fail!( + r#" + class MyType { + static staticMethod(): str {} + } + + test "test" { + log(MyType.staticMethod()); + } + "# + ); +} + +#[test] +fn reference_static_inflight() { + assert_compile_ok!( + r#" + class MyType { + static inflight myStaticMethod(): str {} + } + + test "test" { + log(MyType.myStaticMethod()); + } + "# + ); +} + +// TODO: this currently doesn't work because we don't record the fact that "test" uses +// staticMethod() and therefore we don't bind to it, and then we don't bind to the bucket. +#[test] +fn reference_static_inflight_which_references_preflight_object() { + assert_compile_ok!( + r#" + bring cloud; + + let b = new cloud.Bucket(); + + class MyType { + static inflight staticMethod(): str { + b.list(); + return "foo"; + } + } + + test "test" { + log(MyType.staticMethod()); + } + "# + ); +} + +#[test] +fn reference_from_static_inflight() { + assert_compile_ok!( + r#" + let s = "hello"; + + class MyType { + static inflight staticMethod(): str { + return s; + } + } + "# + ); +} + +#[test] +fn reference_preflight_object_from_static_inflight() { + assert_compile_ok!( + r#" + bring cloud; + + let q = new cloud.Queue(); + + class MyType { + static inflight addToQueue(m: str) { + q.push(m); + } + } + "# + ); +} + +#[test] +fn new_inflight_object() { + assert_compile_ok!( + r#" + inflight class Foo {} + + test "test" { + new Foo(); + } + "# + ); +} + +#[test] +fn reference_preflight_fields() { + assert_compile_ok!( + r#" + bring cloud; + + class MyType { + s: str; + b: cloud.Bucket; + + init() { + this.s = "hello"; + this.b = new cloud.Bucket(); + } + + inflight boom() { + assert(this.s.length > 0); + assert(this.b.list().length > 0); + } + + inflight bam() { + this.b.put("hello", "world"); + this.b.get("aaa"); + } + } + "# + ); +} + +#[test] +fn transitive_reference() { + assert_compile_ok!( + r#" + bring cloud; + + class MyType { + b: cloud.Bucket; + + init() { + this.b = new cloud.Bucket(); + } + + inflight isEmpty(): bool { + return this.b.list().length == 0; + } + + inflight checkIfEmpty() { + if this.isEmpty() { + log("empty!"); + } + } + } + + let t = new MyType(); + test "test" { + t.checkIfEmpty(); + } + "# + ); +} + +#[test] +fn ref_std_macro() { + assert_compile_ok!( + r#" + let arr = [1,2,3]; + + test "test" { + assert(arr.length == 3); + } + "# + ); +} + +#[test] +fn fails_when_referencing_this_from_static() { + assert_compile_fail!( + r#" + class MyType { + static inflight hello() { + this.print(); + } + } + "# + ); +} + +#[test] +fn transitive_reference_via_static() { + assert_compile_ok!( + r#" + bring cloud; + + let b = new cloud.Bucket(); + + class MyType { + static inflight putInBucket() { + b.put("in", "bucket"); + } + } + + class YourType { + inflight putIndirect() { + MyType.putInBucket(); + } + } + + let t = new YourType(); + test "test" { + t.putIndirect(); + } + "# + ); +} + +#[test] +fn fails_if_referencing_unknown_field() { + assert_compile_fail!( + r#" + class MyInflightClass { + inflight putInBucket() { + this.b.put("in", "bucket"); + } + } + "# + ); +} + +#[test] +fn transitive_reference_via_inflight_class() { + assert_compile_ok!( + r#" + bring cloud; + + let b = new cloud.Bucket(); + + inflight class MyInflightClass { + putInBucket() { + b.put("in", "bucket"); + } + } + + test "test" { + let obj = new MyInflightClass(); + obj.putInBucket(); + } + "# + ); +} + +#[test] +fn reference_inflight_class() { + assert_compile_ok!( + r#" + inflight class Foo { + static a(): str { return "a"; } + } + + test "test" { + log(Foo.a()); + } + "# + ); +} + +#[test] +fn inline_inflight_class() { + assert_compile_ok!( + r#" + bring cloud; + class Foo { + b: cloud.Bucket; + q: cloud.Queue; + + init() { + this.b = new cloud.Bucket(); + this.q = new cloud.Queue(); + + this.q.setConsumer(inflight () => { + this.b.put("in", "bucket"); + }); + } + } + "# + ); +} + +#[test] +fn inflight_field_from_inflight_class() { + assert_compile_ok!( + r#" + inflight class MyType { + field: str; + init() { this.field = "hi"; } + + getField(): str { + return this.field; + } + } + "# + ); +} + +#[test] +fn reference_inflight_from_inflight() { + assert_compile_ok!( + r#" + + let s = "hello"; + + inflight class Foo { + foofoo1() { + log(s); + } + } + + test "test" { + let f = new Foo(); + + // class Bar { + // bar() { + // f.foofoo1(); + // } + // } + } + + "# + ); +} + +#[test] +fn json_object() { + assert_compile_ok!( + r#" + let jsonObj1 = Json { key1: "value1" }; + + test "test" { + log(Json.stringify(jsonObj1)); + } + "# + ); +} + +#[test] +fn capture_token() { + assert_compile_ok!( + r#" + bring cloud; + let api = new cloud.Api(); + test "test" { + log(api.url); + }"# + ); +} + +#[test] +fn use_util_functions() { + assert_compile_ok!( + r#" + bring util; + test "test" { + util.env("PATH"); + }"# + ); +} + +#[test] +fn wait_util() { + assert_compile_ok!( + r#" + bring util; + + let foo = "test"; + + test "returns after some time waiting" { + let r = (): bool => { return true; }; + util.waitUntil(r); + }"# + ); +} + +#[test] +fn capture_from_inside_an_inflight_closure() { + assert_compile_ok!( + r#" + bring util; + + let foo = "test"; + + test "my test" { + let r = (): str => { return foo; }; + }"# + ); +} + +#[test] +fn capture_in_keyword_args() { + assert_compile_ok!( + r#" + bring util; + + let x = 1s; + + test "test" { + util.waitUntil((): bool => {}, interval: x); + } + "# + ); +} + +#[test] +fn lift_binary_preflight_expression() { + assert_compile_ok!( + r#" + let x = 1; + let y = 2; + test "test" { + x + y; + } + "# + ); +} + +#[test] +fn lift_binary_preflight_and_inflight_expression() { + assert_compile_ok!( + r#" + let x = 1; + test "test" { + let y = 2; + x + y; + } + "# + ); +} + +#[test] +fn builtins() { + assert_compile_ok!( + r#" + test "test" { + log("hello"); + } + "# + ); +} + +#[test] +fn fail_unqualified_lift() { + assert_compile_fail!( + r#" + bring cloud; + + let q = new cloud.Queue(); + + test "test "{ + q; + } + "# + ); +} + +#[test] +fn unqualified_lift_of_collection() { + assert_compile_ok!( + r#" + let a = [1,2,3]; + + test "test" { + a; + } + "# + ); +} + +#[test] +fn fails_lift_with_inflight_arguments() { + assert_compile_fail!( + r#" + let a = [1234]; + + test "test" { + let i = 0; + a.at(i); + } + "# + ); +} + +#[test] +fn fail_unqualified_lift_element_from_collection_of_objects() { + assert_compile_fail!( + r#" + bring cloud; + let a = [new cloud.Bucket()]; + + test "test" { + a.at(0); + } + "# + ); +} + +#[test] +fn lift_element_from_collection_of_objects() { + assert_compile_ok!( + r#" + bring cloud; + let a = [new cloud.Bucket()]; + + test "test" { + a.at(0).put("hello", "world"); + } + "# + ); +} + +#[test] +fn lift_element_from_collection_as_field() { + assert_compile_ok!( + r#" + bring cloud; + class Foo { + arr: Array; + init() { + this.arr = [new cloud.Bucket()]; + } + + inflight foo() { + this.arr.at(0).put("hello", "world"); + } + } + "# + ); +} + +#[test] +fn no_capture_inside_methods() { + assert_compile_ok!( + r#" + test "test" { + let start = 12; + if true { + start; + } + } + "# + ); +} + +#[test] +fn inflight_constructor() { + assert_compile_ok!( + r#" + class Foo { + inflight x: str; + + inflight init() { + this.x = "hello"; + } + + inflight foo() { + this.x; + } + } + "# + ) +} + +#[test] +fn func_returns_func() { + assert_compile_ok!( + r#" + test "test" { + (s: str): (): bool => { + (): bool => { + s; + }; + }; + } + "# + ); +} + +// ------------------------------- +// base classes + +#[test] +fn preflight_class_extends_preflight_class() { + assert_compile_ok!( + r#" + class Base {} + class Derived extends Base {} + "# + ); +} + +#[test] +fn inflight_class_extends_both_inside_inflight_closure() { + assert_compile_ok!( + r#" + test "test" { + class A {} + class B extends A {} + } + "# + ); +} + +#[test] +fn inflight_class_extends_inflight_class() { + assert_compile_ok!( + r#" + inflight class A {} + inflight class B extends A {} + "# + ); +} + +#[test] +fn fails_when_inflight_class_tries_to_extend_preflight_class() { + assert_compile_fail!( + r#" + class Base {} + inflight class Derived extends Base {} + "# + ); +} + +#[test] +fn fails_when_preflight_class_tries_to_extend_inflight_class() { + assert_compile_fail!( + r#" + inflight class Base {} + class Derived extends Base {} + "# + ); +} + +#[test] +fn closed_inflight_class_extends_outer_inflight_class() { + assert_compile_ok!( + r#" + inflight class Base { } + + test "test" { + inflight class Derived extends Base { } + new Derived(); + } + "# + ); +} + +#[test] +fn base_class_captures_preflight() { + assert_compile_ok!( + r#" + let x = "hello"; + + class Base { + bar() { + log(x); + } + } + + class Derived extends Base { + foo() { + this.bar(); + } + } + "# + ); +} + +#[test] +fn base_class_captures_inflight() { + assert_compile_ok!( + r#" + let x = "hello"; + + class Base { + inflight bar() { + log(x); + } + } + + class Derived extends Base { + inflight foo() { + this.bar(); + } + } + "# + ) +} + +#[test] +fn base_class_with_fields_preflight() { + assert_compile_ok!( + r#" + class Base { + f: str; + init() { + this.f = "hello"; + } + } + + class Derived extends Base { + g: str; + init() { + this.g = "world"; + } + + foo() { + this.f; + this.g; + } + } + "# + ); +} + +#[test] +fn base_class_with_fields_inflight() { + assert_compile_ok!( + r#" + class Base { + inflight f: str; + inflight init() { + this.f = "hello"; + } + } + + class Derived extends Base { + inflight g: str; + inflight init() { + this.g = "world"; + } + + inflight foo() { + this.f; + this.g; + } + } + "# + ); +} + +#[test] +fn base_class_with_lifted_fields() { + assert_compile_ok!( + r#" + let x = "hello"; + + class Base { + f: str; + init() { + this.f = x; + } + } + + class Derived extends Base { + inflight foo() { + this.f; + } + } + "# + ); +} + +#[test] +fn fails_base_class_with_lifted_field_object_unqualified() { + assert_compile_fail!( + r#" + bring cloud; + + class Base { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + } + + class Derived extends Base { + inflight foo() { + this.b; +// ^ Cannot qualify access to a lifted object of type "Bucket" + } + } + "# + ); +} + +#[test] +fn base_class_with_lifted_field_object() { + assert_compile_ok!( + r#" + bring cloud; + + class Base { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + } + + class Derived extends Base { + inflight foo() { + this.b.put("hello", "world"); + } + } + "# + ); +} + +#[test] +fn base_class_lift_indirect() { + assert_compile_ok!( + r#" + bring cloud; + + class Base { + b: cloud.Bucket; + init() { + this.b = new cloud.Bucket(); + } + + inflight put() { + this.b.put("hello", "world"); + this.b.list(); + } + } + + class Derived extends Base { + inflight foo() { + this.put(); + } + } + "# + ) +} + +#[test] +fn lift_via_closure() { + assert_compile_ok!( + r#" + bring cloud; + + let bucket = new cloud.Bucket(); + + let fn = inflight () => { + bucket.put("hello", "world"); + }; + + test "test" { + fn(); + } + "# + ); +} + +#[test] +fn indirect_capture() { + assert_compile_ok!( + r#" + bring cloud; + let b = new cloud.Bucket(); + + class Capture { + q: cloud.Queue; + init() { this.q = new cloud.Queue(); } + + inflight foo() { + b.list(); + } + + inflight goo() { + this.foo(); + } + } + + let f = new Capture(); + test "test" { + f.goo(); + } + "# + ); +} + +#[test] +fn lift_via_closure_class_explicit() { + assert_compile_ok!( + r#" + bring cloud; + + class MyClosure { + q: cloud.Queue; + init() { + this.q = new cloud.Queue(); + } + + inflight handle() { + this.another(); + } + + inflight another() { + this.q.push("hello"); + } + } + + let fn = new MyClosure(); + + test "test" { + fn(); + } + "# + ); +} + +#[test] +fn lift_this() { + assert_compile_ok!( + r#" + class Foo { + inflight x: num; + inflight init() { + this.x = 42; + } + inflight bar(): num { + return this.x; + } + inflight foo(): num { + return this.bar() / 2; + } + } + + let f = new Foo(); + + test "test" { + assert(f.foo() == 21); + } + "# + ); +} + +#[test] +fn reassign_captured_variable() { + // TODO: https://github.com/winglang/wing/issues/3249 (this should fail) + assert_compile_ok!( + r#" + test "test" { + let var i = 10; + + class Inner { + dang(): num { + i = i + 1; + } + } + } + "# + ); +} + +#[test] +fn reassigned_captured_variable_preflight() { + // TODO: https://github.com/winglang/wing/issues/3249 (this should fail) + assert_compile_ok!( + r#" + let var i = 10; + () => { + i = 12; + }; + "# + ); +} + +#[test] +fn no_capture_shadow_inside_inner_scopes() { + assert_compile_ok!( + r#" + test "testing" { + let arr = MutArray [0]; + + let i = 1; + arr.push(i); + + if true { + let i = 2; + arr.push(i); + } + } + "# + ); +} + +#[test] +fn no_lift_shadow_inside_inner_scopes() { + assert_compile_ok!( + r#" + let i = 1; + test "testing" { + let arr = MutArray [0]; + arr.push(i); + + if true { + let i = 2; + arr.push(i); + } + } + "# + ); +} + +#[test] +fn capture_var_from_method_inflight() { + assert_compile_ok!( + r#" + test "test" { + let x = 12; + class Foo { + getX(): num { return x; } + } + } + "# + ) +} + +#[test] +fn closure_field() { + assert_compile_ok!( + r#" + bring cloud; + let globalBucket = new cloud.Bucket(); + + class MyResource { + closure: inflight (str): str; + + init() { + this.closure = inflight (s: str): str => { + globalBucket.list(); + return "hello"; + }; + } + + inflight foo(): str { + return this.closure("anything"); + } + } + + let x = new MyResource(); + + test "variable can be an inflight closure" { + let val = x.foo(); + assert(val == "hello"); + } + "# + ) +} + +#[test] +fn fails_invalid_closure_type() { + assert_compile_fail!( + r#" + bring cloud; + new cloud.Function(inflight (s: num) => {}); + "# + ) +} +#[test] +fn capture_object_with_this_in_name() { + assert_compile_ok!( + r#" + bring cloud; + let bucket_this = new cloud.Bucket(); + let fn = inflight () => { + bucket_this.put("this", "is not a field"); + }; + "# + ) +} + +#[test] +fn identify_field() { + assert_compile_ok!( + r#" + bring cloud; + class A { + bucket_this: cloud.Bucket; + + init() { this.bucket_this = new cloud.Bucket(); } + + inflight foo() { + (this.bucket_this).put("hello", "world"); + } + } + "# + ) +} + +#[test] +fn lift_var_with_this() { + assert_compile_ok!( + r#" + class Foo { + value: str; + init() { this.value = "hello"; } + } + + let foo_this = new Foo(); + test "test" { + assert(foo_this.value == "hello"); + } + "# + ) +} + +#[test] +fn two_identical_lifts() { + assert_compile_ok!( + r#" + bring cloud; + let b = new cloud.Bucket(); + + test "test" { + b.put("hello", "world"); + + () => { + b.put("hello", "world"); + }; + } + "# + ) +} + +#[test] +fn lift_inside_preflight_method() { + assert_compile_ok!( + r#" + bring cloud; + + class Foo { + defineBucket(name: str) { + let b = new cloud.Bucket() as name; + inflight () => { + b.put("dirty","x"); + }; + } + + init() { + this.defineBucket("b1"); + this.defineBucket("b2"); + } + } + "# + ) +} diff --git a/libs/wingc/src/lib.rs b/libs/wingc/src/lib.rs index d2f3cda08b0..12956202317 100644 --- a/libs/wingc/src/lib.rs +++ b/libs/wingc/src/lib.rs @@ -14,6 +14,7 @@ use diagnostic::{found_errors, report_diagnostic, Diagnostic}; use files::Files; use fold::Fold; use jsify::JSifier; +use lifting::LiftTransform; use type_check::jsii_importer::JsiiImportSpec; use type_check::symbol_env::StatementIdx; use type_check::{FunctionSignature, SymbolKind, Type}; @@ -34,6 +35,10 @@ use crate::ast::Phase; use crate::type_check::symbol_env::SymbolEnv; use crate::type_check::{FunctionParameter, TypeChecker, Types}; +#[macro_use] +#[cfg(test)] +mod test_utils; + pub mod ast; pub mod closure_transform; mod comp_ctx; @@ -43,11 +48,14 @@ mod docs; mod files; pub mod fold; pub mod jsify; +mod lifting; pub mod lsp; pub mod parser; + pub mod type_check; mod type_check_assert; pub mod visit; +mod visit_context; mod wasm_util; const WINGSDK_ASSEMBLY_NAME: &'static str = "@winglang/sdk"; @@ -344,11 +352,6 @@ pub fn compile( let mut tc_assert = TypeCheckAssert::new(&types, found_errors()); tc_assert.check(&scope); - // bail out now (before jsification) if there are errors (no point in jsifying) - if found_errors() { - return Err(()); - } - // -- JSIFICATION PHASE -- let app_name = source_path.file_stem().unwrap().to_str().unwrap(); @@ -365,9 +368,24 @@ pub fn compile( return Err(()); } - let mut jsifier = JSifier::new(&types, &files, app_name, &project_dir, true); - jsifier.jsify(&scope); - jsifier.emit_files(&out_dir); + let mut jsifier = JSifier::new(&mut types, &files, app_name, &project_dir, true); + + // -- LIFTING PHASE -- + + let mut lift = LiftTransform::new(&jsifier); + let scope = Box::new(lift.fold_scope(scope)); + + // bail out now (before jsification) if there are errors (no point in jsifying) + if found_errors() { + return Err(()); + } + + let files = jsifier.jsify(&scope); + + match files.emit_files(out_dir) { + Ok(()) => {} + Err(err) => report_diagnostic(err.into()), + } if found_errors() { return Err(()); diff --git a/libs/wingc/src/lifting.rs b/libs/wingc/src/lifting.rs new file mode 100644 index 00000000000..fe88c71fe24 --- /dev/null +++ b/libs/wingc/src/lifting.rs @@ -0,0 +1,367 @@ +use crate::{ + ast::{Class, Expr, ExprKind, FunctionBody, FunctionDefinition, Phase, Reference, UserDefinedType}, + comp_ctx::{CompilationContext, CompilationPhase}, + diagnostic::{report_diagnostic, Diagnostic, WingSpan}, + files::Files, + fold::{self, Fold}, + jsify::{JSifier, JSifyContext}, + type_check::{lifts::Lifts, resolve_user_defined_type, symbol_env::LookupResult, CLOSURE_CLASS_HANDLE_METHOD}, + visit_context::VisitContext, +}; + +pub struct LiftTransform<'a> { + ctx: VisitContext, + jsify: &'a JSifier<'a>, + lifts_stack: Vec, +} + +impl<'a> LiftTransform<'a> { + pub fn new(jsifier: &'a JSifier<'a>) -> Self { + Self { + jsify: jsifier, + ctx: VisitContext::new(), + lifts_stack: vec![], + } + } + + fn is_self_type_reference(&self, node: &Expr) -> bool { + let Some(current_class_udt) = self.ctx.current_class() else { + return false; + }; + + let Some(udt) = node.as_type_reference() else { + return false; + }; + + udt.full_path_str() == current_class_udt.full_path_str() + } + + fn is_defined_in_current_env(&self, fullname: &str, span: &WingSpan) -> bool { + // if the symbol is defined later in the current environment, it means we can't capture a + // reference to a symbol with the same name from a parent so bail out. + // notice that here we are looking in the current environment and not in the method's environment + if let Some(env) = self.ctx.current_env() { + let lookup = env.lookup_nested_str(&fullname, Some(self.ctx.current_stmt_idx())); + + match lookup { + LookupResult::Found(_, e) => { + // if we found the symbol in the current environment, it means we don't need to capture it at all + if e.env.is_same(env) { + return true; + } + } + LookupResult::DefinedLater => { + report_diagnostic(Diagnostic { + span: Some(span.clone()), + message: format!( + "Cannot capture symbol \"{fullname}\" because it is shadowed by another symbol with the same name" + ), + }); + return true; + } + LookupResult::NotFound(_) | LookupResult::ExpectedNamespace(_) => {} + } + } + + return false; + } + + fn should_capture_expr(&self, node: &Expr) -> bool { + let ExprKind::Reference(ref r) = node.kind else { + return false; + }; + + let (fullname, span) = match r { + Reference::Identifier(ref symb) => (symb.name.clone(), symb.span.clone()), + Reference::TypeReference(ref t) => (t.full_path_str(), t.span.clone()), + _ => return false, + }; + + // skip "This" (which is the type of "this") + if let Some(class) = &self.ctx.current_class() { + if class.full_path_str() == fullname { + return false; + } + } + + // if the symbol is defined in the *current* environment (which could also be a nested scope + // inside the current method), we don't need to capture it + if self.is_defined_in_current_env(&fullname, &span) { + return false; + } + + let Some(method_env) = self.ctx.current_method_env() else { + return false; + }; + + let lookup = method_env.lookup_nested_str(&fullname, Some(self.ctx.current_stmt_idx())); + + // any other lookup failure is likely a an invalid reference so we can skip it + let LookupResult::Found(vi, symbol_info) = lookup else { + return false; + }; + + // now, we need to determine if the environment this symbol is defined in is a parent of the + // method's environment. if it is, we need to capture it. + if symbol_info.env.is_same(&method_env) || symbol_info.env.is_child_of(&method_env) { + return false; + } + + // the symbol is defined in a parent environment, but it's still an inflight environment + // which means we don't need to capture. + if symbol_info.phase == Phase::Inflight && symbol_info.env.phase == Phase::Inflight { + return false; + } + + // skip macros + if let Some(x) = vi.as_variable() { + if let Some(f) = x.type_.as_function_sig() { + if f.js_override.is_some() { + return false; + } + } + } + + return true; + } + + fn jsify_expr(&self, node: &Expr, phase: Phase) -> String { + self.jsify.jsify_expression( + &node, + &mut JSifyContext { + in_json: false, + phase: phase, + files: &mut Files::default(), + lifts: None, + }, + ) + } +} + +impl<'a> Fold for LiftTransform<'a> { + fn fold_reference(&mut self, node: Reference) -> Reference { + match node { + Reference::InstanceMember { + object, + property, + optional_accessor, + } => { + self.ctx.push_property(property.name.clone()); + let result = Reference::InstanceMember { + object: Box::new(self.fold_expr(*object)), + property: self.fold_symbol(property), + optional_accessor, + }; + self.ctx.pop_property(); + return result; + } + Reference::TypeMember { typeobject, property } => { + self.ctx.push_property(property.name.clone()); + let result = Reference::TypeMember { + typeobject: Box::new(self.fold_expr(*typeobject)), + property: self.fold_symbol(property), + }; + self.ctx.pop_property(); + return result; + } + _ => {} + } + + fold::fold_reference(self, node) + } + + fn fold_expr(&mut self, node: Expr) -> Expr { + CompilationContext::set(CompilationPhase::Lifting, &node.span); + + let expr_phase = self.jsify.types.get_expr_phase(&node).unwrap(); + let expr_type = self.jsify.types.get_expr_type(&node).unwrap(); + + // this whole thing only applies to inflight expressions + if self.ctx.current_phase() == Phase::Preflight { + return fold::fold_expr(self, node); + } + + // if this expression represents the current class, no need to capture it (it is by definition + // available in the current scope) + if self.is_self_type_reference(&node) { + return fold::fold_expr(self, node); + } + + //--------------- + // LIFT + if expr_phase == Phase::Preflight { + // jsify the expression so we can get the preflight code + let code = self.jsify_expr(&node, Phase::Preflight); + + let property = if let Some(property) = self.ctx.current_property() { + Some(property) + } else if expr_type.is_closure() { + // this is the case where we are lifting a "closure class" (e.g. a class that has a "handle" + // method) the reason we might not have "property" set is because closure classes might be + // syntheticaly generated by the compiler from closures. + Some(CLOSURE_CLASS_HANDLE_METHOD.to_string()) + } else { + None + }; + + // check that we can qualify the lift (e.g. determine which property is being accessed) + if property.is_none() && expr_type.as_preflight_class().is_some() { + report_diagnostic(Diagnostic { + message: format!( + "Cannot qualify access to a lifted object of type \"{}\" (see https://github.com/winglang/wing/issues/76 for more details)", + expr_type.to_string() + ), + span: Some(node.span.clone()), + }); + + return node; + } + + let mut lifts = self.lifts_stack.pop().unwrap(); + lifts.lift(node.id, self.ctx.current_method(), property, &code); + self.lifts_stack.push(lifts); + + return node; + } + + //--------------- + // CAPTURE + + if self.should_capture_expr(&node) { + // jsify the expression so we can get the preflight code + let code = self.jsify_expr(&node, Phase::Inflight); + + let mut lifts = self.lifts_stack.pop().unwrap(); + lifts.capture(&node.id, &code); + self.lifts_stack.push(lifts); + + return node; + } + + fold::fold_expr(self, node) + } + + // State Tracking + + fn fold_function_definition(&mut self, node: FunctionDefinition) -> FunctionDefinition { + match node.body { + FunctionBody::Statements(scope) => { + self.ctx.push_function_definition( + &node.name, + &node.signature.phase, + scope.env.borrow().as_ref().unwrap().get_ref(), + ); + + let result = FunctionDefinition { + name: node.name.clone().map(|f| f.clone()), + body: FunctionBody::Statements(self.fold_scope(scope)), + signature: self.fold_function_signature(node.signature.clone()), + is_static: node.is_static, + span: node.span.clone(), + }; + + self.ctx.pop_function_definition(); + + return result; + } + FunctionBody::External(_) => {} + } + + fold::fold_function_definition(self, node) + } + + fn fold_class(&mut self, node: Class) -> Class { + // nothing to do if we are emitting an inflight class from within an inflight scope + if self.ctx.current_phase() == Phase::Inflight && node.phase == Phase::Inflight { + return Class { + name: self.fold_symbol(node.name), + fields: node + .fields + .into_iter() + .map(|field| self.fold_class_field(field)) + .collect(), + methods: node + .methods + .into_iter() + .map(|(name, def)| (self.fold_symbol(name), fold::fold_function_definition(self, def))) + .collect(), + initializer: fold::fold_function_definition(self, node.initializer), + parent: node.parent.map(|parent| self.fold_expr(parent)), + implements: node + .implements + .into_iter() + .map(|interface| self.fold_user_defined_type(interface)) + .collect(), + phase: node.phase, + inflight_initializer: fold::fold_function_definition(self, node.inflight_initializer), + }; + } + + // extract the "env" from the class initializer and push it to the context + // because this is the environment in which we want to resolve references + // as oppose to the environment of the class definition itself. + let init_env = if let FunctionBody::Statements(ref s) = node.initializer.body { + Some(s.env.borrow().as_ref().unwrap().get_ref()) + } else { + None + }; + + if self.ctx.current_phase() == Phase::Inflight { + if let Some(parent) = &node.parent { + if self.should_capture_expr(parent) { + let mut lifts = self.lifts_stack.pop().unwrap(); + lifts.capture(&parent.id, &self.jsify_expr(&parent, Phase::Inflight)); + self.lifts_stack.push(lifts); + } + } + } + + let udt = UserDefinedType { + root: node.name.clone(), + fields: vec![], + span: node.name.span.clone(), + }; + + self.ctx.push_class(udt.clone(), &node.phase, init_env); + + self.lifts_stack.push(Lifts::new()); + + if let Some(parent) = &node.parent { + let mut lifts = self.lifts_stack.pop().unwrap(); + lifts.capture(&parent.id, &self.jsify_expr(&parent, Phase::Inflight)); + self.lifts_stack.push(lifts); + } + + let result = fold::fold_class(self, node); + + self.ctx.pop_class(); + + let lifts = self.lifts_stack.pop().expect("Unable to pop class tokens"); + + if let Some(env) = &self.ctx.current_env() { + if let Some(mut t) = resolve_user_defined_type(&udt, env, 0).ok() { + let mut_class = t.as_class_mut().unwrap(); + mut_class.set_lifts(lifts); + } + } + + result + } + + fn fold_scope(&mut self, node: crate::ast::Scope) -> crate::ast::Scope { + self.ctx.push_env(node.env.borrow().as_ref().unwrap().get_ref()); + let result = fold::fold_scope(self, node); + self.ctx.pop_env(); + result + } + + fn fold_stmt(&mut self, node: crate::ast::Stmt) -> crate::ast::Stmt { + CompilationContext::set(CompilationPhase::Lifting, &node.span); + + self.ctx.push_stmt(node.idx); + let result = fold::fold_stmt(self, node); + self.ctx.pop_stmt(); + + result + } +} diff --git a/libs/wingc/src/lsp/signature.rs b/libs/wingc/src/lsp/signature.rs index 54c426d51a5..cd4a8554ff0 100644 --- a/libs/wingc/src/lsp/signature.rs +++ b/libs/wingc/src/lsp/signature.rs @@ -8,7 +8,7 @@ use crate::ast::{Expr, ExprKind, Symbol}; use crate::docs::Documented; use crate::lsp::sync::FILES; -use crate::type_check::{resolve_udt_from_expr, resolve_user_defined_type, CLASS_INIT_NAME}; +use crate::type_check::{resolve_user_defined_type, CLASS_INIT_NAME}; use crate::visit::{visit_expr, Visit}; use crate::wasm_util::{ptr_to_string, string_to_combined_ptr, WASM_RETURN_ERROR}; @@ -43,7 +43,7 @@ pub fn on_signature_help(params: lsp_types::SignatureHelpParams) -> Option { - let Some(udt) = resolve_udt_from_expr(class).ok() else { + let Some(udt) = class.as_type_reference() else { return None; }; diff --git a/libs/wingc/src/lsp/sync.rs b/libs/wingc/src/lsp/sync.rs index 0c0a6f9d2e0..790b6569ed0 100644 --- a/libs/wingc/src/lsp/sync.rs +++ b/libs/wingc/src/lsp/sync.rs @@ -146,7 +146,7 @@ fn partial_compile(source_file: &str, text: &[u8], jsii_types: &mut TypeSystem) let app_name = source_path.file_stem().expect("Empty filename").to_str().unwrap(); let project_dir = source_path.parent().expect("Empty filename"); - let mut jsifier = JSifier::new(&types, &files, app_name, &project_dir, true); + let mut jsifier = JSifier::new(&mut types, &files, app_name, &project_dir, true); jsifier.jsify(&scope); return FileData { diff --git a/libs/wingc/src/parser.rs b/libs/wingc/src/parser.rs index 81ad87b5082..f4a10b1ab69 100644 --- a/libs/wingc/src/parser.rs +++ b/libs/wingc/src/parser.rs @@ -14,6 +14,7 @@ use crate::ast::{ }; use crate::comp_ctx::{CompilationContext, CompilationPhase}; use crate::diagnostic::{report_diagnostic, Diagnostic, DiagnosticResult, WingSpan}; +use crate::type_check::{CLASS_INFLIGHT_INIT_NAME, CLASS_INIT_NAME}; use crate::{dbg_panic, WINGSDK_STD_MODULE, WINGSDK_TEST_CLASS_NAME}; pub struct Parser<'a> { @@ -628,23 +629,22 @@ impl<'s> Parser<'s> { continue; } match class_element.kind() { - "method_definition" => { - let method_name = self.node_symbol(&class_element.child_by_field_name("name").unwrap()); - let is_static = class_element.child_by_field_name("static").is_some(); - let func_def = self.build_function_definition(&class_element, class_phase, is_static); - match (method_name, func_def) { - (Ok(method_name), Ok(func_def)) => methods.push((method_name, func_def)), - _ => {} + "method_definition" | "inflight_method_definition" => { + let mut phase = class_phase; + if class_element.kind() == "inflight_method_definition" { + phase = Phase::Inflight; } - } - "inflight_method_definition" => { - let method_name = self.node_symbol(&class_element.child_by_field_name("name").unwrap()); + let is_static = class_element.child_by_field_name("static").is_some(); - let func_def = self.build_function_definition(&class_element, Phase::Inflight, is_static); - match (method_name, func_def) { - (Ok(method_name), Ok(func_def)) => methods.push((method_name, func_def)), - _ => {} - } + let Ok(method_name) = self.node_symbol(&class_element.child_by_field_name("name").unwrap()) else { + continue; + }; + + let Ok(func_def) = self.build_function_definition(Some(method_name.clone()), &class_element, phase, is_static) else { + continue; + }; + + methods.push((method_name, func_def)) } "class_field" => { let is_static = class_element.child_by_field_name("static").is_some(); @@ -710,6 +710,7 @@ impl<'s> Parser<'s> { if is_inflight { inflight_initializer = Some(FunctionDefinition { + name: Some(CLASS_INFLIGHT_INIT_NAME.into()), body: FunctionBody::Statements( self.build_scope(&class_element.child_by_field_name("block").unwrap(), Phase::Inflight), ), @@ -723,6 +724,7 @@ impl<'s> Parser<'s> { }) } else { initializer = Some(FunctionDefinition { + name: Some(CLASS_INIT_NAME.into()), body: FunctionBody::Statements( self.build_scope(&class_element.child_by_field_name("block").unwrap(), Phase::Preflight), ), @@ -760,6 +762,7 @@ impl<'s> Parser<'s> { Some(init) => init, // add a default initializer if none is defined None => FunctionDefinition { + name: Some(CLASS_INIT_NAME.into()), signature: FunctionSignature { parameters: vec![], return_type: Box::new(TypeAnnotation { @@ -783,6 +786,7 @@ impl<'s> Parser<'s> { // add a default inflight initializer if none is defined None => FunctionDefinition { + name: Some(CLASS_INFLIGHT_INIT_NAME.into()), signature: FunctionSignature { parameters: vec![], return_type: Box::new(TypeAnnotation { @@ -959,11 +963,12 @@ impl<'s> Parser<'s> { } fn build_anonymous_closure(&self, anon_closure_node: &Node, phase: Phase) -> DiagnosticResult { - self.build_function_definition(anon_closure_node, phase, true) + self.build_function_definition(None, anon_closure_node, phase, true) } fn build_function_definition( &self, + name: Option, func_def_node: &Node, phase: Phase, is_static: bool, @@ -978,6 +983,7 @@ impl<'s> Parser<'s> { }; Ok(FunctionDefinition { + name, body: statements, signature, is_static, @@ -1837,6 +1843,7 @@ impl<'s> Parser<'s> { let inflight_closure = Expr::new( ExprKind::FunctionClosure(FunctionDefinition { + name: None, body: FunctionBody::Statements(statements), signature: FunctionSignature { parameters: vec![], diff --git a/libs/wingc/src/test_utils.rs b/libs/wingc/src/test_utils.rs new file mode 100644 index 00000000000..d4c982ee83c --- /dev/null +++ b/libs/wingc/src/test_utils.rs @@ -0,0 +1,118 @@ +use itertools::Itertools; +use std::fs::{read_dir, File}; +use std::{env, io::Write}; +use tempfile; + +use crate::{ + compile, + diagnostic::{found_errors, get_diagnostics}, +}; + +#[macro_export] +macro_rules! assert_compile_ok { + ($code:literal) => { + insta::with_settings!({ + prepend_module_to_snapshot => false, + omit_expression => true, + }, { + insta::assert_snapshot!($crate::test_utils::compile_ok($code)); + }) + }; +} + +#[macro_export] +macro_rules! assert_compile_fail { + ($code:literal) => { + insta::with_settings!({ + prepend_module_to_snapshot => false, + omit_expression => true, + }, { + insta::assert_snapshot!($crate::test_utils::compile_fail($code)); + }) + }; +} + +pub fn compile_ok(code: &str) -> String { + let snap = compile_code(code); + if found_errors() { + get_diagnostics().iter().for_each(|d| println!("{}", d)); + assert!(false, "expected no errors"); + } + snap +} + +pub fn compile_fail(code: &str) -> String { + let snap = compile_code(code); + assert!(found_errors()); + snap +} + +/// Compiles `code` and returns the capture scanner results as a string that can be snapshotted +fn compile_code(code: &str) -> String { + let workdir = tempfile::tempdir().unwrap(); + let outdir = tempfile::tempdir().unwrap(); + + let path = workdir.path().join("main.w"); + + // NOTE: this is needed for debugging to work regardless of where you run the test + env::set_current_dir(env!("CARGO_MANIFEST_DIR")).unwrap(); + + // convert tabs to 2 spaces + let code = code.replace("\t", " "); + + let mut f = File::create(&path).unwrap(); + f.write_all(code.as_bytes()).unwrap(); + + let source_path = path.as_path(); + + let result = compile(source_path, Some(outdir.path()), Some(workdir.path())); + + let mut snap = vec![]; + + match result { + Ok(_) => { + let Ok(files) = read_dir(outdir.path()) else { + panic!("failed to read dir"); + }; + + snap.push("## Code".to_string()); + snap.push("".into()); + snap.push("```w".into()); + snap.push(code); + snap.push("```".into()); + snap.push("".into()); + + let files = files + .filter(|f| f.is_ok()) + .map(|f| f.unwrap().path()) + .sorted_by_key(|f| f.as_os_str().to_string_lossy().to_string()) + .collect::>(); + + for path in files { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + let contents = std::fs::read_to_string(&path).unwrap(); + snap.push(format!("## {name}")); + snap.push("".into()); + snap.push("```js".into()); + snap.push(contents.trim().into()); + snap.push("```".into()); + snap.push("".into()); + } + } + Err(_) => { + snap.push("## Errors".into()); + + for d in get_diagnostics() { + let span = if let Some(span) = d.span { + format!("{}:{}", span.start.line, span.start.col) + } else { + "".to_string() + }; + + snap.push(format!("{} {}", d.message, span)) + } + } + } + + return snap.join("\n"); +} diff --git a/libs/wingc/src/type_check.rs b/libs/wingc/src/type_check.rs index 0b3a60acba5..dc936d804f4 100644 --- a/libs/wingc/src/type_check.rs +++ b/libs/wingc/src/type_check.rs @@ -1,5 +1,6 @@ mod class_fields_init; pub(crate) mod jsii_importer; +pub mod lifts; pub mod symbol_env; use crate::ast::{self, ClassField, FunctionDefinition, TypeAnnotationKind}; @@ -32,6 +33,7 @@ use wingii::type_system::TypeSystem; use self::class_fields_init::VisitClassInit; use self::jsii_importer::JsiiImportSpec; +use self::lifts::Lifts; use self::symbol_env::{LookupResult, SymbolEnvIter, SymbolEnvRef}; pub struct UnsafeRef(*const T); @@ -201,7 +203,7 @@ pub enum Type { pub const CLASS_INIT_NAME: &'static str = "init"; pub const CLASS_INFLIGHT_INIT_NAME: &'static str = "$inflight_init"; -pub const HANDLE_METHOD_NAME: &'static str = "handle"; +pub const CLOSURE_CLASS_HANDLE_METHOD: &'static str = "handle"; #[derive(Derivative)] #[derivative(Debug)] @@ -239,6 +241,7 @@ pub struct Class { pub type_parameters: Option>, pub phase: Phase, pub docs: Docs, + pub lifts: Option, // Preflight classes are CDK Constructs which means they have a scope and id as their first arguments // this is natively supported by wing using the `as` `in` keywords. However theoretically it is possible @@ -246,6 +249,20 @@ pub struct Class { // and instead the user will need to pass the relevant args to the class's init method. pub std_construct_args: bool, } +impl Class { + pub(crate) fn set_lifts(&mut self, lifts: Lifts) { + self.lifts = Some(lifts); + } + + /// Returns the type of the "handle" method of a closure class or `None` if this is not a closure + /// class. + pub fn get_closure_method(&self) -> Option { + self + .methods(true) + .find(|(name, type_)| name == CLOSURE_CLASS_HANDLE_METHOD && type_.is_inflight_function()) + .map(|(_, t)| t) + } +} #[derive(Derivative)] #[derivative(Debug)] @@ -274,7 +291,7 @@ impl Interface { impl Display for Interface { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - if let LookupResult::Found(method, _) = self.get_env().lookup_ext(&HANDLE_METHOD_NAME.into(), None) { + if let LookupResult::Found(method, _) = self.get_env().lookup_ext(&CLOSURE_CLASS_HANDLE_METHOD.into(), None) { let method = method.as_variable().unwrap(); if method.phase == Phase::Inflight { write!(f, "{}", method.type_) // show signature of inflight closure @@ -437,7 +454,7 @@ impl Subtype for Type { } // Next, compare the function to a method on the interface named "handle" if it exists - if let Some((method, _)) = r0.get_env().lookup_ext(&HANDLE_METHOD_NAME.into(), None).ok() { + if let Some((method, _)) = r0.get_env().lookup_ext(&CLOSURE_CLASS_HANDLE_METHOD.into(), None).ok() { let method = method.as_variable().unwrap(); if method.phase != Phase::Inflight { return false; @@ -509,7 +526,7 @@ impl Subtype for Type { // To support flexible inflight closures, we say that any class with an inflight method // named "handle" is a subtype of any single-method interface with a matching "handle" - // method type. + // method type (aka "closure classes"). // First, check if there is exactly one inflight method in the interface let mut inflight_methods = iface @@ -522,12 +539,12 @@ impl Subtype for Type { // Next, check that the method's name is "handle" let (handler_method_name, handler_method_type) = handler_method.unwrap(); - if handler_method_name != HANDLE_METHOD_NAME { + if handler_method_name != CLOSURE_CLASS_HANDLE_METHOD { return false; } // Then get the type of the resource's "handle" method if it has one - let res_handle_type = if let Some(method) = class.get_method(&HANDLE_METHOD_NAME.into()) { + let res_handle_type = if let Some(method) = class.get_method(&CLOSURE_CLASS_HANDLE_METHOD.into()) { if method.type_.is_inflight_function() { method.type_ } else { @@ -546,7 +563,7 @@ impl Subtype for Type { // any matching inflight type. // Get the type of the resource's "handle" method if it has one - let res_handle_type = if let Some(method) = res.get_method(&HANDLE_METHOD_NAME.into()) { + let res_handle_type = if let Some(method) = res.get_method(&CLOSURE_CLASS_HANDLE_METHOD.into()) { if method.type_.is_inflight_function() { method.type_ } else { @@ -704,6 +721,16 @@ impl Display for SymbolKind { } } +impl Display for Class { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if let Some(closure) = self.get_closure_method() { + std::fmt::Display::fmt(&closure, f) + } else { + write!(f, "{}", self.name.name) + } + } +} + impl Display for Type { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { @@ -719,7 +746,8 @@ impl Display for Type { Type::Unresolved => write!(f, "unresolved"), Type::Optional(v) => write!(f, "{}?", v), Type::Function(sig) => write!(f, "{}", sig), - Type::Class(class) => write!(f, "{}", class.name.name), + Type::Class(class) => write!(f, "{}", class), + Type::Interface(iface) => write!(f, "{}", iface), Type::Struct(s) => write!(f, "{}", s.name.name), Type::Array(v) => write!(f, "Array<{}>", v), @@ -853,12 +881,14 @@ impl TypeRef { return false; } - /// Returns whether the type is a preflight class with an inflight method named "handle" - pub fn is_handler_preflight_class(&self) -> bool { + /// Returns whether type represents a closure (either a function or a closure class). + pub fn is_closure(&self) -> bool { + if self.as_function_sig().is_some() { + return true; + } + if let Some(ref class) = self.as_preflight_class() { - return class - .methods(true) - .any(|(name, type_)| name == HANDLE_METHOD_NAME && type_.is_inflight_function()); + return class.get_closure_method().is_some(); } false } @@ -1608,7 +1638,7 @@ impl<'a> TypeChecker<'a> { func_sig.clone() } else if let Some(class) = func_type.as_preflight_class() { // return the signature of the "handle" method - let lookup_res = class.get_method(&HANDLE_METHOD_NAME.into()); + let lookup_res = class.get_method(&CLOSURE_CLASS_HANDLE_METHOD.into()); let handle_type = if let Some(method) = lookup_res { method.type_ } else { @@ -2251,7 +2281,6 @@ impl<'a> TypeChecker<'a> { named_args: named_arg_types, } } - fn type_check_statement(&mut self, stmt: &Stmt, env: &mut SymbolEnv) { CompilationContext::set(CompilationPhase::TypeChecking, &stmt.span); @@ -2462,7 +2491,8 @@ impl<'a> TypeChecker<'a> { let (exp_type, _) = self.type_check_exp(value, env); let (var_type, var_phase) = self.type_check_exp(variable, env); - // check if the variable can be reassigned + // TODO: we need to verify that if this variable is defined in a parent environment (i.e. + // being captured) it cannot be reassigned: https://github.com/winglang/wing/issues/3069 if let ExprKind::Reference(r) = &variable.kind { let (var, _) = self.resolve_reference(&r, env); @@ -2612,6 +2642,7 @@ impl<'a> TypeChecker<'a> { type_parameters: None, // TODO no way to have generic args in wing yet docs: Docs::default(), std_construct_args: *phase == Phase::Preflight, + lifts: None, }; let mut class_type = self.types.add_type(Type::Class(class_spec)); match env.define(name, SymbolKind::Type(class_type), StatementIdx::Top) { @@ -3349,6 +3380,7 @@ impl<'a> TypeChecker<'a> { phase: original_type_class.phase, docs: original_type_class.docs.clone(), std_construct_args: original_type_class.std_construct_args, + lifts: None, }); // TODO: here we add a new type regardless whether we already "hydrated" `original_type` with these `type_params`. Cache! @@ -3959,10 +3991,11 @@ impl<'a> TypeChecker<'a> { } // Safety: we return from the function above so parent_udt cannot be None - let parent_udt = resolve_udt_from_expr(parent_expr).unwrap(); + let parent_udt = parent_expr.as_type_reference().unwrap(); if &parent_udt.root == name && parent_udt.fields.is_empty() { self.spanned_error(parent_udt, "Class cannot extend itself".to_string()); + self.types.assign_type_to_expr(parent_expr, self.types.error(), phase); return (None, None); } @@ -3972,11 +4005,12 @@ impl<'a> TypeChecker<'a> { } else { report_diagnostic(Diagnostic { message: format!( - "{} class {} cannot extend {} class \"{}\"", - phase, name, parent_class.phase, parent_class.name + "Class \"{}\" is an {} class and cannot extend {} class \"{}\"", + name, phase, parent_class.phase, parent_class.name ), span: Some(parent_expr.span.clone()), }); + self.types.assign_type_to_expr(parent_expr, self.types.error(), phase); (None, None) } } else { @@ -3984,6 +4018,7 @@ impl<'a> TypeChecker<'a> { message: format!("Expected \"{}\" to be a class", parent_udt), span: Some(parent_expr.span.clone()), }); + self.types.assign_type_to_expr(parent_expr, self.types.error(), phase); (None, None) } } @@ -4117,25 +4152,6 @@ where TypeError { message, span } } -/// Resolves a user defined type (e.g. `Foo.Bar.Baz`) to a type reference -pub fn resolve_udt_from_expr(expr: &Expr) -> Result<&UserDefinedType, TypeError> { - let ExprKind::Reference(ref r) = expr.kind else { - return Err(TypeError { - message: "Expected expression to be a reference".to_string(), - span: expr.span.clone(), - }); - }; - - let Reference::TypeReference(udt) = r else { - return Err(TypeError { - message: "Expected reference to be a reference to a type".to_string(), - span: expr.span.clone(), - }); - }; - - Ok(udt) -} - /// Resolves a user defined type (e.g. `Foo.Bar.Baz`) to a type reference pub fn resolve_user_defined_type( user_defined_type: &UserDefinedType, diff --git a/libs/wingc/src/type_check/jsii_importer.rs b/libs/wingc/src/type_check/jsii_importer.rs index 53cc4eda6a2..41debf2ad60 100644 --- a/libs/wingc/src/type_check/jsii_importer.rs +++ b/libs/wingc/src/type_check/jsii_importer.rs @@ -663,6 +663,7 @@ impl<'a> JsiiImporter<'a> { phase: class_phase, docs: Docs::from(&jsii_class.docs), std_construct_args: false, // Temporary value, will be updated once we parse the initializer args + lifts: None, }; let mut new_type = self.wing_types.add_type(Type::Class(class_spec)); self.register_jsii_type(&jsii_class_fqn, &new_type_symbol, new_type); diff --git a/libs/wingc/src/type_check/lifts.rs b/libs/wingc/src/type_check/lifts.rs new file mode 100644 index 00000000000..b028b56ad28 --- /dev/null +++ b/libs/wingc/src/type_check/lifts.rs @@ -0,0 +1,200 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use itertools::Itertools; + +use crate::ast::Symbol; + +/// A repository of lifts and captures at the class level. +#[derive(Debug)] +pub struct Lifts { + /// All the lifts. The key is "/" + lifts: BTreeMap, + + /// All the captures. The key is token. + captures: BTreeMap, + + /// Map from token to lift + lift_by_token: BTreeMap, + + /// A map of all lifted fields (`this.foo`). Key is token, value is the javascript code. + lifted_fields_by_token: BTreeMap, + + /// Map between expression id and a lift token. + token_by_expr_id: BTreeMap, +} + +/// A record that describes a capture. +#[derive(Debug, Clone)] +pub struct Capture { + /// Lifting token (the symbol used in inflight code) + pub token: String, + + /// The javascript code to capture + pub code: String, +} + +/// A record that describes a single lift from a method. +#[derive(Debug)] +pub struct MethodLift { + /// The method name + pub method: String, + + /// Lifting token (the symbol used in inflight code) + pub token: String, + + /// The javascript code to lift (preflight) + pub code: String, + + /// The operations that qualify the lift (the property names) + pub ops: BTreeSet, +} + +/// A record that describes a lift from a class. +#[derive(Debug)] +pub struct Lift { + /// Lifting token (the symbol used in inflight code) + pub token: String, + + /// The javascript code to lift (preflight) + pub code: String, + + /// Whether this is a field lift (`this.foo`) + pub is_field: bool, +} + +impl Lifts { + pub fn new() -> Self { + Self { + lifts: BTreeMap::new(), + lift_by_token: BTreeMap::new(), + captures: BTreeMap::new(), + lifted_fields_by_token: BTreeMap::new(), + token_by_expr_id: BTreeMap::new(), + } + } + + /// Returns the list of all lifts from this class. + pub fn lifts(&self) -> Vec<&Lift> { + self.lift_by_token.values().collect_vec() + } + + fn render_token(&self, code: &str) -> String { + if code == "this" { + return code.to_string(); + } + + format!("${}", replace_non_alphanumeric(code)) + } + + /// Adds a lift for an expression. + pub fn lift(&mut self, expr_id: usize, method: Option, property: Option, code: &str) { + let is_field = code.contains("this."); + + let token = self.render_token(code); + + self.token_by_expr_id.entry(expr_id).or_insert(token.clone()); + + self.lift_by_token.entry(token.clone()).or_insert(Lift { + token: token.clone(), + is_field, + code: code.to_string(), + }); + + let method = method.map(|m| m.name).unwrap_or(Default::default()); + + let key = format!("{}/{}", method.clone(), token); + let lift = self.lifts.entry(key).or_insert(MethodLift { + code: code.to_string(), + token: token.clone(), + method: method.clone(), + ops: BTreeSet::new(), + }); + + if let Some(op) = &property { + lift.ops.insert(op.clone()); + } + + if is_field { + self + .lifted_fields_by_token + .entry(token.to_string()) + .or_insert(code.to_string()); + } else { + self.capture(&expr_id, code); + } + } + + /// Returns the token for an expression. Called by the jsifier when emitting inflight code. + pub fn token_for_expr(&self, expr_id: &usize) -> Option { + let Some(token) = self.token_by_expr_id.get(expr_id) else { + return None; + }; + + let is_field = if let Some(lift) = self.lift_by_token.get(token) { + lift.is_field + } else { + false + }; + + if is_field { + return Some(format!("this.{}", token).to_string()); + } else { + return Some(token.clone()); + } + } + + /// Captures an expression. + pub fn capture(&mut self, expr_id: &usize, code: &str) { + // no need to capture this (it's already in scope) + if code == "this" { + return; + } + + let token = self.render_token(code); + + self.token_by_expr_id.entry(*expr_id).or_insert(token.clone()); + + self.captures.entry(token.clone()).or_insert(Capture { + token: token.to_string(), + code: code.to_string(), + }); + } + + /// The list of captures. + pub fn captures(&self) -> Vec<&Capture> { + self.captures.values().collect_vec() + } + + /// List of all lifted fields in the class. + pub fn lifted_fields(&self) -> BTreeMap { + self.lifted_fields_by_token.clone() + } + + /// List of all lifts per method. Key is the method name and the value is a list of lifts. + pub fn lifts_per_method(&self) -> BTreeMap> { + let mut result: BTreeMap> = BTreeMap::new(); + + for (_, method_lift) in &self.lifts { + if method_lift.method.is_empty() { + continue; + } + result.entry(method_lift.method.clone()).or_default().push(method_lift); + } + + result + } +} + +fn replace_non_alphanumeric(s: &str) -> String { + let mut result = String::new(); + + for c in s.chars() { + if c.is_alphanumeric() { + result.push(c); + } else { + result.push('_'); + } + } + + result +} diff --git a/libs/wingc/src/visit_context.rs b/libs/wingc/src/visit_context.rs new file mode 100644 index 00000000000..681d0f97e02 --- /dev/null +++ b/libs/wingc/src/visit_context.rs @@ -0,0 +1,119 @@ +use crate::{ + ast::{Phase, Symbol, UserDefinedType}, + type_check::symbol_env::SymbolEnvRef, +}; + +pub struct VisitContext { + phase: Vec, + env: Vec, + method_env: Vec>, + property: Vec, + method: Vec>, + class: Vec, + statement: Vec, +} + +impl VisitContext { + pub fn new() -> Self { + VisitContext { + phase: vec![], + env: vec![], + method_env: vec![], + property: vec![], + class: vec![], + statement: vec![], + method: vec![], + } + } +} + +impl VisitContext { + pub fn push_stmt(&mut self, stmt: usize) { + self.statement.push(stmt); + } + + pub fn pop_stmt(&mut self) { + self.statement.pop(); + } + + pub fn current_stmt_idx(&self) -> usize { + *self.statement.last().unwrap_or(&0) + } + + // -- + + pub fn push_class(&mut self, class: UserDefinedType, phase: &Phase, initializer_env: Option) { + self.class.push(class); + self.phase.push(*phase); + self.method_env.push(initializer_env); + } + + pub fn pop_class(&mut self) { + self.class.pop(); + self.phase.pop(); + self.method_env.pop(); + } + + pub fn current_class(&self) -> Option<&UserDefinedType> { + self.class.last() + } + + // -- + + pub fn push_function_definition(&mut self, function_name: &Option, phase: &Phase, env: SymbolEnvRef) { + self.phase.push(*phase); + self.method.push(function_name.clone()); + + // if the function definition doesn't have a name (i.e. it's a closure), don't push its env + // because it's not a method dude! + let maybe_env = function_name.as_ref().map(|_| env); + self.method_env.push(maybe_env); + } + + pub fn pop_function_definition(&mut self) { + self.phase.pop(); + self.method.pop(); + self.method_env.pop(); + } + + pub fn current_method(&self) -> Option { + // return the first none-None method in the stack (from the end) + self.method.iter().rev().find_map(|m| m.clone()) + } + + pub fn current_phase(&self) -> Phase { + *self.phase.last().unwrap_or(&Phase::Preflight) + } + + pub fn current_method_env(&self) -> Option<&SymbolEnvRef> { + self.method_env.iter().rev().find_map(|m| m.as_ref()) + } + + // -- + + pub fn push_property(&mut self, property: String) { + self.property.push(property); + } + + pub fn pop_property(&mut self) { + self.property.pop(); + } + + pub fn current_property(&self) -> Option { + self.property.last().cloned() + } + + // -- + + pub fn push_env(&mut self, env: SymbolEnvRef) { + self.env.push(env); + } + + pub fn pop_env(&mut self) { + self.env.pop(); + } + + pub fn current_env(&self) -> Option<&SymbolEnvRef> { + self.env.last() + } +} diff --git a/libs/wingsdk/src/core/internal.ts b/libs/wingsdk/src/core/internal.ts index e029b063967..3027d773467 100644 --- a/libs/wingsdk/src/core/internal.ts +++ b/libs/wingsdk/src/core/internal.ts @@ -3,7 +3,7 @@ import { App } from "./app"; import { Duration } from "../std/duration"; import { IResource } from "../std/resource"; -export function serializeImmutableData(scope: IConstruct, obj: any): string { +export function liftObject(scope: IConstruct, obj: any): string { // since typeof(null) is "object", we cover all nullity cases (undefined and null) apriori. if (obj == null) { return JSON.stringify(obj); @@ -14,6 +14,12 @@ export function serializeImmutableData(scope: IConstruct, obj: any): string { return tokens.lift(obj); } + // if the object is a type, and it has a "_toInflightType" method, we use it to serialize + // fyi, typeof(obj) in this case is a "function". + if (typeof obj?._toInflightType === "function") { + return obj._toInflightType(scope).text; + } + switch (typeof obj) { case "string": case "boolean": @@ -22,13 +28,11 @@ export function serializeImmutableData(scope: IConstruct, obj: any): string { case "object": if (Array.isArray(obj)) { - return `[${obj - .map((o) => serializeImmutableData(scope, o)) - .join(",")}]`; + return `[${obj.map((o) => liftObject(scope, o)).join(",")}]`; } if (obj instanceof Duration) { - return serializeImmutableData(scope, { + return liftObject(scope, { seconds: obj.seconds, minutes: obj.minutes, hours: obj.hours, @@ -36,11 +40,11 @@ export function serializeImmutableData(scope: IConstruct, obj: any): string { } if (obj instanceof Set) { - return `new Set(${serializeImmutableData(scope, Array.from(obj))})`; + return `new Set(${liftObject(scope, Array.from(obj))})`; } if (obj instanceof Map) { - return `new Map(${serializeImmutableData(scope, Array.from(obj))})`; + return `new Map(${liftObject(scope, Array.from(obj))})`; } // if the object is a resource (i.e. has a "_toInflight" method"), we use it to serialize @@ -54,14 +58,14 @@ export function serializeImmutableData(scope: IConstruct, obj: any): string { const lines = []; lines.push("{"); for (const [k, v] of Object.entries(obj)) { - lines.push(`${k}: ${serializeImmutableData(scope, v)},`); + lines.push(`${k}: ${liftObject(scope, v)},`); } lines.push("}"); return lines.join(""); } + + break; } - throw new Error( - `unable to serialize immutable data object of type ${obj.constructor?.name}` - ); + throw new Error(`Unable to lift object of type ${obj?.constructor?.name}`); } diff --git a/libs/wingsdk/src/shared/bundling.ts b/libs/wingsdk/src/shared/bundling.ts index 64be8dde1f1..54d6d0d8607 100644 --- a/libs/wingsdk/src/shared/bundling.ts +++ b/libs/wingsdk/src/shared/bundling.ts @@ -36,7 +36,8 @@ export function createBundle(entrypoint: string, outputDir?: string): Bundle { }); if (esbuild.errors.length > 0) { - throw new Error(`Failed to bundle function: ${esbuild.errors.join("\n")}`); + const errors = esbuild.errors.map((e) => e.text).join("\n"); + throw new Error(`Failed to bundle function: ${errors}`); } // the bundled contains line comments with file paths, which are not useful for us, especially diff --git a/libs/wingsdk/src/std/resource.ts b/libs/wingsdk/src/std/resource.ts index b91a58ce489..600874cde44 100644 --- a/libs/wingsdk/src/std/resource.ts +++ b/libs/wingsdk/src/std/resource.ts @@ -3,7 +3,7 @@ import { Duration } from "./duration"; import { App } from "../core"; import { WING_ATTRIBUTE_RESOURCE_CONNECTIONS } from "../core/attributes"; import { Code } from "../core/inflight"; -import { serializeImmutableData } from "../core/internal"; +import { liftObject } from "../core/internal"; import { IInspectable, TreeInspector } from "../core/tree"; import { log } from "../shared/log"; @@ -189,7 +189,6 @@ export abstract class Resource extends Construct implements IResource { if (isResource(obj)) { // Explicitly register the resource's `$inflight_init` op, which is a special op that can be used to makes sure // the host can instantiate a client for this resource. - obj._registerBind(host, ["$inflight_init"]); obj._registerBind(host, ops); @@ -354,7 +353,7 @@ export abstract class Resource extends Construct implements IResource { * @internal */ protected _lift(value: any): string { - return serializeImmutableData(this, value); + return liftObject(this, value); } } diff --git a/libs/wingsdk/src/testing/simulator.ts b/libs/wingsdk/src/testing/simulator.ts index 9cc2527edd6..2302c17d5d1 100644 --- a/libs/wingsdk/src/testing/simulator.ts +++ b/libs/wingsdk/src/testing/simulator.ts @@ -9,6 +9,8 @@ import { readJsonSync } from "../shared/misc"; import { DefaultSimulatorFactory } from "../target-sim/factory.inflight"; import { isToken } from "../target-sim/tokens"; +const START_ATTEMPT_COUNT = 10; + /** * Props for `Simulator`. */ @@ -183,70 +185,34 @@ export class Simulator { ); } - this._traces = []; - - for (const resourceConfig of this._config.resources) { - const context: ISimulatorContext = { - simdir: this.simdir, - resourcePath: resourceConfig.path, - findInstance: (handle: string) => { - return this._handles.find(handle); - }, - addTrace: (trace: Trace) => { - this._addTrace(trace); - }, - withTrace: async (props: IWithTraceProps) => { - // TODO: log start time and end time of activity? - try { - let result = await props.activity(); - this._addTrace({ - data: { - message: props.message, - status: "success", - result: JSON.stringify(result), - }, - type: TraceType.RESOURCE, - sourcePath: resourceConfig.path, - sourceType: resourceConfig.type, - timestamp: new Date().toISOString(), - }); - return result; - } catch (err) { - this._addTrace({ - data: { message: props.message, status: "failure", error: err }, - type: TraceType.RESOURCE, - sourcePath: resourceConfig.path, - sourceType: resourceConfig.type, - timestamp: new Date().toISOString(), - }); - throw err; - } - }, - listTraces: () => { - return [...this._traces]; - }, - }; + // create a copy of the resource list to be used as an init queue. + const initQueue: (BaseResourceSchema & { _attempts?: number })[] = [ + ...this._config.resources, + ]; - const resolvedProps = this.resolveTokens( - resourceConfig.props, - resourceConfig.path - ); - const resource = this._factory.resolve( - resourceConfig.type, - resolvedProps, - context - ); - const resourceAttrs = await resource.init(); - const handle = this._handles.allocate(resource); - (resourceConfig as any).attrs = { ...resourceAttrs, handle }; - let event: Trace = { - type: TraceType.RESOURCE, - data: { message: `${resourceConfig.type} created.` }, - sourcePath: resourceConfig.path, - sourceType: resourceConfig.type, - timestamp: new Date().toISOString(), - }; - this._addTrace(event); + while (true) { + const next = initQueue.shift(); + if (!next) { + break; + } + + // we couldn't start this resource yet, so decrement the retry counter and put it back in + // the init queue. + if (!(await this.tryStartResource(next))) { + // we couldn't start this resource yet, so decrement the attempt counter + next._attempts = next._attempts ?? START_ATTEMPT_COUNT; + next._attempts--; + + // if we've tried too many times, give up (might be a dependency cycle or a bad reference) + if (next._attempts === 0) { + throw new Error( + `Could not start resource ${next.path} after ${START_ATTEMPT_COUNT} attempts. This could be due to a dependency cycle or an invalid attribute reference.` + ); + } + + // put back in the queue for another round + initQueue.push(next); + } } this._running = true; @@ -284,8 +250,6 @@ export class Simulator { this._handles.reset(); this._running = false; - - // TODO: remove "attrs" data from tree } /** @@ -337,6 +301,7 @@ export class Simulator { if (!handle) { return undefined; } + return this._handles.find(handle); } @@ -380,6 +345,100 @@ export class Simulator { return this._tree; } + private async tryStartResource( + resourceConfig: BaseResourceSchema + ): Promise { + const context = this.createContext(resourceConfig); + + const resolvedProps = this.tryResolveTokens( + resourceConfig.props, + resourceConfig.path + ); + if (resolvedProps === undefined) { + this._addTrace({ + type: TraceType.RESOURCE, + data: { message: `${resourceConfig.path} is waiting on a dependency` }, + sourcePath: resourceConfig.path, + sourceType: resourceConfig.type, + timestamp: new Date().toISOString(), + }); + + // this means the resource has a dependency that hasn't been started yet (hopefully). return + // it to the init queue. + return false; + } + + // create the resource based on its type + const resourceObject = this._factory.resolve( + resourceConfig.type, + resolvedProps, + context + ); + + // go ahead and initialize the resource + const attrs = await resourceObject.init(); + + // allocate a handle for the resource so others can find it + const handle = this._handles.allocate(resourceObject); + + // update the resource configuration with new attrs returned after initialization + (resourceConfig as any).attrs = { ...attrs, handle }; + + // trace the resource creation + this._addTrace({ + type: TraceType.RESOURCE, + data: { message: `${resourceConfig.type} created.` }, + sourcePath: resourceConfig.path, + sourceType: resourceConfig.type, + timestamp: new Date().toISOString(), + }); + + return true; + } + + private createContext(resourceConfig: BaseResourceSchema): ISimulatorContext { + return { + simdir: this.simdir, + resourcePath: resourceConfig.path, + findInstance: (handle: string) => { + return this._handles.find(handle); + }, + addTrace: (trace: Trace) => { + this._addTrace(trace); + }, + withTrace: async (props: IWithTraceProps) => { + // TODO: log start time and end time of activity? + try { + let result = await props.activity(); + this._addTrace({ + data: { + message: props.message, + status: "success", + result: JSON.stringify(result), + }, + type: TraceType.RESOURCE, + sourcePath: resourceConfig.path, + sourceType: resourceConfig.type, + timestamp: new Date().toISOString(), + }); + return result; + } catch (err) { + this._addTrace({ + data: { message: props.message, status: "failure", error: err }, + type: TraceType.RESOURCE, + sourcePath: resourceConfig.path, + sourceType: resourceConfig.type, + timestamp: new Date().toISOString(), + }); + throw err; + } + }, + listTraces: () => { + return [...this._traces]; + }, + }; + } + private _addTrace(event: Trace) { event = Object.freeze(event); for (const sub of this._traceSubscribers) { @@ -389,21 +448,21 @@ export class Simulator { } /** - * Return an object with all tokens in it resolved to their appropriate - * values. + * Return an object with all tokens in it resolved to their appropriate values. * - * A token can be a string like "${app/my_bucket#attrs.handle}". This token - * would be resolved to the "handle" attribute of the resource at path - * "app/my_bucket". If that attribute does not exist at the time of resolution - * (for example, if my_bucket is not being simulated yet), an error will be - * thrown. + * A token can be a string like "${app/my_bucket#attrs.handle}". This token would be resolved to + * the "handle" attribute of the resource at path "app/my_bucket". If that attribute does not + * exist at the time of resolution (for example, if my_bucket is not being simulated yet), an + * error will be thrown. * * Tokens can also be nested, like "${app/my_bucket#attrs.handle}/foo/bar". * * @param obj The object to resolve tokens in. * @param source The path of the resource that requested the token to be resolved. + * @returns `undefined` if the token could not be resolved (e.g. needs a dependency), otherwise + * the resolved value. */ - private resolveTokens(obj: any, source: string): any { + private tryResolveTokens(obj: any, source: string): any { if (typeof obj === "string") { if (isToken(obj)) { const ref = obj.slice(2, -1); @@ -412,10 +471,12 @@ export class Simulator { if (rest.startsWith("attrs.")) { const attrName = rest.slice(6); const attr = config?.attrs[attrName]; + + // we couldn't find the attribute. this doesn't mean it doesn't exist, it's just likely + // that this resource haven't been started yet. so return `undefined`, which will cause + // this resource to go back to the init queue. if (!attr) { - throw new Error( - `Tried to resolve token "${obj}" but resource ${path} has no attribute ${attrName} defined yet. Is it possible ${source} needs to take a dependency on ${path}?` - ); + return undefined; } return attr; } else if (rest.startsWith("props.")) { @@ -429,17 +490,31 @@ export class Simulator { throw new Error(`Invalid token reference: "${ref}"`); } } + return obj; } if (Array.isArray(obj)) { - return obj.map((x) => this.resolveTokens(x, source)); + const result = []; + for (const x of obj) { + const value = this.tryResolveTokens(x, source); + if (value === undefined) { + return undefined; + } + result.push(value); + } + + return result; } if (typeof obj === "object") { const ret: any = {}; for (const [key, value] of Object.entries(obj)) { - ret[key] = this.resolveTokens(value, source); + const resolved = this.tryResolveTokens(value, source); + if (resolved === undefined) { + return undefined; + } + ret[key] = resolved; } return ret; } diff --git a/libs/wingsdk/src/testing/testing.ts b/libs/wingsdk/src/testing/testing.ts index f32944eeb9b..00b202c5c9e 100644 --- a/libs/wingsdk/src/testing/testing.ts +++ b/libs/wingsdk/src/testing/testing.ts @@ -1,6 +1,6 @@ import { IConstruct } from "constructs"; import { InflightBindings, NodeJsCode } from "../core"; -import { serializeImmutableData } from "../core/internal"; +import { liftObject } from "../core/internal"; import { IInflightHost, IResource, Resource } from "../std"; /** @@ -30,7 +30,7 @@ export class Testing { const clients: Record = {}; for (const [k, v] of Object.entries(bindings)) { - clients[k] = serializeImmutableData(scope, v.obj); + clients[k] = liftObject(scope, v.obj); } // implements IFunctionHandler diff --git a/libs/wingsdk/test/target-tf-aws/__snapshots__/tokens.test.ts.snap b/libs/wingsdk/test/target-tf-aws/__snapshots__/tokens.test.ts.snap index a4f932030a8..ad501d5b439 100644 --- a/libs/wingsdk/test/target-tf-aws/__snapshots__/tokens.test.ts.snap +++ b/libs/wingsdk/test/target-tf-aws/__snapshots__/tokens.test.ts.snap @@ -39,7 +39,7 @@ exports[`captures tokens 2`] = ` }, \\"rest_api_id\\": \\"\${aws_api_gateway_rest_api.Api_api_91C07D84.id}\\", \\"triggers\\": { - \\"redeployment\\": \\"5c0f11f0478884e3d7859fa987b8b7ecf8f2f6bc\\" + \\"redeployment\\": \\"78e5e40c11e87555822daa92a92cba68abd2ec5b\\" } } }, diff --git a/tools/hangar/__snapshots__/error.ts.snap b/tools/hangar/__snapshots__/error.ts.snap index 2b28356c2db..f346106e45d 100644 --- a/tools/hangar/__snapshots__/error.ts.snap +++ b/tools/hangar/__snapshots__/error.ts.snap @@ -83,8 +83,8 @@ hint: Every preflight object needs a unique identifier within its scope. You can For more information, see https://www.winglang.io/docs/language-guide/language-reference#33-preflight-classes -../../../examples/tests/error/target/test/repeat_construct_id2.wsim.[REDACTED].tmp/.wing/preflight.js:14 - ; +../../../examples/tests/error/target/test/repeat_construct_id2.wsim.[REDACTED].tmp/.wing/preflight.js:13 + }); const bucket1 = this.node.root.newAbstract(\\"@winglang/sdk.cloud.Bucket\\",this,String.raw({ raw: [\\"\\", \\"\\"] }, (make_name()))); >> const bucket2 = this.node.root.newAbstract(\\"@winglang/sdk.cloud.Bucket\\",this,String.raw({ raw: [\\"\\", \\"\\"] }, (make_name()))); } diff --git a/tools/hangar/__snapshots__/invalid.ts.snap b/tools/hangar/__snapshots__/invalid.ts.snap index 5456ca74def..9061a966c4a 100644 --- a/tools/hangar/__snapshots__/invalid.ts.snap +++ b/tools/hangar/__snapshots__/invalid.ts.snap @@ -154,10 +154,10 @@ Duration " exports[`capture_redefinition.w 1`] = ` "error: Cannot capture symbol \\"y\\" because it is shadowed by another symbol with the same name - --> ../../../examples/tests/invalid/capture_redefinition.w:4:7 - | -4 | log(y); - | ^ Cannot capture symbol \\"y\\" because it is shadowed by another symbol with the same name + --> ../../../examples/tests/invalid/capture_redefinition.w:14:9 + | +14 | log(y); + | ^ Cannot capture symbol \\"y\\" because it is shadowed by another symbol with the same name @@ -382,7 +382,15 @@ exports[`cloud_function_expects_inflight.w 1`] = ` | \\\\-^ Expected type to be \\"inflight (event: str): void\\", but got \\"preflight (name: str): str\\" instead -error: Expected type to be \\"inflight (message: str): void\\", but got \\"$Closure1\\" instead +error: Expected type to be \\"inflight (message: str): void\\", but got \\"inflight (x: num): void\\" instead + --> ../../../examples/tests/invalid/cloud_function_expects_inflight.w:9:15 + | + 9 | q.setConsumer(inflight (x: num) => { + | /---------------^ +10 | | // ^ \\"num\\" doesn't match the expected type \\"str\\" +11 | | return; +12 | | }); + | \\\\-^ Expected type to be \\"inflight (message: str): void\\", but got \\"inflight (x: num): void\\" instead @@ -723,6 +731,13 @@ error: Cannot create preflight class \\"PreflightClass\\" in inflight phase | ^^^^^^^^^^^^^^^^^^^^ Cannot create preflight class \\"PreflightClass\\" in inflight phase +error: Cannot qualify access to a lifted object of type \\"PreflightClass\\" (see https://github.com/winglang/wing/issues/76 for more details) + --> ../../../examples/tests/invalid/inflight_class_created_in_preflight.w:19:3 + | +19 | new PreflightClass(); + | ^^^^^^^^^^^^^^^^^^^^ Cannot qualify access to a lifted object of type \\"PreflightClass\\" (see https://github.com/winglang/wing/issues/76 for more details) + + Tests 1 failed (1) @@ -800,25 +815,25 @@ Duration " `; exports[`inflight_ref_explicit_ops.w 1`] = ` -"error: Unable to qualify which operations are performed on 'this.myQueue' of type 'Queue'. This is not supported yet. +"error: Cannot qualify access to a lifted object of type \\"Queue\\" (see https://github.com/winglang/wing/issues/76 for more details) --> ../../../examples/tests/invalid/inflight_ref_explicit_ops.w:13:12 | 13 | return this.myQueue; - | ^^^^^^^^^^^^ Unable to qualify which operations are performed on 'this.myQueue' of type 'Queue'. This is not supported yet. + | ^^^^^^^^^^^^ Cannot qualify access to a lifted object of type \\"Queue\\" (see https://github.com/winglang/wing/issues/76 for more details) -error: Unable to qualify which operations are performed on 'this.b' of type 'Bucket'. This is not supported yet. +error: Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) --> ../../../examples/tests/invalid/inflight_ref_explicit_ops.w:34:13 | 34 | let x = this.b; - | ^^^^^^ Unable to qualify which operations are performed on 'this.b' of type 'Bucket'. This is not supported yet. + | ^^^^^^ Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) -error: Capturing collection of preflight classes is not supported yet (type is 'Array') - --> ../../../examples/tests/invalid/inflight_ref_explicit_ops.w:47:18 +error: Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) + --> ../../../examples/tests/invalid/inflight_ref_explicit_ops.w:47:13 | 47 | let b = this.array.at(1); - | ^^^^^ Capturing collection of preflight classes is not supported yet (type is 'Array') + | ^^^^^^^^^^^^^^^^ Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) @@ -829,18 +844,18 @@ Duration " `; exports[`inflight_ref_resource_sub_method.w 1`] = ` -"error: Unable to qualify which operations are performed on 'this.myQueue' of type 'Queue'. This is not supported yet. +"error: Cannot qualify access to a lifted object of type \\"Queue\\" (see https://github.com/winglang/wing/issues/76 for more details) --> ../../../examples/tests/invalid/inflight_ref_resource_sub_method.w:13:12 | 13 | return this.myQueue; - | ^^^^^^^^^^^^ Unable to qualify which operations are performed on 'this.myQueue' of type 'Queue'. This is not supported yet. + | ^^^^^^^^^^^^ Cannot qualify access to a lifted object of type \\"Queue\\" (see https://github.com/winglang/wing/issues/76 for more details) -error: Unable to qualify which operations are performed on 'globalQueue' of type 'Queue'. This is not supported yet. +error: Cannot qualify access to a lifted object of type \\"Queue\\" (see https://github.com/winglang/wing/issues/76 for more details) --> ../../../examples/tests/invalid/inflight_ref_resource_sub_method.w:18:12 | 18 | return globalQueue; - | ^^^^^^^^^^^ Unable to qualify which operations are performed on 'globalQueue' of type 'Queue'. This is not supported yet. + | ^^^^^^^^^^^ Cannot qualify access to a lifted object of type \\"Queue\\" (see https://github.com/winglang/wing/issues/76 for more details) @@ -851,18 +866,18 @@ Duration " `; exports[`inflight_ref_unknown_op.w 1`] = ` -"error: Unable to qualify which operations are performed on 'this.b' of type 'Bucket'. This is not supported yet. +"error: Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) --> ../../../examples/tests/invalid/inflight_ref_unknown_op.w:13:13 | 13 | let x = this.b; - | ^^^^^^ Unable to qualify which operations are performed on 'this.b' of type 'Bucket'. This is not supported yet. + | ^^^^^^ Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) -error: Unable to qualify which operations are performed on 'globalB' of type 'Bucket'. This is not supported yet. +error: Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) --> ../../../examples/tests/invalid/inflight_ref_unknown_op.w:17:13 | 17 | let y = globalB; - | ^^^^^^^ Unable to qualify which operations are performed on 'globalB' of type 'Bucket'. This is not supported yet. + | ^^^^^^^ Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) @@ -1448,18 +1463,11 @@ Duration " `; exports[`resource_captures.w 1`] = ` -"error: Unable to qualify which operations are performed on 'this.bucket' of type 'Bucket'. This is not supported yet. - --> ../../../examples/tests/invalid/resource_captures.w:23:13 - | -23 | let b = this.bucket; - | ^^^^^^^^^^^ Unable to qualify which operations are performed on 'this.bucket' of type 'Bucket'. This is not supported yet. - - -error: Capturing collection of preflight classes is not supported yet (type is 'Array') - --> ../../../examples/tests/invalid/resource_captures.w:27:10 +"error: Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) + --> ../../../examples/tests/invalid/resource_captures.w:13:13 | -27 | this.collectionOfResources.at(0).put(\\"hello\\", \\"world\\"); - | ^^^^^^^^^^^^^^^^^^^^^ Capturing collection of preflight classes is not supported yet (type is 'Array') +13 | let b = this.bucket; + | ^^^^^^^^^^^ Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) @@ -1477,6 +1485,13 @@ exports[`resource_inflight.w 1`] = ` | ^^^^^^^^^^^^^^^^^^ Cannot create preflight class \\"Bucket\\" in inflight phase +error: Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) + --> ../../../examples/tests/invalid/resource_inflight.w:4:3 + | +4 | new cloud.Bucket(); // Should fail because we can't create resources inflight + | ^^^^^^^^^^^^^^^^^^ Cannot qualify access to a lifted object of type \\"Bucket\\" (see https://github.com/winglang/wing/issues/76 for more details) + + Tests 1 failed (1) @@ -1592,6 +1607,13 @@ error: Inflight classes cannot have a scope | ^^ Inflight classes cannot have a scope +error: Cannot qualify access to a lifted object of type \\"PreflightClass\\" (see https://github.com/winglang/wing/issues/76 for more details) + --> ../../../examples/tests/invalid/scope_and_id.w:17:26 + | +17 | new InflightClass() in pc; + | ^^ Cannot qualify access to a lifted object of type \\"PreflightClass\\" (see https://github.com/winglang/wing/issues/76 for more details) + + Tests 1 failed (1) @@ -2031,7 +2053,7 @@ exports[`use_before_defined.w 1`] = ` error: Symbol \\"x\\" used before being defined --> ../../../examples/tests/invalid/use_before_defined.w:5:10 | -5 | log(\\"\${x}\\"); // Access x before it's defined (even though it's defined in an outer scope) +5 | log(\\"\${x}\\"); | ^ Symbol \\"x\\" used before being defined diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/delete.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/delete.w_compile_tf-aws.md index 93e6c1c8617..090c306687c 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/delete.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/delete.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ api_DELETE }) { +module.exports = function({ $api_DELETE }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { - {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_DELETE")})((req.method === api_DELETE))}; + async handle(req) { + {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_DELETE")})((req.method === $api_DELETE))}; {((cond) => {if (!cond) throw new Error("assertion failed: req.query?.get(\"all\") == \"true\"")})(((req.query)["all"] === "true"))}; {((cond) => {if (!cond) throw new Error("assertion failed: req.query?.get(\"page\") == \"6\"")})(((req.query)["page"] === "6"))}; {((cond) => {if (!cond) throw new Error("assertion failed: req.path == \"/path\"")})((req.path === "/path"))}; @@ -29,19 +27,17 @@ module.exports = function({ api_DELETE }) { ## inflight.$Closure2.js ```js -module.exports = function({ api, http_DELETE, http_Util }) { +module.exports = function({ $api_url, $http_DELETE, $http_Util }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const url = String.raw({ raw: ["", "/path?all=true&page=6"] }, api.url); - const response = (await http_Util.delete(url)); - const fetchResponse = (await http_Util.fetch(url,Object.freeze({"method":http_DELETE}))); + async handle() { + const url = String.raw({ raw: ["", "/path?all=true&page=6"] }, $api_url); + const response = (await $http_Util.delete(url)); + const fetchResponse = (await $http_Util.fetch(url,Object.freeze({"method":$http_DELETE}))); {((cond) => {if (!cond) throw new Error("assertion failed: response.body == \"6\"")})((response.body === "6"))}; {((cond) => {if (!cond) throw new Error("assertion failed: response.status == 200")})((response.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: response.url == url")})((response.url === url))}; @@ -239,7 +235,6 @@ module.exports = function({ api, http_DELETE, http_Util }) { }, "environment": { "variables": { - "CLOUD_API_C82DF3A5": "${aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url}", "WING_FUNCTION_NAME": "Handler-c897cd38", "WING_TARGET": "tf-aws", "WING_TOKEN_TFTOKEN_TOKEN_21": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" @@ -329,14 +324,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const api_DELETE_client = context._lift(api_DELETE); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api_DELETE: ${api_DELETE_client}, + require("./inflight.$Closure1.js")({ + $api_DELETE: ${context._lift(api_DELETE)}, }) `); } @@ -352,9 +345,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(api_DELETE, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(api_DELETE, host, []); } @@ -365,18 +355,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const api_client = context._lift(api); - const http_DELETE_client = context._lift(http_DELETE); - const http_UtilClient = http.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api: ${api_client}, - http_DELETE: ${http_DELETE_client}, - http_Util: ${http_UtilClient.text}, + require("./inflight.$Closure2.js")({ + $api_url: ${context._lift(api.url)}, + $http_DELETE: ${context._lift(http_DELETE)}, + $http_Util: ${context._lift(http.Util)}, }) `); } @@ -392,10 +378,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(api, host, []); - $Closure2._registerBindObject(http_DELETE, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(api.url, host, []); $Closure2._registerBindObject(http_DELETE, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/get.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/get.w_compile_tf-aws.md index d6ad3048e84..77faf95ea6d 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/get.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/get.w_compile_tf-aws.md @@ -2,22 +2,20 @@ ## inflight.$Closure1.js ```js -module.exports = function({ api_GET, body }) { +module.exports = function({ $api_GET, $body }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { - {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_GET")})((req.method === api_GET))}; + async handle(req) { + {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_GET")})((req.method === $api_GET))}; {((cond) => {if (!cond) throw new Error("assertion failed: req.path == \"/path\"")})((req.path === "/path"))}; {((cond) => {if (!cond) throw new Error("assertion failed: req.headers?.get(\"content-type\") == \"application/json\"")})(((req.headers)["content-type"] === "application/json"))}; return { "status": 200, - "body": body,} + "body": $body,} ; } } @@ -28,32 +26,30 @@ module.exports = function({ api_GET, body }) { ## inflight.$Closure2.js ```js -module.exports = function({ api, http_GET, body, http_Util }) { +module.exports = function({ $api_url, $body, $http_GET, $http_Util }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const url = (api.url + "/path"); - const getResponse = (await http_Util.get(url,{ headers: Object.freeze({"content-type":"application/json"}) })); - const fetchResponse = (await http_Util.fetch(url,{ - "method": http_GET, + async handle() { + const url = ($api_url + "/path"); + const getResponse = (await $http_Util.get(url,{ headers: Object.freeze({"content-type":"application/json"}) })); + const fetchResponse = (await $http_Util.fetch(url,{ + "method": $http_GET, "headers": Object.freeze({"content-type":"application/json"}),} )); - const fetchResponseNoMethod = (await http_Util.fetch(url,{ + const fetchResponseNoMethod = (await $http_Util.fetch(url,{ "headers": Object.freeze({"content-type":"application/json"}),} )); - {((cond) => {if (!cond) throw new Error("assertion failed: getResponse.body == body")})((getResponse.body === body))}; + {((cond) => {if (!cond) throw new Error("assertion failed: getResponse.body == body")})((getResponse.body === $body))}; {((cond) => {if (!cond) throw new Error("assertion failed: getResponse.status == 200")})((getResponse.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: getResponse.url == url")})((getResponse.url === url))}; - {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.body == body")})((fetchResponse.body === body))}; + {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.body == body")})((fetchResponse.body === $body))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.status == 200")})((fetchResponse.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.url == url")})((fetchResponse.url === url))}; - {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponseNoMethod.body == body")})((fetchResponseNoMethod.body === body))}; + {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponseNoMethod.body == body")})((fetchResponseNoMethod.body === $body))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponseNoMethod.status == 200")})((fetchResponseNoMethod.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponseNoMethod.url == url")})((fetchResponseNoMethod.url === url))}; } @@ -247,7 +243,6 @@ module.exports = function({ api, http_GET, body, http_Util }) { }, "environment": { "variables": { - "CLOUD_API_C82DF3A5": "${aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url}", "WING_FUNCTION_NAME": "Handler-c838ce37", "WING_TARGET": "tf-aws", "WING_TOKEN_TFTOKEN_TOKEN_21": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" @@ -337,16 +332,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const api_GET_client = context._lift(api_GET); - const body_client = context._lift(body); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api_GET: ${api_GET_client}, - body: ${body_client}, + require("./inflight.$Closure1.js")({ + $api_GET: ${context._lift(api_GET)}, + $body: ${context._lift(body)}, }) `); } @@ -362,10 +354,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(api_GET, host, []); - $Closure1._registerBindObject(body, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(api_GET, host, []); $Closure1._registerBindObject(body, host, []); @@ -377,20 +365,15 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const api_client = context._lift(api); - const http_GET_client = context._lift(http_GET); - const body_client = context._lift(body); - const http_UtilClient = http.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api: ${api_client}, - http_GET: ${http_GET_client}, - body: ${body_client}, - http_Util: ${http_UtilClient.text}, + require("./inflight.$Closure2.js")({ + $api_url: ${context._lift(api.url)}, + $body: ${context._lift(body)}, + $http_GET: ${context._lift(http_GET)}, + $http_Util: ${context._lift(http.Util)}, }) `); } @@ -406,11 +389,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(api, host, []); - $Closure2._registerBindObject(body, host, []); - $Closure2._registerBindObject(http_GET, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(api.url, host, []); $Closure2._registerBindObject(body, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/options.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/options.w_compile_tf-aws.md index ddf80df52af..8a24b3827ca 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/options.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/options.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ api_OPTIONS, path }) { +module.exports = function({ $api_OPTIONS, $path }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { - {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_OPTIONS")})((req.method === api_OPTIONS))}; - {((cond) => {if (!cond) throw new Error("assertion failed: req.path == path")})((req.path === path))}; + async handle(req) { + {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_OPTIONS")})((req.method === $api_OPTIONS))}; + {((cond) => {if (!cond) throw new Error("assertion failed: req.path == path")})((req.path === $path))}; return { "status": 204,} ; @@ -26,18 +24,16 @@ module.exports = function({ api_OPTIONS, path }) { ## inflight.$Closure2.js ```js -module.exports = function({ api_HEAD, path }) { +module.exports = function({ $api_HEAD, $path }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { - {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_HEAD")})((req.method === api_HEAD))}; - {((cond) => {if (!cond) throw new Error("assertion failed: req.path == path")})((req.path === path))}; + async handle(req) { + {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_HEAD")})((req.method === $api_HEAD))}; + {((cond) => {if (!cond) throw new Error("assertion failed: req.path == path")})((req.path === $path))}; return { "status": 204,} ; @@ -57,9 +53,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { + async handle(req) { return { "status": 204,} ; @@ -72,22 +66,20 @@ module.exports = function({ }) { ## inflight.$Closure4.js ```js -module.exports = function({ api, path, http_OPTIONS, http_HEAD, http_Util }) { +module.exports = function({ $api_url, $http_HEAD, $http_OPTIONS, $http_Util, $path }) { class $Closure4 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const url = (api.url + path); - const options = (await http_Util.fetch(url,{ - "method": http_OPTIONS,} + async handle() { + const url = ($api_url + $path); + const options = (await $http_Util.fetch(url,{ + "method": $http_OPTIONS,} )); - const head = (await http_Util.fetch(url,{ - "method": http_HEAD,} + const head = (await $http_Util.fetch(url,{ + "method": $http_HEAD,} )); {((cond) => {if (!cond) throw new Error("assertion failed: options.status == 204")})((options.status === 204))}; {((cond) => {if (!cond) throw new Error("assertion failed: options.url == url")})((options.url === url))}; @@ -394,7 +386,6 @@ module.exports = function({ api, path, http_OPTIONS, http_HEAD, http_Util }) { }, "environment": { "variables": { - "CLOUD_API_C82DF3A5": "${aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url}", "WING_FUNCTION_NAME": "Handler-c8f5c667", "WING_TARGET": "tf-aws", "WING_TOKEN_TFTOKEN_TOKEN_49": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" @@ -532,16 +523,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const api_OPTIONS_client = context._lift(api_OPTIONS); - const path_client = context._lift(path); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api_OPTIONS: ${api_OPTIONS_client}, - path: ${path_client}, + require("./inflight.$Closure1.js")({ + $api_OPTIONS: ${context._lift(api_OPTIONS)}, + $path: ${context._lift(path)}, }) `); } @@ -557,10 +545,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(api_OPTIONS, host, []); - $Closure1._registerBindObject(path, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(api_OPTIONS, host, []); $Closure1._registerBindObject(path, host, []); @@ -572,16 +556,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const api_HEAD_client = context._lift(api_HEAD); - const path_client = context._lift(path); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api_HEAD: ${api_HEAD_client}, - path: ${path_client}, + require("./inflight.$Closure2.js")({ + $api_HEAD: ${context._lift(api_HEAD)}, + $path: ${context._lift(path)}, }) `); } @@ -597,10 +578,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(api_HEAD, host, []); - $Closure2._registerBindObject(path, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(api_HEAD, host, []); $Closure2._registerBindObject(path, host, []); @@ -612,12 +589,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure3.js")({ }) `); } @@ -632,34 +608,21 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure4 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; - const api_client = context._lift(api); - const path_client = context._lift(path); - const http_OPTIONS_client = context._lift(http_OPTIONS); - const http_HEAD_client = context._lift(http_HEAD); - const http_UtilClient = http.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api: ${api_client}, - path: ${path_client}, - http_OPTIONS: ${http_OPTIONS_client}, - http_HEAD: ${http_HEAD_client}, - http_Util: ${http_UtilClient.text}, + require("./inflight.$Closure4.js")({ + $api_url: ${context._lift(api.url)}, + $http_HEAD: ${context._lift(http_HEAD)}, + $http_OPTIONS: ${context._lift(http_OPTIONS)}, + $http_Util: ${context._lift(http.Util)}, + $path: ${context._lift(path)}, }) `); } @@ -675,12 +638,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure4._registerBindObject(api, host, []); - $Closure4._registerBindObject(http_HEAD, host, []); - $Closure4._registerBindObject(http_OPTIONS, host, []); - $Closure4._registerBindObject(path, host, []); - } if (ops.includes("handle")) { $Closure4._registerBindObject(api.url, host, []); $Closure4._registerBindObject(http_HEAD, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/patch.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/patch.w_compile_tf-aws.md index 9952129d0a2..d2be516ed2d 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/patch.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/patch.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ api_PATCH, _id, body, std_Json }) { +module.exports = function({ $_id, $api_PATCH, $body, $std_Json }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { - {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_PATCH")})((req.method === api_PATCH))}; - {((cond) => {if (!cond) throw new Error("assertion failed: req.vars?.get(\"id\") == _id")})(((req.vars)["id"] === _id))}; - {((cond) => {if (!cond) throw new Error("assertion failed: req.path == \"/path/\"+ _id")})((req.path === ("/path/" + _id)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: req.body == Json.stringify(body)")})((req.body === ((args) => { return JSON.stringify(args[0], null, args[1]) })([body])))}; + async handle(req) { + {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_PATCH")})((req.method === $api_PATCH))}; + {((cond) => {if (!cond) throw new Error("assertion failed: req.vars?.get(\"id\") == _id")})(((req.vars)["id"] === $_id))}; + {((cond) => {if (!cond) throw new Error("assertion failed: req.path == \"/path/\"+ _id")})((req.path === ("/path/" + $_id)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: req.body == Json.stringify(body)")})((req.body === ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body])))}; {((cond) => {if (!cond) throw new Error("assertion failed: req.headers?.get(\"content-type\") == \"application/json\"")})(((req.headers)["content-type"] === "application/json"))}; return { "status": 200, @@ -30,30 +28,28 @@ module.exports = function({ api_PATCH, _id, body, std_Json }) { ## inflight.$Closure2.js ```js -module.exports = function({ api, _id, body, http_PATCH, http_Util, std_Json }) { +module.exports = function({ $_id, $api_url, $body, $http_PATCH, $http_Util, $std_Json }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const url = String.raw({ raw: ["", "/path/", ""] }, api.url, _id); - const response = (await http_Util.patch(url,{ + async handle() { + const url = String.raw({ raw: ["", "/path/", ""] }, $api_url, $_id); + const response = (await $http_Util.patch(url,{ "headers": Object.freeze({"content-type":"application/json"}), - "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([body]),} + "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body]),} )); - const fetchResponse = (await http_Util.patch(url,{ - "method": http_PATCH, + const fetchResponse = (await $http_Util.patch(url,{ + "method": $http_PATCH, "headers": Object.freeze({"content-type":"application/json"}), - "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([body]),} + "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body]),} )); - {((cond) => {if (!cond) throw new Error("assertion failed: response.body == _id")})((response.body === _id))}; + {((cond) => {if (!cond) throw new Error("assertion failed: response.body == _id")})((response.body === $_id))}; {((cond) => {if (!cond) throw new Error("assertion failed: response.status == 200")})((response.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: response.url == url")})((response.url === url))}; - {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.body == _id")})((fetchResponse.body === _id))}; + {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.body == _id")})((fetchResponse.body === $_id))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.status == 200")})((fetchResponse.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.url == url")})((fetchResponse.url === url))}; } @@ -247,7 +243,6 @@ module.exports = function({ api, _id, body, http_PATCH, http_Util, std_Json }) { }, "environment": { "variables": { - "CLOUD_API_C82DF3A5": "${aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url}", "WING_FUNCTION_NAME": "Handler-c89df580", "WING_TARGET": "tf-aws", "WING_TOKEN_TFTOKEN_TOKEN_21": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" @@ -337,20 +332,15 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const api_PATCH_client = context._lift(api_PATCH); - const _id_client = context._lift(_id); - const body_client = context._lift(body); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api_PATCH: ${api_PATCH_client}, - _id: ${_id_client}, - body: ${body_client}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $_id: ${context._lift(_id)}, + $api_PATCH: ${context._lift(api_PATCH)}, + $body: ${context._lift(body)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -366,11 +356,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(_id, host, []); - $Closure1._registerBindObject(api_PATCH, host, []); - $Closure1._registerBindObject(body, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(_id, host, []); $Closure1._registerBindObject(api_PATCH, host, []); @@ -383,24 +368,17 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const api_client = context._lift(api); - const _id_client = context._lift(_id); - const body_client = context._lift(body); - const http_PATCH_client = context._lift(http_PATCH); - const http_UtilClient = http.Util._toInflightType(context); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api: ${api_client}, - _id: ${_id_client}, - body: ${body_client}, - http_PATCH: ${http_PATCH_client}, - http_Util: ${http_UtilClient.text}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure2.js")({ + $_id: ${context._lift(_id)}, + $api_url: ${context._lift(api.url)}, + $body: ${context._lift(body)}, + $http_PATCH: ${context._lift(http_PATCH)}, + $http_Util: ${context._lift(http.Util)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -416,12 +394,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(_id, host, []); - $Closure2._registerBindObject(api, host, []); - $Closure2._registerBindObject(body, host, []); - $Closure2._registerBindObject(http_PATCH, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(_id, host, []); $Closure2._registerBindObject(api.url, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/post.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/post.w_compile_tf-aws.md index 5a58ed46623..677d710cec5 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/post.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/post.w_compile_tf-aws.md @@ -2,19 +2,17 @@ ## inflight.$Closure1.js ```js -module.exports = function({ api_POST, body, std_Json }) { +module.exports = function({ $api_POST, $body, $std_Json }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { - {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_POST")})((req.method === api_POST))}; + async handle(req) { + {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_POST")})((req.method === $api_POST))}; {((cond) => {if (!cond) throw new Error("assertion failed: req.path == \"/path\"")})((req.path === "/path"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: req.body == Json.stringify(body)")})((req.body === ((args) => { return JSON.stringify(args[0], null, args[1]) })([body])))}; + {((cond) => {if (!cond) throw new Error("assertion failed: req.body == Json.stringify(body)")})((req.body === ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body])))}; {((cond) => {if (!cond) throw new Error("assertion failed: req.headers?.get(\"content-type\") == \"application/json\"")})(((req.headers)["content-type"] === "application/json"))}; return { "status": 200, @@ -29,30 +27,28 @@ module.exports = function({ api_POST, body, std_Json }) { ## inflight.$Closure2.js ```js -module.exports = function({ api, body, http_POST, http_Util, std_Json }) { +module.exports = function({ $api_url, $body, $http_POST, $http_Util, $std_Json }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const url = (api.url + "/path"); - const response = (await http_Util.post(url,{ + async handle() { + const url = ($api_url + "/path"); + const response = (await $http_Util.post(url,{ "headers": Object.freeze({"content-type":"application/json"}), - "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([body]),} + "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body]),} )); - const fetchResponse = (await http_Util.post(url,{ - "method": http_POST, + const fetchResponse = (await $http_Util.post(url,{ + "method": $http_POST, "headers": Object.freeze({"content-type":"application/json"}), - "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([body]),} + "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body]),} )); - {((cond) => {if (!cond) throw new Error("assertion failed: response.body == Json.stringify(body)")})((response.body === ((args) => { return JSON.stringify(args[0], null, args[1]) })([body])))}; + {((cond) => {if (!cond) throw new Error("assertion failed: response.body == Json.stringify(body)")})((response.body === ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body])))}; {((cond) => {if (!cond) throw new Error("assertion failed: response.status == 200")})((response.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: response.url == url")})((response.url === url))}; - {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.body == Json.stringify(body)")})((fetchResponse.body === ((args) => { return JSON.stringify(args[0], null, args[1]) })([body])))}; + {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.body == Json.stringify(body)")})((fetchResponse.body === ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body])))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.status == 200")})((fetchResponse.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.url == url")})((fetchResponse.url === url))}; } @@ -246,7 +242,6 @@ module.exports = function({ api, body, http_POST, http_Util, std_Json }) { }, "environment": { "variables": { - "CLOUD_API_C82DF3A5": "${aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url}", "WING_FUNCTION_NAME": "Handler-c88947b5", "WING_TARGET": "tf-aws", "WING_TOKEN_TFTOKEN_TOKEN_21": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" @@ -336,18 +331,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const api_POST_client = context._lift(api_POST); - const body_client = context._lift(body); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api_POST: ${api_POST_client}, - body: ${body_client}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $api_POST: ${context._lift(api_POST)}, + $body: ${context._lift(body)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -363,10 +354,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(api_POST, host, []); - $Closure1._registerBindObject(body, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(api_POST, host, []); $Closure1._registerBindObject(body, host, []); @@ -378,22 +365,16 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const api_client = context._lift(api); - const body_client = context._lift(body); - const http_POST_client = context._lift(http_POST); - const http_UtilClient = http.Util._toInflightType(context); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api: ${api_client}, - body: ${body_client}, - http_POST: ${http_POST_client}, - http_Util: ${http_UtilClient.text}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure2.js")({ + $api_url: ${context._lift(api.url)}, + $body: ${context._lift(body)}, + $http_POST: ${context._lift(http_POST)}, + $http_Util: ${context._lift(http.Util)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -409,11 +390,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(api, host, []); - $Closure2._registerBindObject(body, host, []); - $Closure2._registerBindObject(http_POST, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(api.url, host, []); $Closure2._registerBindObject(body, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/put.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/put.w_compile_tf-aws.md index b8870dcab32..af1f014b164 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/put.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/api/put.w_compile_tf-aws.md @@ -2,22 +2,20 @@ ## inflight.$Closure1.js ```js -module.exports = function({ _id, user, api_PUT, body, std_Json }) { +module.exports = function({ $_id, $api_PUT, $body, $std_Json, $user }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { - const path = String.raw({ raw: ["/path/", "/nn/", ""] }, _id, user); - {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_PUT")})((req.method === api_PUT))}; - {((cond) => {if (!cond) throw new Error("assertion failed: req.vars?.get(\"id\") == _id")})(((req.vars)["id"] === _id))}; - {((cond) => {if (!cond) throw new Error("assertion failed: req.vars?.get(\"user\") == user")})(((req.vars)["user"] === user))}; + async handle(req) { + const path = String.raw({ raw: ["/path/", "/nn/", ""] }, $_id, $user); + {((cond) => {if (!cond) throw new Error("assertion failed: req.method == api_PUT")})((req.method === $api_PUT))}; + {((cond) => {if (!cond) throw new Error("assertion failed: req.vars?.get(\"id\") == _id")})(((req.vars)["id"] === $_id))}; + {((cond) => {if (!cond) throw new Error("assertion failed: req.vars?.get(\"user\") == user")})(((req.vars)["user"] === $user))}; {((cond) => {if (!cond) throw new Error("assertion failed: req.path == path")})((req.path === path))}; - {((cond) => {if (!cond) throw new Error("assertion failed: req.body == Json.stringify(body)")})((req.body === ((args) => { return JSON.stringify(args[0], null, args[1]) })([body])))}; + {((cond) => {if (!cond) throw new Error("assertion failed: req.body == Json.stringify(body)")})((req.body === ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body])))}; {((cond) => {if (!cond) throw new Error("assertion failed: req.headers?.get(\"content-type\") == \"application/json\"")})(((req.headers)["content-type"] === "application/json"))}; return { "status": 200, @@ -33,32 +31,30 @@ module.exports = function({ _id, user, api_PUT, body, std_Json }) { ## inflight.$Closure2.js ```js -module.exports = function({ api, _id, user, body, http_PUT, http_Util, std_Json }) { +module.exports = function({ $_id, $api_url, $body, $http_PUT, $http_Util, $std_Json, $user }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const url = String.raw({ raw: ["", "/path/", "/nn/", ""] }, api.url, _id, user); - const response = (await http_Util.put(url,{ + async handle() { + const url = String.raw({ raw: ["", "/path/", "/nn/", ""] }, $api_url, $_id, $user); + const response = (await $http_Util.put(url,{ "headers": Object.freeze({"content-type":"application/json"}), - "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([body]),} + "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body]),} )); - const fetchResponse = (await http_Util.put(url,{ - "method": http_PUT, + const fetchResponse = (await $http_Util.put(url,{ + "method": $http_PUT, "headers": Object.freeze({"content-type":"application/json"}), - "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([body]),} + "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([$body]),} )); {((cond) => {if (!cond) throw new Error("assertion failed: response.headers.get(\"content-type\") == \"application/json; charset=utf-8\"")})(((response.headers)["content-type"] === "application/json; charset=utf-8"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: response.body == _id")})((response.body === _id))}; + {((cond) => {if (!cond) throw new Error("assertion failed: response.body == _id")})((response.body === $_id))}; {((cond) => {if (!cond) throw new Error("assertion failed: response.status == 200")})((response.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: response.url == url")})((response.url === url))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.headers.get(\"content-type\") == \"application/json; charset=utf-8\"")})(((fetchResponse.headers)["content-type"] === "application/json; charset=utf-8"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.body == _id")})((fetchResponse.body === _id))}; + {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.body == _id")})((fetchResponse.body === $_id))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.status == 200")})((fetchResponse.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: fetchResponse.url == url")})((fetchResponse.url === url))}; } @@ -252,7 +248,6 @@ module.exports = function({ api, _id, user, body, http_PUT, http_Util, std_Json }, "environment": { "variables": { - "CLOUD_API_C82DF3A5": "${aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url}", "WING_FUNCTION_NAME": "Handler-c8e4b12f", "WING_TARGET": "tf-aws", "WING_TOKEN_TFTOKEN_TOKEN_21": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" @@ -342,22 +337,16 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const _id_client = context._lift(_id); - const user_client = context._lift(user); - const api_PUT_client = context._lift(api_PUT); - const body_client = context._lift(body); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - _id: ${_id_client}, - user: ${user_client}, - api_PUT: ${api_PUT_client}, - body: ${body_client}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $_id: ${context._lift(_id)}, + $api_PUT: ${context._lift(api_PUT)}, + $body: ${context._lift(body)}, + $std_Json: ${context._lift(std.Json)}, + $user: ${context._lift(user)}, }) `); } @@ -373,12 +362,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(_id, host, []); - $Closure1._registerBindObject(api_PUT, host, []); - $Closure1._registerBindObject(body, host, []); - $Closure1._registerBindObject(user, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(_id, host, []); $Closure1._registerBindObject(api_PUT, host, []); @@ -392,26 +375,18 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const api_client = context._lift(api); - const _id_client = context._lift(_id); - const user_client = context._lift(user); - const body_client = context._lift(body); - const http_PUT_client = context._lift(http_PUT); - const http_UtilClient = http.Util._toInflightType(context); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api: ${api_client}, - _id: ${_id_client}, - user: ${user_client}, - body: ${body_client}, - http_PUT: ${http_PUT_client}, - http_Util: ${http_UtilClient.text}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure2.js")({ + $_id: ${context._lift(_id)}, + $api_url: ${context._lift(api.url)}, + $body: ${context._lift(body)}, + $http_PUT: ${context._lift(http_PUT)}, + $http_Util: ${context._lift(http.Util)}, + $std_Json: ${context._lift(std.Json)}, + $user: ${context._lift(user)}, }) `); } @@ -427,13 +402,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(_id, host, []); - $Closure2._registerBindObject(api, host, []); - $Closure2._registerBindObject(body, host, []); - $Closure2._registerBindObject(http_PUT, host, []); - $Closure2._registerBindObject(user, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(_id, host, []); $Closure2._registerBindObject(api.url, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/add_object.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/add_object.w_compile_tf-aws.md index ba3e187ce72..7e018b799df 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/add_object.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/add_object.w_compile_tf-aws.md @@ -2,19 +2,17 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b, jsonObj1, std_Json }) { +module.exports = function({ $b, $jsonObj1, $std_Json }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: b.list().length == 2")})(((await b.list()).length === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(b.getJson(\"file1.json\")) == Json.stringify(jsonObj1)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([(await b.getJson("file1.json"))]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([jsonObj1])))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.get(\"file2.txt\") == \"Bar\"")})(((await b.get("file2.txt")) === "Bar"))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: b.list().length == 2")})(((await $b.list()).length === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(b.getJson(\"file1.json\")) == Json.stringify(jsonObj1)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([(await $b.getJson("file1.json"))]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([$jsonObj1])))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.get(\"file2.txt\") == \"Bar\"")})(((await $b.get("file2.txt")) === "Bar"))}; } } return $Closure1; @@ -224,18 +222,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); - const jsonObj1_client = context._lift(jsonObj1); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, - jsonObj1: ${jsonObj1_client}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, + $jsonObj1: ${context._lift(jsonObj1)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -251,10 +245,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - $Closure1._registerBindObject(jsonObj1, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["get", "getJson", "list"]); $Closure1._registerBindObject(jsonObj1, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/bucket_list.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/bucket_list.w_compile_tf-aws.md index 575204b2b55..de79d782dd2 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/bucket_list.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/bucket_list.w_compile_tf-aws.md @@ -2,23 +2,21 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const jsonObj1 = Object.freeze({"key1":"value1"}); - {((cond) => {if (!cond) throw new Error("assertion failed: b.list().length == 1")})(((await b.list()).length === 1))}; - (await b.putJson("file1.json",jsonObj1)); - (await b.put("file2.txt","Bar")); - (await b.put("random","Buz")); - const objs = (await b.list()); - const objs2 = (await b.list("file")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.list().length == 1")})(((await $b.list()).length === 1))}; + (await $b.putJson("file1.json",jsonObj1)); + (await $b.put("file2.txt","Bar")); + (await $b.put("random","Buz")); + const objs = (await $b.list()); + const objs2 = (await $b.list("file")); {((cond) => {if (!cond) throw new Error("assertion failed: objs.contains(\"file1.json\")")})(objs.includes("file1.json"))}; {((cond) => {if (!cond) throw new Error("assertion failed: objs.contains(\"file2.txt\")")})(objs.includes("file2.txt"))}; {((cond) => {if (!cond) throw new Error("assertion failed: objs.contains(\"file3.txt\")")})(objs.includes("file3.txt"))}; @@ -227,14 +225,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, }) `); } @@ -250,9 +246,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["list", "put", "putJson"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/delete.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/delete.w_compile_tf-aws.md index 74ea789552a..ddba570ef43 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/delete.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/delete.w_compile_tf-aws.md @@ -2,34 +2,32 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { let error = ""; const jsonObj1 = Object.freeze({"key1":"value1"}); - (await b.putJson("file1.json",jsonObj1)); - (await b.delete("file1.txt")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.exists(\"file1.json\")")})((await b.exists("file1.json")))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.exists(\"file2.txt\")")})((await b.exists("file2.txt")))}; - (await b.delete("file1.json",Object.freeze({"mustExist":true}))); + (await $b.putJson("file1.json",jsonObj1)); + (await $b.delete("file1.txt")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.exists(\"file1.json\")")})((await $b.exists("file1.json")))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.exists(\"file2.txt\")")})((await $b.exists("file2.txt")))}; + (await $b.delete("file1.json",Object.freeze({"mustExist":true}))); try { - (await b.delete("file1.json",Object.freeze({"mustExist":true}))); + (await $b.delete("file1.json",Object.freeze({"mustExist":true}))); } catch ($error_e) { const e = $error_e.message; error = e; } {((cond) => {if (!cond) throw new Error("assertion failed: error == \"Object does not exist (key=file1.json).\"")})((error === "Object does not exist (key=file1.json)."))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.exists(\"file2.txt\")")})((await b.exists("file2.txt")))}; - (await b.delete("file2.txt")); - {((cond) => {if (!cond) throw new Error("assertion failed: !b.exists(\"file2.txt\")")})((!(await b.exists("file2.txt"))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.exists(\"file2.txt\")")})((await $b.exists("file2.txt")))}; + (await $b.delete("file2.txt")); + {((cond) => {if (!cond) throw new Error("assertion failed: !b.exists(\"file2.txt\")")})((!(await $b.exists("file2.txt"))))}; } } return $Closure1; @@ -228,14 +226,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, }) `); } @@ -251,9 +247,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["delete", "exists", "putJson"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/events.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/events.w_compile_tf-aws.md index f7e2df9dc9b..164933c87ce 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/events.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/events.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ table, idsCounter }) { +module.exports = function({ $idsCounter, $table }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key, operation, source) { - (await table.insert(String.raw({ raw: ["", ""] }, (await idsCounter.inc())),Object.freeze({"key":key,"operation":operation,"source":String.raw({ raw: ["", ""] }, source)}))); + async handle(key, operation, source) { + (await $table.insert(String.raw({ raw: ["", ""] }, (await $idsCounter.inc())),Object.freeze({"key":key,"operation":operation,"source":String.raw({ raw: ["", ""] }, source)}))); } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ table, idsCounter }) { ## inflight.$Closure2.js ```js -module.exports = function({ logHistory, Source }) { +module.exports = function({ $Source, $logHistory }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key) { - (await logHistory(key,"DELETE",Source.anyEvent)); + async handle(key) { + (await $logHistory(key,"DELETE",$Source.anyEvent)); } } return $Closure2; @@ -42,17 +38,15 @@ module.exports = function({ logHistory, Source }) { ## inflight.$Closure3.js ```js -module.exports = function({ logHistory, Source }) { +module.exports = function({ $Source, $logHistory }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key) { - (await logHistory(key,"UPDATE",Source.anyEvent)); + async handle(key) { + (await $logHistory(key,"UPDATE",$Source.anyEvent)); } } return $Closure3; @@ -62,17 +56,15 @@ module.exports = function({ logHistory, Source }) { ## inflight.$Closure4.js ```js -module.exports = function({ logHistory, Source }) { +module.exports = function({ $Source, $logHistory }) { class $Closure4 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key) { - (await logHistory(key,"CREATE",Source.anyEvent)); + async handle(key) { + (await $logHistory(key,"CREATE",$Source.anyEvent)); } } return $Closure4; @@ -82,17 +74,15 @@ module.exports = function({ logHistory, Source }) { ## inflight.$Closure5.js ```js -module.exports = function({ logHistory, Source }) { +module.exports = function({ $Source, $logHistory }) { class $Closure5 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key, event) { - (await logHistory(key,String.raw({ raw: ["", ""] }, event),Source.onEvent)); + async handle(key, event) { + (await $logHistory(key,String.raw({ raw: ["", ""] }, event),$Source.onEvent)); } } return $Closure5; @@ -102,22 +92,20 @@ module.exports = function({ logHistory, Source }) { ## inflight.$Closure6.js ```js -module.exports = function({ Util }) { +module.exports = function({ $Util }) { class $Closure6 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(pred) { + async handle(pred) { let i = 0; while ((i < 12)) { if ((await pred())) { return true; } - (await Util.sleep(10000)); + (await $Util.sleep(10000)); i = (i + 1); } return false; @@ -130,19 +118,17 @@ module.exports = function({ Util }) { ## inflight.$Closure7.js ```js -module.exports = function({ table }) { +module.exports = function({ $table }) { class $Closure7 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(opts) { - return async () => { + async handle(opts) { + return async () => { let count = 0; - for (const u of (await table.list())) { + for (const u of (await $table.list())) { if (((((u)["key"] === opts.key) && ((u)["operation"] === opts.type)) && ((u)["source"] === String.raw({ raw: ["", ""] }, opts.source)))) { count = (count + 1); } @@ -159,31 +145,29 @@ module.exports = function({ table }) { ## inflight.$Closure8.js ```js -module.exports = function({ b, wait, checkHitCount, Source }) { +module.exports = function({ $Source, $b, $checkHitCount, $wait }) { class $Closure8 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await b.put("a","1")); - (await b.put("b","1")); - (await b.put("c","1")); - (await b.put("b","100")); - (await b.delete("c")); - {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"a\", type: \"CREATE\", source: Source.anyEvent, count: 1))")})((await wait((await checkHitCount({ key: "a", type: "CREATE", source: Source.anyEvent, count: 1 })))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"b\", type: \"CREATE\", source: Source.anyEvent, count: 1))")})((await wait((await checkHitCount({ key: "b", type: "CREATE", source: Source.anyEvent, count: 1 })))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"c\", type: \"CREATE\", source: Source.anyEvent, count: 1))")})((await wait((await checkHitCount({ key: "c", type: "CREATE", source: Source.anyEvent, count: 1 })))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"a\", type: \"CREATE\", source: Source.onEvent, count: 1))")})((await wait((await checkHitCount({ key: "a", type: "CREATE", source: Source.onEvent, count: 1 })))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"b\", type: \"CREATE\", source: Source.onEvent, count: 1))")})((await wait((await checkHitCount({ key: "b", type: "CREATE", source: Source.onEvent, count: 1 })))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"c\", type: \"CREATE\", source: Source.onEvent, count: 1))")})((await wait((await checkHitCount({ key: "c", type: "CREATE", source: Source.onEvent, count: 1 })))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"b\", type: \"UPDATE\", source: Source.anyEvent, count: 1))")})((await wait((await checkHitCount({ key: "b", type: "UPDATE", source: Source.anyEvent, count: 1 })))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"c\", type: \"DELETE\", source: Source.anyEvent, count: 1))")})((await wait((await checkHitCount({ key: "c", type: "DELETE", source: Source.anyEvent, count: 1 })))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"b\", type: \"UPDATE\", source: Source.onEvent, count: 1))")})((await wait((await checkHitCount({ key: "b", type: "UPDATE", source: Source.onEvent, count: 1 })))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"c\", type: \"DELETE\", source: Source.onEvent, count: 1))")})((await wait((await checkHitCount({ key: "c", type: "DELETE", source: Source.onEvent, count: 1 })))))}; + async handle() { + (await $b.put("a","1")); + (await $b.put("b","1")); + (await $b.put("c","1")); + (await $b.put("b","100")); + (await $b.delete("c")); + {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"a\", type: \"CREATE\", source: Source.anyEvent, count: 1))")})((await $wait((await $checkHitCount({ key: "a", type: "CREATE", source: $Source.anyEvent, count: 1 })))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"b\", type: \"CREATE\", source: Source.anyEvent, count: 1))")})((await $wait((await $checkHitCount({ key: "b", type: "CREATE", source: $Source.anyEvent, count: 1 })))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"c\", type: \"CREATE\", source: Source.anyEvent, count: 1))")})((await $wait((await $checkHitCount({ key: "c", type: "CREATE", source: $Source.anyEvent, count: 1 })))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"a\", type: \"CREATE\", source: Source.onEvent, count: 1))")})((await $wait((await $checkHitCount({ key: "a", type: "CREATE", source: $Source.onEvent, count: 1 })))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"b\", type: \"CREATE\", source: Source.onEvent, count: 1))")})((await $wait((await $checkHitCount({ key: "b", type: "CREATE", source: $Source.onEvent, count: 1 })))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"c\", type: \"CREATE\", source: Source.onEvent, count: 1))")})((await $wait((await $checkHitCount({ key: "c", type: "CREATE", source: $Source.onEvent, count: 1 })))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"b\", type: \"UPDATE\", source: Source.anyEvent, count: 1))")})((await $wait((await $checkHitCount({ key: "b", type: "UPDATE", source: $Source.anyEvent, count: 1 })))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"c\", type: \"DELETE\", source: Source.anyEvent, count: 1))")})((await $wait((await $checkHitCount({ key: "c", type: "DELETE", source: $Source.anyEvent, count: 1 })))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"b\", type: \"UPDATE\", source: Source.onEvent, count: 1))")})((await $wait((await $checkHitCount({ key: "b", type: "UPDATE", source: $Source.onEvent, count: 1 })))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: wait(checkHitCount(key: \"c\", type: \"DELETE\", source: Source.onEvent, count: 1))")})((await $wait((await $checkHitCount({ key: "c", type: "DELETE", source: $Source.onEvent, count: 1 })))))}; } } return $Closure8; @@ -197,9 +181,7 @@ module.exports = function({ }) { class Util { constructor({ }) { } - async $inflight_init() { - } - static async sleep(milli) { + static async sleep(milli) { return (require("/sleep.js")["sleep"])(milli) } } @@ -1088,12 +1070,11 @@ class $Root extends $stdlib.std.Resource { class Util extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("sleep"); + this._addInflightOps("sleep", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Util.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Util.js")({ }) `); } @@ -1108,31 +1089,18 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } - static _registerTypeBind(host, ops) { - if (ops.includes("sleep")) { - } - super._registerTypeBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const table_client = context._lift(table); - const idsCounter_client = context._lift(idsCounter); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - table: ${table_client}, - idsCounter: ${idsCounter_client}, + require("./inflight.$Closure1.js")({ + $idsCounter: ${context._lift(idsCounter)}, + $table: ${context._lift(table)}, }) `); } @@ -1148,10 +1116,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(idsCounter, host, []); - $Closure1._registerBindObject(table, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(idsCounter, host, ["inc"]); $Closure1._registerBindObject(table, host, ["insert"]); @@ -1163,22 +1127,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const logHistory_client = context._lift(logHistory); - const SourceClient = $stdlib.core.NodeJsCode.fromInline(` - Object.freeze((function (tmp) { - tmp[tmp["anyEvent"] = 0] = "anyEvent"; - tmp[tmp["onEvent"] = 1] = "onEvent"; - return tmp; - })({})) - `); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - logHistory: ${logHistory_client}, - Source: ${SourceClient.text}, + require("./inflight.$Closure2.js")({ + $Source: ${context._lift(Source)}, + $logHistory: ${context._lift(logHistory)}, }) `); } @@ -1194,9 +1149,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(logHistory, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(logHistory, host, ["handle"]); } @@ -1207,22 +1159,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const logHistory_client = context._lift(logHistory); - const SourceClient = $stdlib.core.NodeJsCode.fromInline(` - Object.freeze((function (tmp) { - tmp[tmp["anyEvent"] = 0] = "anyEvent"; - tmp[tmp["onEvent"] = 1] = "onEvent"; - return tmp; - })({})) - `); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - logHistory: ${logHistory_client}, - Source: ${SourceClient.text}, + require("./inflight.$Closure3.js")({ + $Source: ${context._lift(Source)}, + $logHistory: ${context._lift(logHistory)}, }) `); } @@ -1238,9 +1181,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(logHistory, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(logHistory, host, ["handle"]); } @@ -1251,22 +1191,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; - const logHistory_client = context._lift(logHistory); - const SourceClient = $stdlib.core.NodeJsCode.fromInline(` - Object.freeze((function (tmp) { - tmp[tmp["anyEvent"] = 0] = "anyEvent"; - tmp[tmp["onEvent"] = 1] = "onEvent"; - return tmp; - })({})) - `); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - logHistory: ${logHistory_client}, - Source: ${SourceClient.text}, + require("./inflight.$Closure4.js")({ + $Source: ${context._lift(Source)}, + $logHistory: ${context._lift(logHistory)}, }) `); } @@ -1282,9 +1213,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure4._registerBindObject(logHistory, host, []); - } if (ops.includes("handle")) { $Closure4._registerBindObject(logHistory, host, ["handle"]); } @@ -1295,22 +1223,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure5.js"; - const logHistory_client = context._lift(logHistory); - const SourceClient = $stdlib.core.NodeJsCode.fromInline(` - Object.freeze((function (tmp) { - tmp[tmp["anyEvent"] = 0] = "anyEvent"; - tmp[tmp["onEvent"] = 1] = "onEvent"; - return tmp; - })({})) - `); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - logHistory: ${logHistory_client}, - Source: ${SourceClient.text}, + require("./inflight.$Closure5.js")({ + $Source: ${context._lift(Source)}, + $logHistory: ${context._lift(logHistory)}, }) `); } @@ -1326,9 +1245,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure5._registerBindObject(logHistory, host, []); - } if (ops.includes("handle")) { $Closure5._registerBindObject(logHistory, host, ["handle"]); } @@ -1339,14 +1255,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure6.js"; - const UtilClient = Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Util: ${UtilClient.text}, + require("./inflight.$Closure6.js")({ + $Util: ${context._lift(Util)}, }) `); } @@ -1362,8 +1276,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } if (ops.includes("handle")) { $Closure6._registerBindObject(Util, host, ["sleep"]); } @@ -1374,14 +1286,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure7.js"; - const table_client = context._lift(table); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - table: ${table_client}, + require("./inflight.$Closure7.js")({ + $table: ${context._lift(table)}, }) `); } @@ -1397,9 +1307,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure7._registerBindObject(table, host, []); - } if (ops.includes("handle")) { $Closure7._registerBindObject(table, host, ["list"]); } @@ -1410,26 +1317,15 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure8.js"; - const b_client = context._lift(b); - const wait_client = context._lift(wait); - const checkHitCount_client = context._lift(checkHitCount); - const SourceClient = $stdlib.core.NodeJsCode.fromInline(` - Object.freeze((function (tmp) { - tmp[tmp["anyEvent"] = 0] = "anyEvent"; - tmp[tmp["onEvent"] = 1] = "onEvent"; - return tmp; - })({})) - `); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, - wait: ${wait_client}, - checkHitCount: ${checkHitCount_client}, - Source: ${SourceClient.text}, + require("./inflight.$Closure8.js")({ + $Source: ${context._lift(Source)}, + $b: ${context._lift(b)}, + $checkHitCount: ${context._lift(checkHitCount)}, + $wait: ${context._lift(wait)}, }) `); } @@ -1445,11 +1341,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure8._registerBindObject(b, host, []); - $Closure8._registerBindObject(checkHitCount, host, []); - $Closure8._registerBindObject(wait, host, []); - } if (ops.includes("handle")) { $Closure8._registerBindObject(b, host, ["delete", "put"]); $Closure8._registerBindObject(checkHitCount, host, ["handle"]); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/exists.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/exists.w_compile_tf-aws.md index 6a04d81479b..1879710d7dc 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/exists.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/exists.w_compile_tf-aws.md @@ -2,23 +2,21 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await b.put("test1.txt","Foo")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.exists(\"test1.txt\")")})((await b.exists("test1.txt")))}; - {((cond) => {if (!cond) throw new Error("assertion failed: !b.exists(\"test2.txt\")")})((!(await b.exists("test2.txt"))))}; - (await b.put("test2.txt","Bar")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.exists(\"test2.txt\")")})((await b.exists("test2.txt")))}; - (await b.delete("test1.txt")); - {((cond) => {if (!cond) throw new Error("assertion failed: !b.exists(\"test1.txt\")")})((!(await b.exists("test1.txt"))))}; + async handle() { + (await $b.put("test1.txt","Foo")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.exists(\"test1.txt\")")})((await $b.exists("test1.txt")))}; + {((cond) => {if (!cond) throw new Error("assertion failed: !b.exists(\"test2.txt\")")})((!(await $b.exists("test2.txt"))))}; + (await $b.put("test2.txt","Bar")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.exists(\"test2.txt\")")})((await $b.exists("test2.txt")))}; + (await $b.delete("test1.txt")); + {((cond) => {if (!cond) throw new Error("assertion failed: !b.exists(\"test1.txt\")")})((!(await $b.exists("test1.txt"))))}; } } return $Closure1; @@ -206,14 +204,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, }) `); } @@ -229,9 +225,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["delete", "exists", "put"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/public_url.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/public_url.w_compile_tf-aws.md index c2a9a36d95d..c52a87c61dd 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/public_url.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/public_url.w_compile_tf-aws.md @@ -2,26 +2,24 @@ ## inflight.$Closure1.js ```js -module.exports = function({ publicBucket, privateBucket, util_Util, http_Util }) { +module.exports = function({ $http_Util, $privateBucket, $publicBucket, $util_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { let error = ""; - (await publicBucket.put("file1.txt","Foo")); - (await privateBucket.put("file2.txt","Bar")); - const publicUrl = (await publicBucket.publicUrl("file1.txt")); + (await $publicBucket.put("file1.txt","Foo")); + (await $privateBucket.put("file2.txt","Bar")); + const publicUrl = (await $publicBucket.publicUrl("file1.txt")); {((cond) => {if (!cond) throw new Error("assertion failed: publicUrl != \"\"")})((publicUrl !== ""))}; - if (((await util_Util.env("WING_TARGET")) !== "sim")) { - {((cond) => {if (!cond) throw new Error("assertion failed: http.get(publicUrl).body == \"Foo\"")})(((await http_Util.get(publicUrl)).body === "Foo"))}; + if (((await $util_Util.env("WING_TARGET")) !== "sim")) { + {((cond) => {if (!cond) throw new Error("assertion failed: http.get(publicUrl).body == \"Foo\"")})(((await $http_Util.get(publicUrl)).body === "Foo"))}; } try { - (await privateBucket.publicUrl("file2.txt")); + (await $privateBucket.publicUrl("file2.txt")); } catch ($error_e) { const e = $error_e.message; @@ -269,20 +267,15 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const publicBucket_client = context._lift(publicBucket); - const privateBucket_client = context._lift(privateBucket); - const util_UtilClient = util.Util._toInflightType(context); - const http_UtilClient = http.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - publicBucket: ${publicBucket_client}, - privateBucket: ${privateBucket_client}, - util_Util: ${util_UtilClient.text}, - http_Util: ${http_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $http_Util: ${context._lift(http.Util)}, + $privateBucket: ${context._lift(privateBucket)}, + $publicBucket: ${context._lift(publicBucket)}, + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -298,10 +291,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(privateBucket, host, []); - $Closure1._registerBindObject(publicBucket, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(privateBucket, host, ["publicUrl", "put"]); $Closure1._registerBindObject(publicBucket, host, ["publicUrl", "put"]); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/put.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/put.w_compile_tf-aws.md index 6899fc56b04..944247937c2 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/put.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/put.w_compile_tf-aws.md @@ -2,28 +2,26 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await b.put("test1.txt","Foo")); - (await b.put("test2.txt","Bar")); - const first = (await b.get("test1.txt")); - const second = (await b.get("test2.txt")); + async handle() { + (await $b.put("test1.txt","Foo")); + (await $b.put("test2.txt","Bar")); + const first = (await $b.get("test1.txt")); + const second = (await $b.get("test2.txt")); {((cond) => {if (!cond) throw new Error("assertion failed: first == \"Foo\"")})((first === "Foo"))}; {((cond) => {if (!cond) throw new Error("assertion failed: second == \"Bar\"")})((second === "Bar"))}; - (await b.delete("test1.txt")); - const files = (await b.list()); + (await $b.delete("test1.txt")); + const files = (await $b.list()); {((cond) => {if (!cond) throw new Error("assertion failed: files.contains(\"test1.txt\") == false")})((files.includes("test1.txt") === false))}; {((cond) => {if (!cond) throw new Error("assertion failed: files.contains(\"test2.txt\") == true")})((files.includes("test2.txt") === true))}; - (await b.put("test2.txt","Baz")); - const third = (await b.get("test2.txt")); + (await $b.put("test2.txt","Baz")); + const third = (await $b.get("test2.txt")); {((cond) => {if (!cond) throw new Error("assertion failed: third == \"Baz\"")})((third === "Baz"))}; } } @@ -212,14 +210,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, }) `); } @@ -235,9 +231,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["delete", "get", "list", "put"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/put_json.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/put_json.w_compile_tf-aws.md index ecff55319dc..1f8b7621b96 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/put_json.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/put_json.w_compile_tf-aws.md @@ -2,30 +2,28 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const jsonObj1 = Object.freeze({"test":"test1"}); const jsonObj2 = Object.freeze({"test":"test2"}); - (await b.putJson("test1.txt",jsonObj1)); - (await b.putJson("test2.txt",jsonObj2)); - const testJson1 = (await b.getJson("test1.txt")); - const testJson2 = (await b.getJson("test2.txt")); + (await $b.putJson("test1.txt",jsonObj1)); + (await $b.putJson("test2.txt",jsonObj2)); + const testJson1 = (await $b.getJson("test1.txt")); + const testJson2 = (await $b.getJson("test2.txt")); {((cond) => {if (!cond) throw new Error("assertion failed: testJson1.get(\"test\") == jsonObj1.get(\"test\")")})(((testJson1)["test"] === (jsonObj1)["test"]))}; {((cond) => {if (!cond) throw new Error("assertion failed: testJson2.get(\"test\") == jsonObj2.get(\"test\")")})(((testJson2)["test"] === (jsonObj2)["test"]))}; const jsonObj3 = Object.freeze({"test":"test3"}); - (await b.putJson("test3.txt",jsonObj3)); - const testJson3 = (await b.getJson("test3.txt")); + (await $b.putJson("test3.txt",jsonObj3)); + const testJson3 = (await $b.getJson("test3.txt")); {((cond) => {if (!cond) throw new Error("assertion failed: testJson3.get(\"test\") == jsonObj3.get(\"test\")")})(((testJson3)["test"] === (jsonObj3)["test"]))}; - (await b.delete("test1.txt")); - const files = (await b.list()); + (await $b.delete("test1.txt")); + const files = (await $b.list()); {((cond) => {if (!cond) throw new Error("assertion failed: files.contains(\"test1.txt\") == false")})((files.includes("test1.txt") === false))}; {((cond) => {if (!cond) throw new Error("assertion failed: files.contains(\"test2.txt\") == true")})((files.includes("test2.txt") === true))}; } @@ -215,14 +213,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, }) `); } @@ -238,9 +234,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["delete", "getJson", "list", "putJson"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_delete.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_delete.w_compile_tf-aws.md index 11335110792..91cfc8feb72 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_delete.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_delete.w_compile_tf-aws.md @@ -2,27 +2,25 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const jsonObj2 = Object.freeze({"key2":"value2"}); - (await b.put("file1.txt","Foo")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file1.txt\") == true")})(((await b.tryDelete("file1.txt")) === true))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file1.txt\") == false")})(((await b.tryDelete("file1.txt")) === false))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"random\") == false")})(((await b.tryDelete("random")) === false))}; - (await b.put("file2.txt","Bar")); - (await b.putJson("file2.json",jsonObj2)); - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file2.txt\") == true")})(((await b.tryDelete("file2.txt")) === true))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file2.json\") == true")})(((await b.tryDelete("file2.json")) === true))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file2.txt\") == false")})(((await b.tryDelete("file2.txt")) === false))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file2.json\") == false")})(((await b.tryDelete("file2.json")) === false))}; + (await $b.put("file1.txt","Foo")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file1.txt\") == true")})(((await $b.tryDelete("file1.txt")) === true))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file1.txt\") == false")})(((await $b.tryDelete("file1.txt")) === false))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"random\") == false")})(((await $b.tryDelete("random")) === false))}; + (await $b.put("file2.txt","Bar")); + (await $b.putJson("file2.json",jsonObj2)); + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file2.txt\") == true")})(((await $b.tryDelete("file2.txt")) === true))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file2.json\") == true")})(((await $b.tryDelete("file2.json")) === true))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file2.txt\") == false")})(((await $b.tryDelete("file2.txt")) === false))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryDelete(\"file2.json\") == false")})(((await $b.tryDelete("file2.json")) === false))}; } } return $Closure1; @@ -210,14 +208,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, }) `); } @@ -233,9 +229,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["put", "putJson", "tryDelete"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_get.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_get.w_compile_tf-aws.md index 0761b03e9ee..851b82ffce5 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_get.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_get.w_compile_tf-aws.md @@ -2,23 +2,21 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await b.put("test1.txt","Foo")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGet(\"test1.txt\") == \"Foo\"")})(((await b.tryGet("test1.txt")) === "Foo"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGet(\"test2.txt\") == nil")})(((await b.tryGet("test2.txt")) === undefined))}; - (await b.put("test2.txt","Bar")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGet(\"test2.txt\") == \"Bar\"")})(((await b.tryGet("test2.txt")) === "Bar"))}; - (await b.delete("test1.txt")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGet(\"test1.txt\") == nil")})(((await b.tryGet("test1.txt")) === undefined))}; + async handle() { + (await $b.put("test1.txt","Foo")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGet(\"test1.txt\") == \"Foo\"")})(((await $b.tryGet("test1.txt")) === "Foo"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGet(\"test2.txt\") == nil")})(((await $b.tryGet("test2.txt")) === undefined))}; + (await $b.put("test2.txt","Bar")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGet(\"test2.txt\") == \"Bar\"")})(((await $b.tryGet("test2.txt")) === "Bar"))}; + (await $b.delete("test1.txt")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGet(\"test1.txt\") == nil")})(((await $b.tryGet("test1.txt")) === undefined))}; } } return $Closure1; @@ -206,14 +204,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, }) `); } @@ -229,9 +225,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["delete", "put", "tryGet"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_get_json.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_get_json.w_compile_tf-aws.md index d58955738a3..d2a51fe5849 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_get_json.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/bucket/try_get_json.w_compile_tf-aws.md @@ -2,27 +2,25 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b, std_Json }) { +module.exports = function({ $b, $std_Json }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const jsonObj1 = Object.freeze({"key1":"value1"}); const jsonObj2 = Object.freeze({"key2":"value2"}); - (await b.putJson("file1.json",jsonObj1)); - {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(b.tryGetJson(\"file1.json\")) == Json.stringify(jsonObj1)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([(await b.tryGetJson("file1.json"))]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([jsonObj1])))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGetJson(\"file2.json\") == nil")})(((await b.tryGetJson("file2.json")) === undefined))}; - (await b.putJson("file2.json",jsonObj2)); - {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(b.tryGetJson(\"file2.json\")) == Json.stringify(jsonObj2)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([(await b.tryGetJson("file2.json"))]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([jsonObj2])))}; - (await b.delete("file1.json")); - (await b.delete("file2.json")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGetJson(\"file1.json\") == nil")})(((await b.tryGetJson("file1.json")) === undefined))}; - {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGetJson(\"file2.json\") == nil")})(((await b.tryGetJson("file2.json")) === undefined))}; + (await $b.putJson("file1.json",jsonObj1)); + {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(b.tryGetJson(\"file1.json\")) == Json.stringify(jsonObj1)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([(await $b.tryGetJson("file1.json"))]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([jsonObj1])))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGetJson(\"file2.json\") == nil")})(((await $b.tryGetJson("file2.json")) === undefined))}; + (await $b.putJson("file2.json",jsonObj2)); + {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(b.tryGetJson(\"file2.json\")) == Json.stringify(jsonObj2)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([(await $b.tryGetJson("file2.json"))]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([jsonObj2])))}; + (await $b.delete("file1.json")); + (await $b.delete("file2.json")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGetJson(\"file1.json\") == nil")})(((await $b.tryGetJson("file1.json")) === undefined))}; + {((cond) => {if (!cond) throw new Error("assertion failed: b.tryGetJson(\"file2.json\") == nil")})(((await $b.tryGetJson("file2.json")) === undefined))}; } } return $Closure1; @@ -210,16 +208,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -235,9 +230,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["delete", "putJson", "tryGetJson"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/dec.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/dec.w_compile_tf-aws.md index 9b3e8ae09af..ff9c2dd85d5 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/dec.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/dec.w_compile_tf-aws.md @@ -2,22 +2,20 @@ ## inflight.$Closure1.js ```js -module.exports = function({ counter }) { +module.exports = function({ $counter }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 1")})(((await counter.peek()) === 1))}; - const dec1 = (await counter.dec()); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 0")})(((await counter.peek()) === 0))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 1")})(((await $counter.peek()) === 1))}; + const dec1 = (await $counter.dec()); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 0")})(((await $counter.peek()) === 0))}; {((cond) => {if (!cond) throw new Error("assertion failed: dec1 == 1")})((dec1 === 1))}; - const dec2 = (await counter.dec(2)); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == -2")})(((await counter.peek()) === (-2)))}; + const dec2 = (await $counter.dec(2)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == -2")})(((await $counter.peek()) === (-2)))}; {((cond) => {if (!cond) throw new Error("assertion failed: dec2 == 0")})((dec2 === 0))}; } } @@ -28,23 +26,21 @@ module.exports = function({ counter }) { ## inflight.$Closure2.js ```js -module.exports = function({ counter }) { +module.exports = function({ $counter }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const key = "my-key"; - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 0")})(((await counter.peek(key)) === 0))}; - const dec1 = (await counter.dec(undefined,key)); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == -1")})(((await counter.peek(key)) === (-1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 0")})(((await $counter.peek(key)) === 0))}; + const dec1 = (await $counter.dec(undefined,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == -1")})(((await $counter.peek(key)) === (-1)))}; {((cond) => {if (!cond) throw new Error("assertion failed: dec1 == 0")})((dec1 === 0))}; - const dec2 = (await counter.dec(2,key)); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == -3")})(((await counter.peek(key)) === (-3)))}; + const dec2 = (await $counter.dec(2,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == -3")})(((await $counter.peek(key)) === (-3)))}; {((cond) => {if (!cond) throw new Error("assertion failed: dec2 == -1")})((dec2 === (-1)))}; } } @@ -276,14 +272,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const counter_client = context._lift(counter); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counter: ${counter_client}, + require("./inflight.$Closure1.js")({ + $counter: ${context._lift(counter)}, }) `); } @@ -299,9 +293,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(counter, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(counter, host, ["dec", "peek"]); } @@ -312,14 +303,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const counter_client = context._lift(counter); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counter: ${counter_client}, + require("./inflight.$Closure2.js")({ + $counter: ${context._lift(counter)}, }) `); } @@ -335,9 +324,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(counter, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(counter, host, ["dec", "peek"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/inc.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/inc.w_compile_tf-aws.md index f79b0447410..2f15e83dc1d 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/inc.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/inc.w_compile_tf-aws.md @@ -2,27 +2,25 @@ ## inflight.$Closure1.js ```js -module.exports = function({ counter }) { +module.exports = function({ $counter }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 0")})(((await counter.peek()) === 0))}; - const r0 = (await counter.inc()); + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 0")})(((await $counter.peek()) === 0))}; + const r0 = (await $counter.inc()); {((cond) => {if (!cond) throw new Error("assertion failed: r0 == 0")})((r0 === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 1")})(((await counter.peek()) === 1))}; - const r1 = (await counter.inc()); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 1")})(((await $counter.peek()) === 1))}; + const r1 = (await $counter.inc()); {((cond) => {if (!cond) throw new Error("assertion failed: r1 == 1")})((r1 === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 2")})(((await counter.peek()) === 2))}; - const r2 = (await counter.inc(10)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 2")})(((await $counter.peek()) === 2))}; + const r2 = (await $counter.inc(10)); {((cond) => {if (!cond) throw new Error("assertion failed: r2 == 2")})((r2 === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 12")})(((await counter.peek()) === 12))}; - const r3 = (await counter.inc()); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 12")})(((await $counter.peek()) === 12))}; + const r3 = (await $counter.inc()); {((cond) => {if (!cond) throw new Error("assertion failed: r3 == 12")})((r3 === 12))}; } } @@ -33,28 +31,26 @@ module.exports = function({ counter }) { ## inflight.$Closure2.js ```js -module.exports = function({ counter }) { +module.exports = function({ $counter }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const key = "my-key"; - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 0")})(((await counter.peek(key)) === 0))}; - const r0 = (await counter.inc(undefined,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 0")})(((await $counter.peek(key)) === 0))}; + const r0 = (await $counter.inc(undefined,key)); {((cond) => {if (!cond) throw new Error("assertion failed: r0 == 0")})((r0 === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 1")})(((await counter.peek(key)) === 1))}; - const r1 = (await counter.inc(undefined,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 1")})(((await $counter.peek(key)) === 1))}; + const r1 = (await $counter.inc(undefined,key)); {((cond) => {if (!cond) throw new Error("assertion failed: r1 == 1")})((r1 === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 2")})(((await counter.peek(key)) === 2))}; - const r2 = (await counter.inc(10,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 2")})(((await $counter.peek(key)) === 2))}; + const r2 = (await $counter.inc(10,key)); {((cond) => {if (!cond) throw new Error("assertion failed: r2 == 2")})((r2 === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 12")})(((await counter.peek(key)) === 12))}; - const r3 = (await counter.inc(undefined,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 12")})(((await $counter.peek(key)) === 12))}; + const r3 = (await $counter.inc(undefined,key)); {((cond) => {if (!cond) throw new Error("assertion failed: r3 == 12")})((r3 === 12))}; } } @@ -286,14 +282,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const counter_client = context._lift(counter); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counter: ${counter_client}, + require("./inflight.$Closure1.js")({ + $counter: ${context._lift(counter)}, }) `); } @@ -309,9 +303,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(counter, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(counter, host, ["inc", "peek"]); } @@ -322,14 +313,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const counter_client = context._lift(counter); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counter: ${counter_client}, + require("./inflight.$Closure2.js")({ + $counter: ${context._lift(counter)}, }) `); } @@ -345,9 +334,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(counter, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(counter, host, ["inc", "peek"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/initial.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/initial.w_compile_tf-aws.md index 2e3fc12755d..91f78a53400 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/initial.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/initial.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ counterA }) { +module.exports = function({ $counterA }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: counterA.peek() == 0")})(((await counterA.peek()) === 0))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: counterA.peek() == 0")})(((await $counterA.peek()) === 0))}; } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ counterA }) { ## inflight.$Closure2.js ```js -module.exports = function({ counterB }) { +module.exports = function({ $counterB }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: counterB.peek() == 500")})(((await counterB.peek()) === 500))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: counterB.peek() == 500")})(((await $counterB.peek()) === 500))}; } } return $Closure2; @@ -42,17 +38,15 @@ module.exports = function({ counterB }) { ## inflight.$Closure3.js ```js -module.exports = function({ counterC }) { +module.exports = function({ $counterC }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: counterC.peek() == -198")})(((await counterC.peek()) === (-198)))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: counterC.peek() == -198")})(((await $counterC.peek()) === (-198)))}; } } return $Closure3; @@ -384,14 +378,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const counterA_client = context._lift(counterA); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counterA: ${counterA_client}, + require("./inflight.$Closure1.js")({ + $counterA: ${context._lift(counterA)}, }) `); } @@ -407,9 +399,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(counterA, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(counterA, host, ["peek"]); } @@ -420,14 +409,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const counterB_client = context._lift(counterB); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counterB: ${counterB_client}, + require("./inflight.$Closure2.js")({ + $counterB: ${context._lift(counterB)}, }) `); } @@ -443,9 +430,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(counterB, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(counterB, host, ["peek"]); } @@ -456,14 +440,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const counterC_client = context._lift(counterC); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counterC: ${counterC_client}, + require("./inflight.$Closure3.js")({ + $counterC: ${context._lift(counterC)}, }) `); } @@ -479,9 +461,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(counterC, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(counterC, host, ["peek"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/peek.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/peek.w_compile_tf-aws.md index a15e5d2607b..20240dde4b3 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/peek.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/peek.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ c }) { +module.exports = function({ $c }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 0")})(((await c.peek()) === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 0")})(((await c.peek()) === 0))}; - (await c.inc()); - {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 1")})(((await c.peek()) === 1))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 0")})(((await $c.peek()) === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 0")})(((await $c.peek()) === 0))}; + (await $c.inc()); + {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 1")})(((await $c.peek()) === 1))}; } } return $Closure1; @@ -25,21 +23,19 @@ module.exports = function({ c }) { ## inflight.$Closure2.js ```js -module.exports = function({ c }) { +module.exports = function({ $c }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const key = "my-key"; - {((cond) => {if (!cond) throw new Error("assertion failed: c.peek(key) == 0")})(((await c.peek(key)) === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: c.peek(key) == 0")})(((await c.peek(key)) === 0))}; - (await c.inc(undefined,key)); - {((cond) => {if (!cond) throw new Error("assertion failed: c.peek(key) == 1")})(((await c.peek(key)) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: c.peek(key) == 0")})(((await $c.peek(key)) === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: c.peek(key) == 0")})(((await $c.peek(key)) === 0))}; + (await $c.inc(undefined,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: c.peek(key) == 1")})(((await $c.peek(key)) === 1))}; } } return $Closure2; @@ -270,14 +266,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const c_client = context._lift(c); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c: ${c_client}, + require("./inflight.$Closure1.js")({ + $c: ${context._lift(c)}, }) `); } @@ -293,9 +287,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(c, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(c, host, ["inc", "peek"]); } @@ -306,14 +297,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const c_client = context._lift(c); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c: ${c_client}, + require("./inflight.$Closure2.js")({ + $c: ${context._lift(c)}, }) `); } @@ -329,9 +318,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(c, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(c, host, ["inc", "peek"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/set.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/set.w_compile_tf-aws.md index 851dd54d1d5..e6342f33ffc 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/set.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/counter/set.w_compile_tf-aws.md @@ -2,25 +2,23 @@ ## inflight.$Closure1.js ```js -module.exports = function({ counter }) { +module.exports = function({ $counter }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 0")})(((await counter.peek()) === 0))}; - (await counter.inc()); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 1")})(((await counter.peek()) === 1))}; - (await counter.inc()); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 2")})(((await counter.peek()) === 2))}; - (await counter.inc(10)); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 12")})(((await counter.peek()) === 12))}; - (await counter.set(88)); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 88")})(((await counter.peek()) === 88))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 0")})(((await $counter.peek()) === 0))}; + (await $counter.inc()); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 1")})(((await $counter.peek()) === 1))}; + (await $counter.inc()); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 2")})(((await $counter.peek()) === 2))}; + (await $counter.inc(10)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 12")})(((await $counter.peek()) === 12))}; + (await $counter.set(88)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek() == 88")})(((await $counter.peek()) === 88))}; } } return $Closure1; @@ -30,26 +28,24 @@ module.exports = function({ counter }) { ## inflight.$Closure2.js ```js -module.exports = function({ counter }) { +module.exports = function({ $counter }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const key = "my-key"; - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 0")})(((await counter.peek(key)) === 0))}; - (await counter.inc(undefined,key)); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 1")})(((await counter.peek(key)) === 1))}; - (await counter.inc(undefined,key)); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 2")})(((await counter.peek(key)) === 2))}; - (await counter.inc(10,key)); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 12")})(((await counter.peek(key)) === 12))}; - (await counter.set(88,key)); - {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 88")})(((await counter.peek(key)) === 88))}; + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 0")})(((await $counter.peek(key)) === 0))}; + (await $counter.inc(undefined,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 1")})(((await $counter.peek(key)) === 1))}; + (await $counter.inc(undefined,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 2")})(((await $counter.peek(key)) === 2))}; + (await $counter.inc(10,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 12")})(((await $counter.peek(key)) === 12))}; + (await $counter.set(88,key)); + {((cond) => {if (!cond) throw new Error("assertion failed: counter.peek(key) == 88")})(((await $counter.peek(key)) === 88))}; } } return $Closure2; @@ -280,14 +276,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const counter_client = context._lift(counter); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counter: ${counter_client}, + require("./inflight.$Closure1.js")({ + $counter: ${context._lift(counter)}, }) `); } @@ -303,9 +297,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(counter, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(counter, host, ["inc", "peek", "set"]); } @@ -316,14 +307,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const counter_client = context._lift(counter); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counter: ${counter_client}, + require("./inflight.$Closure2.js")({ + $counter: ${context._lift(counter)}, }) `); } @@ -339,9 +328,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(counter, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(counter, host, ["inc", "peek", "set"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/function/invoke.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/function/invoke.w_compile_tf-aws.md index 914ee3d4024..f9940af0753 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/function/invoke.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/function/invoke.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ util_Util }) { +module.exports = function({ $util_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(input) { - const target = (await util_Util.tryEnv("WING_TARGET")); + async handle(input) { + const target = (await $util_Util.tryEnv("WING_TARGET")); {((cond) => {if (!cond) throw new Error("assertion failed: target?")})(((target) != null))}; return String.raw({ raw: ["", "-response"] }, input); } @@ -24,17 +22,15 @@ module.exports = function({ util_Util }) { ## inflight.$Closure2.js ```js -module.exports = function({ f }) { +module.exports = function({ $f }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const x = (await f.invoke("hello")); + async handle() { + const x = (await $f.invoke("hello")); {((cond) => {if (!cond) throw new Error("assertion failed: x == \"hello-response\"")})((x === "hello-response"))}; } } @@ -247,14 +243,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const util_UtilClient = util.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - util_Util: ${util_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -269,26 +263,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const f_client = context._lift(f); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - f: ${f_client}, + require("./inflight.$Closure2.js")({ + $f: ${context._lift(f)}, }) `); } @@ -304,9 +289,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(f, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(f, host, ["invoke"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/function/memory_and_env.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/function/memory_and_env.w_compile_tf-aws.md index dc6378dd73b..6e6862db6ac 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/function/memory_and_env.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/function/memory_and_env.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ c }) { +module.exports = function({ $c }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await c.inc()); + async handle() { + (await $c.inc()); } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ c }) { ## inflight.$Closure2.js ```js -module.exports = function({ c }) { +module.exports = function({ $c }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await c.inc()); + async handle() { + (await $c.inc()); } } return $Closure2; @@ -42,21 +38,19 @@ module.exports = function({ c }) { ## inflight.$Closure3.js ```js -module.exports = function({ c, f1, f2 }) { +module.exports = function({ $c, $f1, $f2 }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 0")})(((await c.peek()) === 0))}; - (await f1.invoke("")); - {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 1")})(((await c.peek()) === 1))}; - (await f2.invoke("")); - {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 2")})(((await c.peek()) === 2))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 0")})(((await $c.peek()) === 0))}; + (await $f1.invoke("")); + {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 1")})(((await $c.peek()) === 1))}; + (await $f2.invoke("")); + {((cond) => {if (!cond) throw new Error("assertion failed: c.peek() == 2")})(((await $c.peek()) === 2))}; } } return $Closure3; @@ -403,14 +397,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const c_client = context._lift(c); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c: ${c_client}, + require("./inflight.$Closure1.js")({ + $c: ${context._lift(c)}, }) `); } @@ -426,9 +418,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(c, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(c, host, ["inc"]); } @@ -439,14 +428,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const c_client = context._lift(c); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c: ${c_client}, + require("./inflight.$Closure2.js")({ + $c: ${context._lift(c)}, }) `); } @@ -462,9 +449,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(c, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(c, host, ["inc"]); } @@ -475,18 +459,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const c_client = context._lift(c); - const f1_client = context._lift(f1); - const f2_client = context._lift(f2); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c: ${c_client}, - f1: ${f1_client}, - f2: ${f2_client}, + require("./inflight.$Closure3.js")({ + $c: ${context._lift(c)}, + $f1: ${context._lift(f1)}, + $f2: ${context._lift(f2)}, }) `); } @@ -502,11 +482,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(c, host, []); - $Closure3._registerBindObject(f1, host, []); - $Closure3._registerBindObject(f2, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(c, host, ["peek"]); $Closure3._registerBindObject(f1, host, ["invoke"]); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/abs.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/abs.w_compile_tf-aws.md index 789442dfa1d..6249b243f81 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/abs.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/abs.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ x, y, math_Util }) { +module.exports = function({ $math_Util, $x, $y }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.abs(x - y) == 2")})(((await math_Util.abs((x - y))) === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.abs(y - x) == 2")})(((await math_Util.abs((y - x))) === 2))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.abs(x - y) == 2")})(((await $math_Util.abs(($x - $y))) === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.abs(y - x) == 2")})(((await $math_Util.abs(($y - $x))) === 2))}; } } return $Closure1; @@ -157,18 +155,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const x_client = context._lift(x); - const y_client = context._lift(y); - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - x: ${x_client}, - y: ${y_client}, - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, + $x: ${context._lift(x)}, + $y: ${context._lift(y)}, }) `); } @@ -184,10 +178,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(x, host, []); - $Closure1._registerBindObject(y, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(x, host, []); $Closure1._registerBindObject(y, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acos.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acos.w_compile_tf-aws.md index b9d4288c854..060c72cdf03 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acos.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acos.w_compile_tf-aws.md @@ -2,30 +2,28 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { try { - {console.log(String.raw({ raw: ["", ""] }, (await math_Util.acos((-2)))))}; + {console.log(String.raw({ raw: ["", ""] }, (await $math_Util.acos((-2)))))}; } catch ($error_e) { const e = $error_e.message; {((cond) => {if (!cond) throw new Error("assertion failed: e == \"Input value must be between -1 and 1, inclusive.\"")})((e === "Input value must be between -1 and 1, inclusive."))}; } - {((cond) => {if (!cond) throw new Error("assertion failed: math.acos(-1) == math.PI")})(((await math_Util.acos((-1))) === math_Util.PI))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acos(-0) == 1.5707963267948966")})(((await math_Util.acos((-0))) === 1.5707963267948966))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acos(0) == 1.5707963267948966")})(((await math_Util.acos(0)) === 1.5707963267948966))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acos(0.5) == 1.0471975511965979")})(((await math_Util.acos(0.5)) === 1.0471975511965979))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acos(1) == 0")})(((await math_Util.acos(1)) === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acos(-1) == math.PI")})(((await $math_Util.acos((-1))) === $math_Util.PI))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acos(-0) == 1.5707963267948966")})(((await $math_Util.acos((-0))) === 1.5707963267948966))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acos(0) == 1.5707963267948966")})(((await $math_Util.acos(0)) === 1.5707963267948966))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acos(0.5) == 1.0471975511965979")})(((await $math_Util.acos(0.5)) === 1.0471975511965979))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acos(1) == 0")})(((await $math_Util.acos(1)) === 0))}; try { - {console.log(String.raw({ raw: ["", ""] }, (await math_Util.acos(2))))}; + {console.log(String.raw({ raw: ["", ""] }, (await $math_Util.acos(2))))}; } catch ($error_e) { const e = $error_e.message; @@ -174,14 +172,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -196,13 +192,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } try { {console.log(String.raw({ raw: ["", ""] }, (math.Util.acos((-2)))))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acot.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acot.w_compile_tf-aws.md index 321e5cdceee..ce8e5762418 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acot.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acot.w_compile_tf-aws.md @@ -2,21 +2,19 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(0) == 1.5707963267948966")})(((await math_Util.acot(0)) === 1.5707963267948966))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(math.PI / 2) == 0.5669115049410094")})(((await math_Util.acot((math_Util.PI / 2))) === 0.5669115049410094))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(math.PI) == 0.30816907111598496")})(((await math_Util.acot(math_Util.PI)) === 0.30816907111598496))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(math.TAU) == 0.15783119028815887")})(((await math_Util.acot(math_Util.TAU)) === 0.15783119028815887))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(-0) == -1.5707963267948966")})(((await math_Util.acot((-0))) === (-1.5707963267948966)))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(0) == 1.5707963267948966")})(((await $math_Util.acot(0)) === 1.5707963267948966))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(math.PI / 2) == 0.5669115049410094")})(((await $math_Util.acot(($math_Util.PI / 2))) === 0.5669115049410094))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(math.PI) == 0.30816907111598496")})(((await $math_Util.acot($math_Util.PI)) === 0.30816907111598496))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(math.TAU) == 0.15783119028815887")})(((await $math_Util.acot($math_Util.TAU)) === 0.15783119028815887))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(-0) == -1.5707963267948966")})(((await $math_Util.acot((-0))) === (-1.5707963267948966)))}; } } return $Closure1; @@ -160,14 +158,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -182,13 +178,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(0) == 1.5707963267948966")})(((math.Util.acot(0)) === 1.5707963267948966))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.acot(math.PI / 2) == 0.5669115049410094")})(((math.Util.acot((math.Util.PI / 2))) === 0.5669115049410094))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acsc.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acsc.w_compile_tf-aws.md index 6de007c6604..f06125fe7c1 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acsc.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/acsc.w_compile_tf-aws.md @@ -2,28 +2,26 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { try { - {console.log(String.raw({ raw: ["", ""] }, (await math_Util.acsc(0.5))))}; + {console.log(String.raw({ raw: ["", ""] }, (await $math_Util.acsc(0.5))))}; } catch ($error_e) { const e = $error_e.message; {((cond) => {if (!cond) throw new Error("assertion failed: e == \"Input value must be equal or greater than |1|.\"")})((e === "Input value must be equal or greater than |1|."))}; } - {((cond) => {if (!cond) throw new Error("assertion failed: math.acsc(1) == 1.5707963267948966")})(((await math_Util.acsc(1)) === 1.5707963267948966))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acsc(math.PI / 2) == 0.69010709137454")})(((await math_Util.acsc((math_Util.PI / 2))) === 0.69010709137454))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acsc(math.PI) == 0.3239461069319807")})(((await math_Util.acsc(math_Util.PI)) === 0.3239461069319807))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acsc(math.TAU) == 0.15983462638513704")})(((await math_Util.acsc(math_Util.TAU)) === 0.15983462638513704))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.acsc(-1) == -1.5707963267948966")})(((await math_Util.acsc((-1))) === (-1.5707963267948966)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acsc(1) == 1.5707963267948966")})(((await $math_Util.acsc(1)) === 1.5707963267948966))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acsc(math.PI / 2) == 0.69010709137454")})(((await $math_Util.acsc(($math_Util.PI / 2))) === 0.69010709137454))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acsc(math.PI) == 0.3239461069319807")})(((await $math_Util.acsc($math_Util.PI)) === 0.3239461069319807))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acsc(math.TAU) == 0.15983462638513704")})(((await $math_Util.acsc($math_Util.TAU)) === 0.15983462638513704))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.acsc(-1) == -1.5707963267948966")})(((await $math_Util.acsc((-1))) === (-1.5707963267948966)))}; } } return $Closure1; @@ -167,14 +165,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -189,13 +185,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } try { {console.log(String.raw({ raw: ["", ""] }, (math.Util.acsc(0.5))))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/angular_conversion.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/angular_conversion.w_compile_tf-aws.md index 27a700e4a2d..f389277a868 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/angular_conversion.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/angular_conversion.w_compile_tf-aws.md @@ -2,28 +2,26 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(360) == math.TAU")})(((await math_Util.degreesToRadians(360)) === math_Util.TAU))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(180) == math.PI")})(((await math_Util.degreesToRadians(180)) === math_Util.PI))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(90) == math.PI / 2")})(((await math_Util.degreesToRadians(90)) === (math_Util.PI / 2)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(60) == math.PI / 3")})(((await math_Util.degreesToRadians(60)) === (math_Util.PI / 3)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(45) == math.PI / 4")})(((await math_Util.degreesToRadians(45)) === (math_Util.PI / 4)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(30) == math.PI / 6")})(((await math_Util.degreesToRadians(30)) === (math_Util.PI / 6)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.radiansToDegrees(math.TAU) == 360")})(((await math_Util.radiansToDegrees(math_Util.TAU)) === 360))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.radiansToDegrees(math.PI) == 180")})(((await math_Util.radiansToDegrees(math_Util.PI)) === 180))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.radiansToDegrees(math.PI / 2) == 90")})(((await math_Util.radiansToDegrees((math_Util.PI / 2))) === 90))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.radiansToDegrees(math.PI / 3)) == 60")})(((await math_Util.round((await math_Util.radiansToDegrees((math_Util.PI / 3))))) === 60))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.radiansToDegrees(math.PI / 4) == 45")})(((await math_Util.radiansToDegrees((math_Util.PI / 4))) === 45))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.radiansToDegrees(math.PI / 6)) == 30")})(((await math_Util.round((await math_Util.radiansToDegrees((math_Util.PI / 6))))) === 30))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(360) == math.TAU")})(((await $math_Util.degreesToRadians(360)) === $math_Util.TAU))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(180) == math.PI")})(((await $math_Util.degreesToRadians(180)) === $math_Util.PI))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(90) == math.PI / 2")})(((await $math_Util.degreesToRadians(90)) === ($math_Util.PI / 2)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(60) == math.PI / 3")})(((await $math_Util.degreesToRadians(60)) === ($math_Util.PI / 3)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(45) == math.PI / 4")})(((await $math_Util.degreesToRadians(45)) === ($math_Util.PI / 4)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(30) == math.PI / 6")})(((await $math_Util.degreesToRadians(30)) === ($math_Util.PI / 6)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.radiansToDegrees(math.TAU) == 360")})(((await $math_Util.radiansToDegrees($math_Util.TAU)) === 360))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.radiansToDegrees(math.PI) == 180")})(((await $math_Util.radiansToDegrees($math_Util.PI)) === 180))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.radiansToDegrees(math.PI / 2) == 90")})(((await $math_Util.radiansToDegrees(($math_Util.PI / 2))) === 90))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.radiansToDegrees(math.PI / 3)) == 60")})(((await $math_Util.round((await $math_Util.radiansToDegrees(($math_Util.PI / 3))))) === 60))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.radiansToDegrees(math.PI / 4) == 45")})(((await $math_Util.radiansToDegrees(($math_Util.PI / 4))) === 45))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.radiansToDegrees(math.PI / 6)) == 30")})(((await $math_Util.round((await $math_Util.radiansToDegrees(($math_Util.PI / 6))))) === 30))}; } } return $Closure1; @@ -167,14 +165,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -189,13 +185,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(360) == math.TAU")})(((math.Util.degreesToRadians(360)) === math.Util.TAU))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.degreesToRadians(180) == math.PI")})(((math.Util.degreesToRadians(180)) === math.Util.PI))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/asec.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/asec.w_compile_tf-aws.md index 1ec4e6218d5..5db66292e19 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/asec.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/asec.w_compile_tf-aws.md @@ -2,29 +2,27 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { try { - {console.log(String.raw({ raw: ["", ""] }, (await math_Util.asec(0.5))))}; + {console.log(String.raw({ raw: ["", ""] }, (await $math_Util.asec(0.5))))}; } catch ($error_e) { const e = $error_e.message; {((cond) => {if (!cond) throw new Error("assertion failed: e == \"Input value must be equal or greater than |1|.\"")})((e === "Input value must be equal or greater than |1|."))}; } - {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(2) == 1.0471975511965979")})(((await math_Util.asec(2)) === 1.0471975511965979))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(1) == 0")})(((await math_Util.asec(1)) === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(math.PI) == 1.2468502198629159")})(((await math_Util.asec(math_Util.PI)) === 1.2468502198629159))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(-math.PI) == 1.8947424337268775")})(((await math_Util.asec((-math_Util.PI))) === 1.8947424337268775))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(-1) == math.PI")})(((await math_Util.asec((-1))) === math_Util.PI))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(-2) == 2.0943951023931957")})(((await math_Util.asec((-2))) === 2.0943951023931957))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(2) == 1.0471975511965979")})(((await $math_Util.asec(2)) === 1.0471975511965979))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(1) == 0")})(((await $math_Util.asec(1)) === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(math.PI) == 1.2468502198629159")})(((await $math_Util.asec($math_Util.PI)) === 1.2468502198629159))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(-math.PI) == 1.8947424337268775")})(((await $math_Util.asec((-$math_Util.PI))) === 1.8947424337268775))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(-1) == math.PI")})(((await $math_Util.asec((-1))) === $math_Util.PI))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asec(-2) == 2.0943951023931957")})(((await $math_Util.asec((-2))) === 2.0943951023931957))}; } } return $Closure1; @@ -168,14 +166,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -190,13 +186,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } try { {console.log(String.raw({ raw: ["", ""] }, (math.Util.asec(0.5))))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/asin.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/asin.w_compile_tf-aws.md index d6eadee6fe3..6293723c087 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/asin.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/asin.w_compile_tf-aws.md @@ -2,30 +2,28 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { try { - {console.log(String.raw({ raw: ["", ""] }, (await math_Util.asin((-2)))))}; + {console.log(String.raw({ raw: ["", ""] }, (await $math_Util.asin((-2)))))}; } catch ($error_e) { const e = $error_e.message; {((cond) => {if (!cond) throw new Error("assertion failed: e == \"Input value must be between -1 and 1, inclusive.\"")})((e === "Input value must be between -1 and 1, inclusive."))}; } - {((cond) => {if (!cond) throw new Error("assertion failed: math.asin(-1) == -1.5707963267948966")})(((await math_Util.asin((-1))) === (-1.5707963267948966)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.asin(-0) == -0")})(((await math_Util.asin((-0))) === (-0)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.asin(0) == 0")})(((await math_Util.asin(0)) === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.asin(0.5) == 0.5235987755982989")})(((await math_Util.asin(0.5)) === 0.5235987755982989))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.asin(1) == 1.5707963267948966")})(((await math_Util.asin(1)) === 1.5707963267948966))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asin(-1) == -1.5707963267948966")})(((await $math_Util.asin((-1))) === (-1.5707963267948966)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asin(-0) == -0")})(((await $math_Util.asin((-0))) === (-0)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asin(0) == 0")})(((await $math_Util.asin(0)) === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asin(0.5) == 0.5235987755982989")})(((await $math_Util.asin(0.5)) === 0.5235987755982989))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.asin(1) == 1.5707963267948966")})(((await $math_Util.asin(1)) === 1.5707963267948966))}; try { - {console.log(String.raw({ raw: ["", ""] }, (await math_Util.asin(2))))}; + {console.log(String.raw({ raw: ["", ""] }, (await $math_Util.asin(2))))}; } catch ($error_e) { const e = $error_e.message; @@ -174,14 +172,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -196,13 +192,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } try { {console.log(String.raw({ raw: ["", ""] }, (math.Util.asin((-2)))))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/atan.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/atan.w_compile_tf-aws.md index aa5c81b04f2..2069c8968f2 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/atan.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/atan.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.atan(-1) == -0.7853981633974483")})(((await math_Util.atan((-1))) === (-0.7853981633974483)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.atan(-0) == -0")})(((await math_Util.atan((-0))) === (-0)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.atan(0) == 0")})(((await math_Util.atan(0)) === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.atan(1) == 0.7853981633974483")})(((await math_Util.atan(1)) === 0.7853981633974483))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.atan(-1) == -0.7853981633974483")})(((await $math_Util.atan((-1))) === (-0.7853981633974483)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.atan(-0) == -0")})(((await $math_Util.atan((-0))) === (-0)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.atan(0) == 0")})(((await $math_Util.atan(0)) === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.atan(1) == 0.7853981633974483")})(((await $math_Util.atan(1)) === 0.7853981633974483))}; } } return $Closure1; @@ -159,14 +157,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -181,13 +177,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.atan(-1) == -0.7853981633974483")})(((math.Util.atan((-1))) === (-0.7853981633974483)))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.atan(-0) == -0")})(((math.Util.atan((-0))) === (-0)))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/combinations.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/combinations.w_compile_tf-aws.md index 7286c255e18..d88909f6a1b 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/combinations.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/combinations.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ population, subset, math_Util }) { +module.exports = function({ $math_Util, $population, $subset }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.combinations(population, subset) == 10")})(((await math_Util.combinations(population,subset)) === 10))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.combinations(population, subset) == 10")})(((await $math_Util.combinations($population,$subset)) === 10))}; } } return $Closure1; @@ -156,18 +154,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const population_client = context._lift(population); - const subset_client = context._lift(subset); - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - population: ${population_client}, - subset: ${subset_client}, - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, + $population: ${context._lift(population)}, + $subset: ${context._lift(subset)}, }) `); } @@ -183,10 +177,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(population, host, []); - $Closure1._registerBindObject(subset, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(population, host, []); $Closure1._registerBindObject(subset, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/cos.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/cos.w_compile_tf-aws.md index 8979f6cab20..9eb6deb9e2a 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/cos.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/cos.w_compile_tf-aws.md @@ -2,22 +2,20 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(-0) == 1")})(((await math_Util.cos((-0))) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(0) == 1")})(((await math_Util.cos(0)) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(1) == 0.5403023058681398")})(((await math_Util.cos(1)) === 0.5403023058681398))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(-5) == 0.28366218546322625")})(((await math_Util.cos((-5))) === 0.28366218546322625))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(math.PI) == -1")})(((await math_Util.cos(math_Util.PI)) === (-1)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(math.PI * 2) == 1")})(((await math_Util.cos((math_Util.PI * 2))) === 1))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(-0) == 1")})(((await $math_Util.cos((-0))) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(0) == 1")})(((await $math_Util.cos(0)) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(1) == 0.5403023058681398")})(((await $math_Util.cos(1)) === 0.5403023058681398))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(-5) == 0.28366218546322625")})(((await $math_Util.cos((-5))) === 0.28366218546322625))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(math.PI) == -1")})(((await $math_Util.cos($math_Util.PI)) === (-1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(math.PI * 2) == 1")})(((await $math_Util.cos(($math_Util.PI * 2))) === 1))}; } } return $Closure1; @@ -161,14 +159,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -183,13 +179,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(-0) == 1")})(((math.Util.cos((-0))) === 1))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.cos(0) == 1")})(((math.Util.cos(0)) === 1))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/cot.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/cot.w_compile_tf-aws.md index e167bd37884..c30e0fb5ff5 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/cot.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/cot.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.cot(0) == math.INF")})(((await math_Util.cot(0)) === math_Util.INF))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.cot(math.PI / 4)) == 1")})(((await math_Util.round((await math_Util.cot((math_Util.PI / 4))))) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.cot(math.PI * 3 / 4)) == -1")})(((await math_Util.round((await math_Util.cot(((math_Util.PI * 3) / 4))))) === (-1)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.cot(-0) == -math.INF")})(((await math_Util.cot((-0))) === (-math_Util.INF)))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.cot(0) == math.INF")})(((await $math_Util.cot(0)) === $math_Util.INF))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.cot(math.PI / 4)) == 1")})(((await $math_Util.round((await $math_Util.cot(($math_Util.PI / 4))))) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.cot(math.PI * 3 / 4)) == -1")})(((await $math_Util.round((await $math_Util.cot((($math_Util.PI * 3) / 4))))) === (-1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.cot(-0) == -math.INF")})(((await $math_Util.cot((-0))) === (-$math_Util.INF)))}; } } return $Closure1; @@ -159,14 +157,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -181,13 +177,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.cot(0) == math.INF")})(((math.Util.cot(0)) === math.Util.INF))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.cot(math.PI / 4)) == 1")})(((math.Util.round((math.Util.cot((math.Util.PI / 4))))) === 1))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/csc.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/csc.w_compile_tf-aws.md index 9855f77648c..bb02b85d5ea 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/csc.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/csc.w_compile_tf-aws.md @@ -2,24 +2,22 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(-0) == -math.INF")})(((await math_Util.csc((-0))) === (-math_Util.INF)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(0) == math.INF")})(((await math_Util.csc(0)) === math_Util.INF))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(1) == 1.1883951057781212")})(((await math_Util.csc(1)) === 1.1883951057781212))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(-5) == 1.0428352127714058")})(((await math_Util.csc((-5))) === 1.0428352127714058))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(math.PI / 2) == 1")})(((await math_Util.csc((math_Util.PI / 2))) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(math.TAU / 4) == 1")})(((await math_Util.csc((math_Util.TAU / 4))) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(math.PI * 3 / 2) == -1")})(((await math_Util.csc(((math_Util.PI * 3) / 2))) === (-1)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(math.TAU * 3 / 4) == -1")})(((await math_Util.csc(((math_Util.TAU * 3) / 4))) === (-1)))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(-0) == -math.INF")})(((await $math_Util.csc((-0))) === (-$math_Util.INF)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(0) == math.INF")})(((await $math_Util.csc(0)) === $math_Util.INF))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(1) == 1.1883951057781212")})(((await $math_Util.csc(1)) === 1.1883951057781212))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(-5) == 1.0428352127714058")})(((await $math_Util.csc((-5))) === 1.0428352127714058))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(math.PI / 2) == 1")})(((await $math_Util.csc(($math_Util.PI / 2))) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(math.TAU / 4) == 1")})(((await $math_Util.csc(($math_Util.TAU / 4))) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(math.PI * 3 / 2) == -1")})(((await $math_Util.csc((($math_Util.PI * 3) / 2))) === (-1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(math.TAU * 3 / 4) == -1")})(((await $math_Util.csc((($math_Util.TAU * 3) / 4))) === (-1)))}; } } return $Closure1; @@ -163,14 +161,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -185,13 +181,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(-0) == -math.INF")})(((math.Util.csc((-0))) === (-math.Util.INF)))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.csc(0) == math.INF")})(((math.Util.csc(0)) === math.Util.INF))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/euler.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/euler.w_compile_tf-aws.md index b16d691e5b3..c6c0b532665 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/euler.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/euler.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(interestRate, currentVal) { - return (currentVal * (math_Util.E ** interestRate)); + async handle(interestRate, currentVal) { + return (currentVal * ($math_Util.E ** interestRate)); } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ math_Util }) { ## inflight.$Closure2.js ```js -module.exports = function({ compoundOneYear, interest, value, math_Util }) { +module.exports = function({ $compoundOneYear, $interest, $math_Util, $value }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(compoundOneYear(interest, value), decimalPlaces: 2) == 105.13")})(((await math_Util.round((await compoundOneYear(interest,value)),{ decimalPlaces: 2 })) === 105.13))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(compoundOneYear(interest, value), decimalPlaces: 2) == 105.13")})(((await $math_Util.round((await $compoundOneYear($interest,$value)),{ decimalPlaces: 2 })) === 105.13))}; } } return $Closure2; @@ -176,14 +172,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -198,32 +192,20 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const compoundOneYear_client = context._lift(compoundOneYear); - const interest_client = context._lift(interest); - const value_client = context._lift(value); - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - compoundOneYear: ${compoundOneYear_client}, - interest: ${interest_client}, - value: ${value_client}, - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure2.js")({ + $compoundOneYear: ${context._lift(compoundOneYear)}, + $interest: ${context._lift(interest)}, + $math_Util: ${context._lift(math.Util)}, + $value: ${context._lift(value)}, }) `); } @@ -239,11 +221,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(compoundOneYear, host, []); - $Closure2._registerBindObject(interest, host, []); - $Closure2._registerBindObject(value, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(compoundOneYear, host, ["handle"]); $Closure2._registerBindObject(interest, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/factorial.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/factorial.w_compile_tf-aws.md index 77add02d771..35a2bfe682f 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/factorial.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/factorial.w_compile_tf-aws.md @@ -2,22 +2,20 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(0) == 1")})(((await math_Util.factorial(0)) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(1) == 1")})(((await math_Util.factorial(1)) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(2) == 2")})(((await math_Util.factorial(2)) === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(3) == 6")})(((await math_Util.factorial(3)) === 6))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(4) == 24")})(((await math_Util.factorial(4)) === 24))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(5) == 120")})(((await math_Util.factorial(5)) === 120))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(0) == 1")})(((await $math_Util.factorial(0)) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(1) == 1")})(((await $math_Util.factorial(1)) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(2) == 2")})(((await $math_Util.factorial(2)) === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(3) == 6")})(((await $math_Util.factorial(3)) === 6))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(4) == 24")})(((await $math_Util.factorial(4)) === 24))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(5) == 120")})(((await $math_Util.factorial(5)) === 120))}; } } return $Closure1; @@ -161,14 +159,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -183,13 +179,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(0) == 1")})(((math.Util.factorial(0)) === 1))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.factorial(1) == 1")})(((math.Util.factorial(1)) === 1))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/fibonacci.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/fibonacci.w_compile_tf-aws.md index e8d58e67bee..325e22a2d65 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/fibonacci.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/fibonacci.w_compile_tf-aws.md @@ -2,27 +2,25 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(0) == 0")})(((await math_Util.fibonacci(0)) === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(1) == 1")})(((await math_Util.fibonacci(1)) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(2) == 1")})(((await math_Util.fibonacci(2)) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(3) == 2")})(((await math_Util.fibonacci(3)) === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(4) == 3")})(((await math_Util.fibonacci(4)) === 3))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(5) == 5")})(((await math_Util.fibonacci(5)) === 5))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(6) == 8")})(((await math_Util.fibonacci(6)) === 8))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(7) == 13")})(((await math_Util.fibonacci(7)) === 13))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(8) == 21")})(((await math_Util.fibonacci(8)) === 21))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(9) == 34")})(((await math_Util.fibonacci(9)) === 34))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(10) == 55")})(((await math_Util.fibonacci(10)) === 55))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(0) == 0")})(((await $math_Util.fibonacci(0)) === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(1) == 1")})(((await $math_Util.fibonacci(1)) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(2) == 1")})(((await $math_Util.fibonacci(2)) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(3) == 2")})(((await $math_Util.fibonacci(3)) === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(4) == 3")})(((await $math_Util.fibonacci(4)) === 3))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(5) == 5")})(((await $math_Util.fibonacci(5)) === 5))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(6) == 8")})(((await $math_Util.fibonacci(6)) === 8))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(7) == 13")})(((await $math_Util.fibonacci(7)) === 13))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(8) == 21")})(((await $math_Util.fibonacci(8)) === 21))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(9) == 34")})(((await $math_Util.fibonacci(9)) === 34))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(10) == 55")})(((await $math_Util.fibonacci(10)) === 55))}; } } return $Closure1; @@ -166,14 +164,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -188,13 +184,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(0) == 0")})(((math.Util.fibonacci(0)) === 0))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.fibonacci(1) == 1")})(((math.Util.fibonacci(1)) === 1))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/floor_ceil_round.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/floor_ceil_round.w_compile_tf-aws.md index ad3f420a458..4d003de9d53 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/floor_ceil_round.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/floor_ceil_round.w_compile_tf-aws.md @@ -2,27 +2,25 @@ ## inflight.$Closure1.js ```js -module.exports = function({ x, y, math_Util }) { +module.exports = function({ $__x_, $__y_, $math_Util, $x, $y }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.floor(x) == 5")})(((await math_Util.floor(x)) === 5))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.ceil(x) == 6")})(((await math_Util.ceil(x)) === 6))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(x) == 5")})(((await math_Util.round(x)) === 5))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(y) == 6")})(((await math_Util.round(y)) === 6))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(-x) == -5")})(((await math_Util.round((-x))) === (-5)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(-y) == -6")})(((await math_Util.round((-y))) === (-6)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.E, decimalPlaces: 1) == 2.7")})(((await math_Util.round(math_Util.E,{ decimalPlaces: 1 })) === 2.7))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.E, decimalPlaces: 2) == 2.72")})(((await math_Util.round(math_Util.E,{ decimalPlaces: 2 })) === 2.72))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.E, decimalPlaces: 3) == 2.718")})(((await math_Util.round(math_Util.E,{ decimalPlaces: 3 })) === 2.718))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.E, decimalPlaces: 4) == 2.7183")})(((await math_Util.round(math_Util.E,{ decimalPlaces: 4 })) === 2.7183))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.E, decimalPlaces: 5) == 2.71828")})(((await math_Util.round(math_Util.E,{ decimalPlaces: 5 })) === 2.71828))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.floor(x) == 5")})(((await $math_Util.floor($x)) === 5))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.ceil(x) == 6")})(((await $math_Util.ceil($x)) === 6))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(x) == 5")})(((await $math_Util.round($x)) === 5))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(y) == 6")})(((await $math_Util.round($y)) === 6))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(-x) == -5")})(((await $math_Util.round($__x_)) === (-5)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(-y) == -6")})(((await $math_Util.round($__y_)) === (-6)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.E, decimalPlaces: 1) == 2.7")})(((await $math_Util.round($math_Util.E,{ decimalPlaces: 1 })) === 2.7))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.E, decimalPlaces: 2) == 2.72")})(((await $math_Util.round($math_Util.E,{ decimalPlaces: 2 })) === 2.72))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.E, decimalPlaces: 3) == 2.718")})(((await $math_Util.round($math_Util.E,{ decimalPlaces: 3 })) === 2.718))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.E, decimalPlaces: 4) == 2.7183")})(((await $math_Util.round($math_Util.E,{ decimalPlaces: 4 })) === 2.7183))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.E, decimalPlaces: 5) == 2.71828")})(((await $math_Util.round($math_Util.E,{ decimalPlaces: 5 })) === 2.71828))}; } } return $Closure1; @@ -166,18 +164,16 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const x_client = context._lift(x); - const y_client = context._lift(y); - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - x: ${x_client}, - y: ${y_client}, - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $__x_: ${context._lift((-x))}, + $__y_: ${context._lift((-y))}, + $math_Util: ${context._lift(math.Util)}, + $x: ${context._lift(x)}, + $y: ${context._lift(y)}, }) `); } @@ -193,11 +189,9 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(x, host, []); - $Closure1._registerBindObject(y, host, []); - } if (ops.includes("handle")) { + $Closure1._registerBindObject((-x), host, []); + $Closure1._registerBindObject((-y), host, []); $Closure1._registerBindObject(x, host, []); $Closure1._registerBindObject(y, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/hypot.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/hypot.w_compile_tf-aws.md index da4d1dbb449..47f73d9aa8e 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/hypot.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/hypot.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.hypot([3, 4]) == 5")})(((await math_Util.hypot(Object.freeze([3, 4]))) === 5))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.hypot([5, 12]) == 13")})(((await math_Util.hypot(Object.freeze([5, 12]))) === 13))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.hypot([3, 4, 5]), decimalPlaces: 2) == 7.07")})(((await math_Util.round((await math_Util.hypot(Object.freeze([3, 4, 5]))),{ decimalPlaces: 2 })) === 7.07))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.hypot([-5]) == 5")})(((await math_Util.hypot(Object.freeze([(-5)]))) === 5))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.hypot([3, 4]) == 5")})(((await $math_Util.hypot(Object.freeze([3, 4]))) === 5))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.hypot([5, 12]) == 13")})(((await $math_Util.hypot(Object.freeze([5, 12]))) === 13))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(math.hypot([3, 4, 5]), decimalPlaces: 2) == 7.07")})(((await $math_Util.round((await $math_Util.hypot(Object.freeze([3, 4, 5]))),{ decimalPlaces: 2 })) === 7.07))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.hypot([-5]) == 5")})(((await $math_Util.hypot(Object.freeze([(-5)]))) === 5))}; } } return $Closure1; @@ -159,14 +157,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -181,13 +177,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.hypot([3, 4]) == 5")})(((math.Util.hypot(Object.freeze([3, 4]))) === 5))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.hypot([5, 12]) == 13")})(((math.Util.hypot(Object.freeze([5, 12]))) === 13))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/median_mode_mean.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/median_mode_mean.w_compile_tf-aws.md index 35ce4dbb0e5..dfbe54d064b 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/median_mode_mean.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/median_mode_mean.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ odd_arr, even_arr, math_Util }) { +module.exports = function({ $even_arr, $math_Util, $odd_arr }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.median(odd_arr) == 6")})(((await math_Util.median(odd_arr)) === 6))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.median(even_arr) == 4.5")})(((await math_Util.median(even_arr)) === 4.5))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.median(odd_arr) == 6")})(((await $math_Util.median($odd_arr)) === 6))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.median(even_arr) == 4.5")})(((await $math_Util.median($even_arr)) === 4.5))}; } } return $Closure1; @@ -23,22 +21,20 @@ module.exports = function({ odd_arr, even_arr, math_Util }) { ## inflight.$Closure2.js ```js -module.exports = function({ modal_arr, bimodal, multimodal, math_Util }) { +module.exports = function({ $_bimodal_at_0__, $_bimodal_at_1__, $_multimodal_at_0__, $_multimodal_at_1__, $_multimodal_at_2__, $math_Util, $modal_arr }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.mode(modal_arr).at(0) == 2")})(((await (await math_Util.mode(modal_arr)).at(0)) === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: bimodal.at(0) == 2")})(((await bimodal.at(0)) === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: bimodal.at(1) == 7")})(((await bimodal.at(1)) === 7))}; - {((cond) => {if (!cond) throw new Error("assertion failed: multimodal.at(0) == 2")})(((await multimodal.at(0)) === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: multimodal.at(1) == 7")})(((await multimodal.at(1)) === 7))}; - {((cond) => {if (!cond) throw new Error("assertion failed: multimodal.at(2) == 9")})(((await multimodal.at(2)) === 9))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.mode(modal_arr).at(0) == 2")})(((await (await $math_Util.mode($modal_arr)).at(0)) === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: bimodal.at(0) == 2")})(($_bimodal_at_0__ === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: bimodal.at(1) == 7")})(($_bimodal_at_1__ === 7))}; + {((cond) => {if (!cond) throw new Error("assertion failed: multimodal.at(0) == 2")})(($_multimodal_at_0__ === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: multimodal.at(1) == 7")})(($_multimodal_at_1__ === 7))}; + {((cond) => {if (!cond) throw new Error("assertion failed: multimodal.at(2) == 9")})(($_multimodal_at_2__ === 9))}; } } return $Closure2; @@ -48,19 +44,17 @@ module.exports = function({ modal_arr, bimodal, multimodal, math_Util }) { ## inflight.$Closure3.js ```js -module.exports = function({ mean_arr, math_Util }) { +module.exports = function({ $math_Util, $mean_arr }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.arithmeticMean(mean_arr) == 42")})(((await math_Util.arithmeticMean(mean_arr)) === 42))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.geometricMean(mean_arr) == 30")})(((await math_Util.geometricMean(mean_arr)) === 30))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.harmonicMean(mean_arr) == 15")})(((await math_Util.harmonicMean(mean_arr)) === 15))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.arithmeticMean(mean_arr) == 42")})(((await $math_Util.arithmeticMean($mean_arr)) === 42))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.geometricMean(mean_arr) == 30")})(((await $math_Util.geometricMean($mean_arr)) === 30))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.harmonicMean(mean_arr) == 15")})(((await $math_Util.harmonicMean($mean_arr)) === 15))}; } } return $Closure3; @@ -336,18 +330,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const odd_arr_client = context._lift(odd_arr); - const even_arr_client = context._lift(even_arr); - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - odd_arr: ${odd_arr_client}, - even_arr: ${even_arr_client}, - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $even_arr: ${context._lift(even_arr)}, + $math_Util: ${context._lift(math.Util)}, + $odd_arr: ${context._lift(odd_arr)}, }) `); } @@ -363,10 +353,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(even_arr, host, []); - $Closure1._registerBindObject(odd_arr, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(even_arr, host, []); $Closure1._registerBindObject(odd_arr, host, []); @@ -378,20 +364,18 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const modal_arr_client = context._lift(modal_arr); - const bimodal_client = context._lift(bimodal); - const multimodal_client = context._lift(multimodal); - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - modal_arr: ${modal_arr_client}, - bimodal: ${bimodal_client}, - multimodal: ${multimodal_client}, - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure2.js")({ + $_bimodal_at_0__: ${context._lift((bimodal.at(0)))}, + $_bimodal_at_1__: ${context._lift((bimodal.at(1)))}, + $_multimodal_at_0__: ${context._lift((multimodal.at(0)))}, + $_multimodal_at_1__: ${context._lift((multimodal.at(1)))}, + $_multimodal_at_2__: ${context._lift((multimodal.at(2)))}, + $math_Util: ${context._lift(math.Util)}, + $modal_arr: ${context._lift(modal_arr)}, }) `); } @@ -407,15 +391,13 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(bimodal, host, []); - $Closure2._registerBindObject(modal_arr, host, []); - $Closure2._registerBindObject(multimodal, host, []); - } if (ops.includes("handle")) { - $Closure2._registerBindObject(bimodal, host, ["at"]); - $Closure2._registerBindObject(modal_arr, host, []); - $Closure2._registerBindObject(multimodal, host, ["at"]); + $Closure2._registerBindObject((bimodal.at(0)), host, []); + $Closure2._registerBindObject((bimodal.at(1)), host, []); + $Closure2._registerBindObject((multimodal.at(0)), host, []); + $Closure2._registerBindObject((multimodal.at(1)), host, []); + $Closure2._registerBindObject((multimodal.at(2)), host, []); + $Closure2._registerBindObject(modal_arr, host, ["at"]); } super._registerBind(host, ops); } @@ -424,16 +406,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const mean_arr_client = context._lift(mean_arr); - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - mean_arr: ${mean_arr_client}, - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure3.js")({ + $math_Util: ${context._lift(math.Util)}, + $mean_arr: ${context._lift(mean_arr)}, }) `); } @@ -449,9 +428,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(mean_arr, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(mean_arr, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/min_max.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/min_max.w_compile_tf-aws.md index 86b699ebf29..9c6e619a216 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/min_max.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/min_max.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ myArray, math_Util }) { +module.exports = function({ $math_Util, $myArray }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.min(myArray) == 1")})(((await math_Util.min(myArray)) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.max(myArray) == 5")})(((await math_Util.max(myArray)) === 5))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.min(myArray) == 1")})(((await $math_Util.min($myArray)) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.max(myArray) == 5")})(((await $math_Util.max($myArray)) === 5))}; } } return $Closure1; @@ -157,16 +155,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const myArray_client = context._lift(myArray); - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - myArray: ${myArray_client}, - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, + $myArray: ${context._lift(myArray)}, }) `); } @@ -182,9 +177,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(myArray, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(myArray, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/pi.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/pi.w_compile_tf-aws.md index bc74cd0b3be..284ab80e515 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/pi.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/pi.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(radius) { - return ((2 * math_Util.PI) * radius); + async handle(radius) { + return ((2 * $math_Util.PI) * radius); } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ math_Util }) { ## inflight.$Closure2.js ```js -module.exports = function({ circumference, r, math_Util }) { +module.exports = function({ $circumference, $math_Util, $r }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.round(circumference(r), decimalPlaces: 2) == 62.83")})(((await math_Util.round((await circumference(r)),{ decimalPlaces: 2 })) === 62.83))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.round(circumference(r), decimalPlaces: 2) == 62.83")})(((await $math_Util.round((await $circumference($r)),{ decimalPlaces: 2 })) === 62.83))}; } } return $Closure2; @@ -176,14 +172,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -198,30 +192,19 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const circumference_client = context._lift(circumference); - const r_client = context._lift(r); - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - circumference: ${circumference_client}, - r: ${r_client}, - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure2.js")({ + $circumference: ${context._lift(circumference)}, + $math_Util: ${context._lift(math.Util)}, + $r: ${context._lift(r)}, }) `); } @@ -237,10 +220,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(circumference, host, []); - $Closure2._registerBindObject(r, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(circumference, host, ["handle"]); $Closure2._registerBindObject(r, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/prime.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/prime.w_compile_tf-aws.md index 00c15a4b871..0c866dc95a8 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/prime.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/prime.w_compile_tf-aws.md @@ -2,23 +2,21 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(1) == false")})(((await math_Util.isPrime(1)) === false))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(2) == true")})(((await math_Util.isPrime(2)) === true))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(3) == true")})(((await math_Util.isPrime(3)) === true))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(4) == false")})(((await math_Util.isPrime(4)) === false))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(10) == false")})(((await math_Util.isPrime(10)) === false))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(11) == true")})(((await math_Util.isPrime(11)) === true))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(12) == false")})(((await math_Util.isPrime(12)) === false))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(1) == false")})(((await $math_Util.isPrime(1)) === false))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(2) == true")})(((await $math_Util.isPrime(2)) === true))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(3) == true")})(((await $math_Util.isPrime(3)) === true))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(4) == false")})(((await $math_Util.isPrime(4)) === false))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(10) == false")})(((await $math_Util.isPrime(10)) === false))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(11) == true")})(((await $math_Util.isPrime(11)) === true))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(12) == false")})(((await $math_Util.isPrime(12)) === false))}; } } return $Closure1; @@ -162,14 +160,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -184,13 +180,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(1) == false")})(((math.Util.isPrime(1)) === false))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.isPrime(2) == true")})(((math.Util.isPrime(2)) === true))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/sec.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/sec.w_compile_tf-aws.md index 4f806a94e80..4ac6b4aace5 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/sec.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/sec.w_compile_tf-aws.md @@ -2,22 +2,20 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(-0) == 1")})(((await math_Util.sec((-0))) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(0) == 1")})(((await math_Util.sec(0)) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(1) == 1.8508157176809255")})(((await math_Util.sec(1)) === 1.8508157176809255))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(-5) == 3.5253200858160887")})(((await math_Util.sec((-5))) === 3.5253200858160887))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(math.PI) == -1")})(((await math_Util.sec(math_Util.PI)) === (-1)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(math.TAU) == 1")})(((await math_Util.sec(math_Util.TAU)) === 1))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(-0) == 1")})(((await $math_Util.sec((-0))) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(0) == 1")})(((await $math_Util.sec(0)) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(1) == 1.8508157176809255")})(((await $math_Util.sec(1)) === 1.8508157176809255))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(-5) == 3.5253200858160887")})(((await $math_Util.sec((-5))) === 3.5253200858160887))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(math.PI) == -1")})(((await $math_Util.sec($math_Util.PI)) === (-1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(math.TAU) == 1")})(((await $math_Util.sec($math_Util.TAU)) === 1))}; } } return $Closure1; @@ -161,14 +159,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -183,13 +179,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(-0) == 1")})(((math.Util.sec((-0))) === 1))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.sec(0) == 1")})(((math.Util.sec(0)) === 1))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/sin.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/sin.w_compile_tf-aws.md index 2bc87612cf0..2619e48b3e8 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/sin.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/sin.w_compile_tf-aws.md @@ -2,21 +2,19 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(-0) == -0")})(((await math_Util.sin((-0))) === (-0)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(0) == 0")})(((await math_Util.sin(0)) === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(1) == 0.8414709848078965")})(((await math_Util.sin(1)) === 0.8414709848078965))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(-5) == 0.9589242746631385")})(((await math_Util.sin((-5))) === 0.9589242746631385))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(math.PI / 2) == 1")})(((await math_Util.sin((math_Util.PI / 2))) === 1))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(-0) == -0")})(((await $math_Util.sin((-0))) === (-0)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(0) == 0")})(((await $math_Util.sin(0)) === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(1) == 0.8414709848078965")})(((await $math_Util.sin(1)) === 0.8414709848078965))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(-5) == 0.9589242746631385")})(((await $math_Util.sin((-5))) === 0.9589242746631385))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(math.PI / 2) == 1")})(((await $math_Util.sin(($math_Util.PI / 2))) === 1))}; } } return $Closure1; @@ -160,14 +158,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -182,13 +178,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(-0) == -0")})(((math.Util.sin((-0))) === (-0)))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.sin(0) == 0")})(((math.Util.sin(0)) === 0))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/tan.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/tan.w_compile_tf-aws.md index 38c4c434430..e5d667e1b98 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/tan.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/tan.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.tan(-0) == -0")})(((await math_Util.tan((-0))) === (-0)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.tan(0) == 0")})(((await math_Util.tan(0)) === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.tan(1) == 1.5574077246549023")})(((await math_Util.tan(1)) === 1.5574077246549023))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.tan(math.PI / 4) == 0.9999999999999999")})(((await math_Util.tan((math_Util.PI / 4))) === 0.9999999999999999))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.tan(-0) == -0")})(((await $math_Util.tan((-0))) === (-0)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.tan(0) == 0")})(((await $math_Util.tan(0)) === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.tan(1) == 1.5574077246549023")})(((await $math_Util.tan(1)) === 1.5574077246549023))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.tan(math.PI / 4) == 0.9999999999999999")})(((await $math_Util.tan(($math_Util.PI / 4))) === 0.9999999999999999))}; } } return $Closure1; @@ -159,14 +157,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -181,13 +177,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.tan(-0) == -0")})(((math.Util.tan((-0))) === (-0)))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.tan(0) == 0")})(((math.Util.tan(0)) === 0))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/tau.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/tau.w_compile_tf-aws.md index 115a0969288..c1d63939243 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/tau.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/math/tau.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ math_Util }) { +module.exports = function({ $math_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: math.TAU / 4 == math.PI / 2")})(((math_Util.TAU / 4) === (math_Util.PI / 2)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.TAU / 2 == math.PI")})(((math_Util.TAU / 2) === math_Util.PI))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.TAU * 3 / 4 == math.PI * 3 / 2")})((((math_Util.TAU * 3) / 4) === ((math_Util.PI * 3) / 2)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: math.TAU == math.PI * 2")})((math_Util.TAU === (math_Util.PI * 2)))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: math.TAU / 4 == math.PI / 2")})((($math_Util.TAU / 4) === ($math_Util.PI / 2)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.TAU / 2 == math.PI")})((($math_Util.TAU / 2) === $math_Util.PI))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.TAU * 3 / 4 == math.PI * 3 / 2")})(((($math_Util.TAU * 3) / 4) === (($math_Util.PI * 3) / 2)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: math.TAU == math.PI * 2")})(($math_Util.TAU === ($math_Util.PI * 2)))}; } } return $Closure1; @@ -159,14 +157,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const math_UtilClient = math.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - math_Util: ${math_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $math_Util: ${context._lift(math.Util)}, }) `); } @@ -181,13 +177,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: math.TAU / 4 == math.PI / 2")})(((math.Util.TAU / 4) === (math.Util.PI / 2)))}; {((cond) => {if (!cond) throw new Error("assertion failed: math.TAU / 2 == math.PI")})(((math.Util.TAU / 2) === math.Util.PI))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/pop.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/pop.w_compile_tf-aws.md index 6142dcb31c1..a83e00c90ae 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/pop.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/pop.w_compile_tf-aws.md @@ -2,26 +2,24 @@ ## inflight.$Closure1.js ```js -module.exports = function({ q, NIL }) { +module.exports = function({ $NIL, $q }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const msgs = Object.freeze(["Foo", "Bar"]); for (const msg of msgs) { - (await q.push(msg)); + (await $q.push(msg)); } - const first = ((await q.pop()) ?? NIL); - const second = ((await q.pop()) ?? NIL); - const third = ((await q.pop()) ?? NIL); + const first = ((await $q.pop()) ?? $NIL); + const second = ((await $q.pop()) ?? $NIL); + const third = ((await $q.pop()) ?? $NIL); {((cond) => {if (!cond) throw new Error("assertion failed: msgs.contains(first)")})(msgs.includes(first))}; {((cond) => {if (!cond) throw new Error("assertion failed: msgs.contains(second)")})(msgs.includes(second))}; - {((cond) => {if (!cond) throw new Error("assertion failed: third == NIL")})((third === NIL))}; + {((cond) => {if (!cond) throw new Error("assertion failed: third == NIL")})((third === $NIL))}; } } return $Closure1; @@ -177,16 +175,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const q_client = context._lift(q); - const NIL_client = context._lift(NIL); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - q: ${q_client}, - NIL: ${NIL_client}, + require("./inflight.$Closure1.js")({ + $NIL: ${context._lift(NIL)}, + $q: ${context._lift(q)}, }) `); } @@ -202,10 +197,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(NIL, host, []); - $Closure1._registerBindObject(q, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(NIL, host, []); $Closure1._registerBindObject(q, host, ["pop", "push"]); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/purge.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/purge.w_compile_tf-aws.md index 46a5cc9ac16..ee12e32fb59 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/purge.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/purge.w_compile_tf-aws.md @@ -2,38 +2,36 @@ ## inflight.$Closure1.js ```js -module.exports = function({ q, js }) { +module.exports = function({ $js, $q }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await q.push("foo")); - (await q.push("bar")); - (await q.push("baz")); - const wait = async (pred) => { + async handle() { + (await $q.push("foo")); + (await $q.push("bar")); + (await $q.push("baz")); + const wait = async (pred) => { let i = 0; while ((i < 60)) { if ((await pred())) { return true; } - (await js.sleep(100)); + (await $js.sleep(100)); i = (i + 1); } return false; } ; - {((cond) => {if (!cond) throw new Error("assertion failed: wait(inflight (): bool => { \n return q.approxSize() == 3;\n })")})((await wait(async () => { - return ((await q.approxSize()) === 3); + {((cond) => {if (!cond) throw new Error("assertion failed: wait(inflight (): bool => { \n return q.approxSize() == 3;\n })")})((await wait(async () => { + return ((await $q.approxSize()) === 3); } )))}; - (await q.purge()); - {((cond) => {if (!cond) throw new Error("assertion failed: wait(inflight (): bool => {\n return q.approxSize() == 0;\n })")})((await wait(async () => { - return ((await q.approxSize()) === 0); + (await $q.purge()); + {((cond) => {if (!cond) throw new Error("assertion failed: wait(inflight (): bool => {\n return q.approxSize() == 0;\n })")})((await wait(async () => { + return ((await $q.approxSize()) === 0); } )))}; } @@ -49,9 +47,7 @@ module.exports = function({ }) { class TestHelper { constructor({ }) { } - async $inflight_init() { - } - async sleep(milli) { + async sleep(milli) { return (require("/sleep.js")["sleep"])(milli) } } @@ -207,12 +203,11 @@ class $Root extends $stdlib.std.Resource { class TestHelper extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("sleep"); + this._addInflightOps("sleep", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.TestHelper.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.TestHelper.js")({ }) `); } @@ -227,28 +222,18 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("sleep")) { - } - super._registerBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const q_client = context._lift(q); - const js_client = context._lift(js); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - q: ${q_client}, - js: ${js_client}, + require("./inflight.$Closure1.js")({ + $js: ${context._lift(js)}, + $q: ${context._lift(q)}, }) `); } @@ -264,10 +249,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(js, host, []); - $Closure1._registerBindObject(q, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(js, host, ["sleep"]); $Closure1._registerBindObject(q, host, ["approxSize", "purge", "push"]); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/set_consumer.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/set_consumer.w_compile_tf-aws.md index f18ef2f32ef..f391350012b 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/set_consumer.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/queue/set_consumer.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ c }) { +module.exports = function({ $c }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(msg) { - (await c.inc()); + async handle(msg) { + (await $c.inc()); } } return $Closure1; @@ -22,28 +20,26 @@ module.exports = function({ c }) { ## inflight.$Closure2.js ```js -module.exports = function({ q, predicate, js }) { +module.exports = function({ $js, $predicate, $q }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await q.push("hello")); - (await q.push("world")); + async handle() { + (await $q.push("hello")); + (await $q.push("world")); let i = 0; while ((i < 600)) { i = (i + 1); - if ((await predicate.test())) { - {((cond) => {if (!cond) throw new Error("assertion failed: predicate.test()")})((await predicate.test()))}; + if ((await $predicate.test())) { + {((cond) => {if (!cond) throw new Error("assertion failed: predicate.test()")})((await $predicate.test()))}; return; } - (await js.sleep(100)); + (await $js.sleep(100)); } - {((cond) => {if (!cond) throw new Error("assertion failed: predicate.test()")})((await predicate.test()))}; + {((cond) => {if (!cond) throw new Error("assertion failed: predicate.test()")})((await $predicate.test()))}; } } return $Closure2; @@ -55,13 +51,11 @@ module.exports = function({ q, predicate, js }) { ```js module.exports = function({ }) { class Predicate { - constructor({ c }) { - this.c = c; - } - async $inflight_init() { + constructor({ $this_c }) { + this.$this_c = $this_c; } - async test() { - return ((await this.c.peek()) === 2); + async test() { + return ((await this.$this_c.peek()) === 2); } } return Predicate; @@ -75,9 +69,7 @@ module.exports = function({ }) { class TestHelper { constructor({ }) { } - async $inflight_init() { - } - async sleep(milli) { + async sleep(milli) { return (require("/sleep.js")["sleep"])(milli) } } @@ -334,22 +326,20 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, c) { super(scope, id); this.c = c; - this._addInflightOps("test"); + this._addInflightOps("test", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Predicate.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Predicate.js")({ }) `); } _toInflight() { - const c_client = this._lift(this.c); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const PredicateClient = ${Predicate._toInflightType(this).text}; const client = new PredicateClient({ - c: ${c_client}, + $this_c: ${this._lift(this.c)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -357,9 +347,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Predicate._registerBindObject(this.c, host, []); - } if (ops.includes("test")) { Predicate._registerBindObject(this.c, host, ["peek"]); } @@ -369,12 +356,11 @@ class $Root extends $stdlib.std.Resource { class TestHelper extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("sleep"); + this._addInflightOps("sleep", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.TestHelper.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.TestHelper.js")({ }) `); } @@ -389,26 +375,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("sleep")) { - } - super._registerBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const c_client = context._lift(c); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c: ${c_client}, + require("./inflight.$Closure1.js")({ + $c: ${context._lift(c)}, }) `); } @@ -424,9 +401,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(c, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(c, host, ["inc"]); } @@ -437,18 +411,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const q_client = context._lift(q); - const predicate_client = context._lift(predicate); - const js_client = context._lift(js); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - q: ${q_client}, - predicate: ${predicate_client}, - js: ${js_client}, + require("./inflight.$Closure2.js")({ + $js: ${context._lift(js)}, + $predicate: ${context._lift(predicate)}, + $q: ${context._lift(q)}, }) `); } @@ -464,11 +434,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(js, host, []); - $Closure2._registerBindObject(predicate, host, []); - $Closure2._registerBindObject(q, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(js, host, ["sleep"]); $Closure2._registerBindObject(predicate, host, ["test"]); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/schedule/on_tick.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/schedule/on_tick.w_compile_tf-aws.md index 2dc249f9ff0..6c581e9a29b 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/schedule/on_tick.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/schedule/on_tick.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ c1 }) { +module.exports = function({ $c1 }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await c1.inc()); + async handle() { + (await $c1.inc()); } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ c1 }) { ## inflight.$Closure2.js ```js -module.exports = function({ c2 }) { +module.exports = function({ $c2 }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await c2.inc()); + async handle() { + (await $c2.inc()); } } return $Closure2; @@ -42,21 +38,19 @@ module.exports = function({ c2 }) { ## inflight.$Closure3.js ```js -module.exports = function({ c1, c2, Utils }) { +module.exports = function({ $Utils, $c1, $c2 }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: c1.peek() == 0")})(((await c1.peek()) === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: c2.peek() == 0")})(((await c2.peek()) === 0))}; - (await Utils.sleep(((60 * 1000) * 1.1))); - {((cond) => {if (!cond) throw new Error("assertion failed: c1.peek() >= 1")})(((await c1.peek()) >= 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: c2.peek() >= 1")})(((await c2.peek()) >= 1))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: c1.peek() == 0")})(((await $c1.peek()) === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: c2.peek() == 0")})(((await $c2.peek()) === 0))}; + (await $Utils.sleep(((60 * 1000) * 1.1))); + {((cond) => {if (!cond) throw new Error("assertion failed: c1.peek() >= 1")})(((await $c1.peek()) >= 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: c2.peek() >= 1")})(((await $c2.peek()) >= 1))}; } } return $Closure3; @@ -70,9 +64,7 @@ module.exports = function({ }) { class Utils { constructor({ }) { } - async $inflight_init() { - } - static async sleep(milli) { + static async sleep(milli) { return (require("/sleep.js")["sleep"])(milli) } } @@ -461,14 +453,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const c1_client = context._lift(c1); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c1: ${c1_client}, + require("./inflight.$Closure1.js")({ + $c1: ${context._lift(c1)}, }) `); } @@ -484,9 +474,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(c1, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(c1, host, ["inc"]); } @@ -497,14 +484,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const c2_client = context._lift(c2); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c2: ${c2_client}, + require("./inflight.$Closure2.js")({ + $c2: ${context._lift(c2)}, }) `); } @@ -520,9 +505,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(c2, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(c2, host, ["inc"]); } @@ -532,12 +514,11 @@ class $Root extends $stdlib.std.Resource { class Utils extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("sleep"); + this._addInflightOps("sleep", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Utils.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Utils.js")({ }) `); } @@ -552,33 +533,19 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } - static _registerTypeBind(host, ops) { - if (ops.includes("sleep")) { - } - super._registerTypeBind(host, ops); - } } class $Closure3 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const c1_client = context._lift(c1); - const c2_client = context._lift(c2); - const UtilsClient = Utils._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c1: ${c1_client}, - c2: ${c2_client}, - Utils: ${UtilsClient.text}, + require("./inflight.$Closure3.js")({ + $Utils: ${context._lift(Utils)}, + $c1: ${context._lift(c1)}, + $c2: ${context._lift(c2)}, }) `); } @@ -594,10 +561,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(c1, host, []); - $Closure3._registerBindObject(c2, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(Utils, host, ["sleep"]); $Closure3._registerBindObject(c1, host, ["peek"]); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/array.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/array.w_compile_tf-aws.md index fef7fdd2da6..562805421ff 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/array.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/array.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: [\"hello\"].length == 1")})((Object.freeze(["hello"]).length === 1))}; {((cond) => {if (!cond) throw new Error("assertion failed: MutArray[\"hello\"].length == 1")})((["hello"].length === 1))}; } @@ -30,9 +28,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const i = ["hello", "wing"]; const separator = ","; const joinedString = (await i.join()); @@ -54,9 +50,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const o = ["hello", "wing"]; const p = Object.freeze([...(o)]); {((cond) => {if (!cond) throw new Error("assertion failed: o.length == p.length")})((o.length === p.length))}; @@ -77,9 +71,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const q = Object.freeze(["hello", "wing"]); const r = [...(q)]; {((cond) => {if (!cond) throw new Error("assertion failed: q.length == r.length")})((q.length === r.length))}; @@ -100,9 +92,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const lastStr = "wing"; const s = ["hello", lastStr, lastStr]; {((cond) => {if (!cond) throw new Error("assertion failed: s.lastIndexOf(lastStr) == 2")})((s.lastIndexOf(lastStr) === 2))}; @@ -123,9 +113,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: [\"hello\"].at(0) == \"hello\"")})(((await Object.freeze(["hello"]).at(0)) === "hello"))}; {((cond) => {if (!cond) throw new Error("assertion failed: MutArray[\"hello\", \"world\"].at(1) == \"world\"")})(((await ["hello", "world"].at(1)) === "world"))}; } @@ -144,9 +132,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const a = ["hello"]; {((cond) => {if (!cond) throw new Error("assertion failed: a.length == 1")})((a.length === 1))}; (await a.push("world")); @@ -173,9 +159,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const b = ["hello"]; {((cond) => {if (!cond) throw new Error("assertion failed: b.length == 1")})((b.length === 1))}; const d = (await b.concat(["wing"])); @@ -198,9 +182,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const array = Object.freeze(["hello"]); {((cond) => {if (!cond) throw new Error("assertion failed: array.length == 1")})((array.length === 1))}; const anotherArray = Object.freeze(["wing"]); @@ -225,9 +207,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const e = ["hello", "wing"]; {((cond) => {if (!cond) throw new Error("assertion failed: e.contains(\"wing\")")})(e.includes("wing"))}; {((cond) => {if (!cond) throw new Error("assertion failed: !e.contains(\"NotThere\")")})((!e.includes("NotThere")))}; @@ -250,9 +230,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const g = ["hello", "wing"]; {((cond) => {if (!cond) throw new Error("assertion failed: g.indexOf(\"wing\") == 1")})((g.indexOf("wing") === 1))}; {((cond) => {if (!cond) throw new Error("assertion failed: g.indexOf(\"notThere\") == -1")})((g.indexOf("notThere") === (-1)))}; @@ -272,9 +250,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const g = Object.freeze(["hello", "wing"]); {((cond) => {if (!cond) throw new Error("assertion failed: g.indexOf(\"wing\") == 1")})((g.indexOf("wing") === 1))}; {((cond) => {if (!cond) throw new Error("assertion failed: g.indexOf(\"notThere\") == -1")})((g.indexOf("notThere") === (-1)))}; @@ -294,9 +270,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const i = ["hello", "wing"]; const separator = ";"; const joinedString = (await i.join(separator)); @@ -1358,12 +1332,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -1378,24 +1351,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure2.js")({ }) `); } @@ -1410,24 +1375,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure3 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure3.js")({ }) `); } @@ -1442,24 +1399,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure4 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure4.js")({ }) `); } @@ -1474,24 +1423,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure5 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure5.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure5.js")({ }) `); } @@ -1506,24 +1447,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure6 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure6.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure6.js")({ }) `); } @@ -1538,24 +1471,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure7 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure7.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure7.js")({ }) `); } @@ -1570,24 +1495,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure8 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure8.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure8.js")({ }) `); } @@ -1602,24 +1519,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure9 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure9.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure9.js")({ }) `); } @@ -1634,24 +1543,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure10 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure10.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure10.js")({ }) `); } @@ -1666,24 +1567,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure11 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure11.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure11.js")({ }) `); } @@ -1698,24 +1591,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure12 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure12.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure12.js")({ }) `); } @@ -1730,24 +1615,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure13 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure13.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure13.js")({ }) `); } @@ -1762,13 +1639,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } const bucket = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"myBucket"); const buckets = Object.freeze([bucket]); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/bool.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/bool.w_compile_tf-aws.md index a19b6be7f89..3857eb2248e 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/bool.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/bool.w_compile_tf-aws.md @@ -2,26 +2,24 @@ ## inflight.$Closure1.js ```js -module.exports = function({ PARSE_ERROR, std_Boolean, std_Json }) { +module.exports = function({ $PARSE_ERROR, $std_Boolean, $std_Json }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const t = (await std_Boolean.fromJson((JSON.parse("true")))); + async handle() { + const t = (await $std_Boolean.fromJson((JSON.parse("true")))); {((cond) => {if (!cond) throw new Error("assertion failed: t == true")})((t === true))}; - const f = (await std_Boolean.fromJson((JSON.parse("false")))); + const f = (await $std_Boolean.fromJson((JSON.parse("false")))); {((cond) => {if (!cond) throw new Error("assertion failed: f == false")})((f === false))}; try { - (await std_Boolean.fromJson(123)); + (await $std_Boolean.fromJson(123)); } catch ($error_s) { const s = $error_s.message; - {((cond) => {if (!cond) throw new Error("assertion failed: s == PARSE_ERROR")})((s === PARSE_ERROR))}; + {((cond) => {if (!cond) throw new Error("assertion failed: s == PARSE_ERROR")})((s === $PARSE_ERROR))}; } } } @@ -165,18 +163,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const PARSE_ERROR_client = context._lift(PARSE_ERROR); - const std_BooleanClient = std.Boolean._toInflightType(context); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - PARSE_ERROR: ${PARSE_ERROR_client}, - std_Boolean: ${std_BooleanClient.text}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $PARSE_ERROR: ${context._lift(PARSE_ERROR)}, + $std_Boolean: ${context._lift(std.Boolean)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -192,16 +186,13 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(PARSE_ERROR, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(PARSE_ERROR, host, []); } super._registerBind(host, ops); } } - const assertThrows = (expected, block) => { + const assertThrows = ((expected, block) => { let error = false; try { (block()); @@ -212,15 +203,13 @@ class $Root extends $stdlib.std.Resource { error = true; } {((cond) => {if (!cond) throw new Error("assertion failed: error")})(error)}; - } - ; + }); const PARSE_ERROR = "unable to parse number 123 as a boolean"; const t = (std.Boolean.fromJson((JSON.parse("true")))); {((cond) => {if (!cond) throw new Error("assertion failed: t == true")})((t === true))}; - (assertThrows(PARSE_ERROR, () => { + (assertThrows(PARSE_ERROR,(() => { (std.Boolean.fromJson(123)); - } - )); + }))); const f = (std.Boolean.fromJson((JSON.parse("false")))); {((cond) => {if (!cond) throw new Error("assertion failed: f == false")})((f === false))}; this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:fromJson()",new $Closure1(this,"$Closure1")); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/duration.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/duration.w_compile_tf-aws.md index bbb7d3a160b..07d812e96ee 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/duration.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/duration.w_compile_tf-aws.md @@ -2,36 +2,34 @@ ## inflight.$Closure1.js ```js -module.exports = function({ std_Duration }) { +module.exports = function({ $std_Duration }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: 12ms.seconds == 12 / 1000")})(((await std_Duration.fromSeconds(0.012)).seconds === (12 / 1000)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 12s.seconds == 12")})(((await std_Duration.fromSeconds(12)).seconds === 12))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 12m.seconds == 12 * 60")})(((await std_Duration.fromSeconds(720)).seconds === (12 * 60)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 12h.seconds == 12 * 60 * 60")})(((await std_Duration.fromSeconds(43200)).seconds === ((12 * 60) * 60)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 12d.seconds == 12 * 60 * 60 * 24")})(((await std_Duration.fromSeconds(1036800)).seconds === (((12 * 60) * 60) * 24)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 12mo.seconds == (12 * 60 * 60 * 24 * 365) / 12")})(((await std_Duration.fromSeconds(31536000)).seconds === (((((12 * 60) * 60) * 24) * 365) / 12)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 12y.seconds == 12 * 60 * 60 * 24 * 365")})(((await std_Duration.fromSeconds(378432000)).seconds === ((((12 * 60) * 60) * 24) * 365)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromMilliseconds(10).seconds == 10ms.seconds")})(((await std_Duration.fromMilliseconds(10)).seconds === (await std_Duration.fromSeconds(0.01)).seconds))}; - {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromMinutes(10).seconds == 10m.seconds")})(((await std_Duration.fromMinutes(10)).seconds === (await std_Duration.fromSeconds(600)).seconds))}; - {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromSeconds(10).seconds == 10s.seconds")})(((await std_Duration.fromSeconds(10)).seconds === (await std_Duration.fromSeconds(10)).seconds))}; - {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromHours(10).seconds == 10h.seconds")})(((await std_Duration.fromHours(10)).seconds === (await std_Duration.fromSeconds(36000)).seconds))}; - {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromDays(10).seconds == 10d.seconds")})(((await std_Duration.fromDays(10)).seconds === (await std_Duration.fromSeconds(864000)).seconds))}; - {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromMonths(10).seconds == 10mo.seconds")})(((await std_Duration.fromMonths(10)).seconds === (await std_Duration.fromSeconds(26280000)).seconds))}; - {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromYears(10).seconds == 10y.seconds")})(((await std_Duration.fromYears(10)).seconds === (await std_Duration.fromSeconds(315360000)).seconds))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 1s.milliseconds == 1000")})(((await std_Duration.fromSeconds(1)).milliseconds === 1000))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 1s.minutes == 1 / 60")})(((await std_Duration.fromSeconds(1)).minutes === (1 / 60)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 1s.hours == 1 / (60 * 60)")})(((await std_Duration.fromSeconds(1)).hours === (1 / (60 * 60))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 1s.days == 1 / (60 * 60 * 24)")})(((await std_Duration.fromSeconds(1)).days === (1 / ((60 * 60) * 24))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 1s.months == 1 / ((60 * 60 * 24 * 365) / 12)")})(((await std_Duration.fromSeconds(1)).months === (1 / ((((60 * 60) * 24) * 365) / 12))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 1s.years == 1 / (60 * 60 * 24 * 365)")})(((await std_Duration.fromSeconds(1)).years === (1 / (((60 * 60) * 24) * 365))))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: 12ms.seconds == 12 / 1000")})(((await $std_Duration.fromSeconds(0.012)).seconds === (12 / 1000)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 12s.seconds == 12")})(((await $std_Duration.fromSeconds(12)).seconds === 12))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 12m.seconds == 12 * 60")})(((await $std_Duration.fromSeconds(720)).seconds === (12 * 60)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 12h.seconds == 12 * 60 * 60")})(((await $std_Duration.fromSeconds(43200)).seconds === ((12 * 60) * 60)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 12d.seconds == 12 * 60 * 60 * 24")})(((await $std_Duration.fromSeconds(1036800)).seconds === (((12 * 60) * 60) * 24)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 12mo.seconds == (12 * 60 * 60 * 24 * 365) / 12")})(((await $std_Duration.fromSeconds(31536000)).seconds === (((((12 * 60) * 60) * 24) * 365) / 12)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 12y.seconds == 12 * 60 * 60 * 24 * 365")})(((await $std_Duration.fromSeconds(378432000)).seconds === ((((12 * 60) * 60) * 24) * 365)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromMilliseconds(10).seconds == 10ms.seconds")})(((await $std_Duration.fromMilliseconds(10)).seconds === (await $std_Duration.fromSeconds(0.01)).seconds))}; + {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromMinutes(10).seconds == 10m.seconds")})(((await $std_Duration.fromMinutes(10)).seconds === (await $std_Duration.fromSeconds(600)).seconds))}; + {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromSeconds(10).seconds == 10s.seconds")})(((await $std_Duration.fromSeconds(10)).seconds === (await $std_Duration.fromSeconds(10)).seconds))}; + {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromHours(10).seconds == 10h.seconds")})(((await $std_Duration.fromHours(10)).seconds === (await $std_Duration.fromSeconds(36000)).seconds))}; + {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromDays(10).seconds == 10d.seconds")})(((await $std_Duration.fromDays(10)).seconds === (await $std_Duration.fromSeconds(864000)).seconds))}; + {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromMonths(10).seconds == 10mo.seconds")})(((await $std_Duration.fromMonths(10)).seconds === (await $std_Duration.fromSeconds(26280000)).seconds))}; + {((cond) => {if (!cond) throw new Error("assertion failed: duration.fromYears(10).seconds == 10y.seconds")})(((await $std_Duration.fromYears(10)).seconds === (await $std_Duration.fromSeconds(315360000)).seconds))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 1s.milliseconds == 1000")})(((await $std_Duration.fromSeconds(1)).milliseconds === 1000))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 1s.minutes == 1 / 60")})(((await $std_Duration.fromSeconds(1)).minutes === (1 / 60)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 1s.hours == 1 / (60 * 60)")})(((await $std_Duration.fromSeconds(1)).hours === (1 / (60 * 60))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 1s.days == 1 / (60 * 60 * 24)")})(((await $std_Duration.fromSeconds(1)).days === (1 / ((60 * 60) * 24))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 1s.months == 1 / ((60 * 60 * 24 * 365) / 12)")})(((await $std_Duration.fromSeconds(1)).months === (1 / ((((60 * 60) * 24) * 365) / 12))))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 1s.years == 1 / (60 * 60 * 24 * 365)")})(((await $std_Duration.fromSeconds(1)).years === (1 / (((60 * 60) * 24) * 365))))}; } } return $Closure1; @@ -174,14 +172,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const std_DurationClient = std.Duration._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - std_Duration: ${std_DurationClient.text}, + require("./inflight.$Closure1.js")({ + $std_Duration: ${context._lift(std.Duration)}, }) `); } @@ -196,13 +192,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: 12ms.seconds == 12 / 1000")})(((std.Duration.fromSeconds(0.012)).seconds === (12 / 1000)))}; {((cond) => {if (!cond) throw new Error("assertion failed: 12s.seconds == 12")})(((std.Duration.fromSeconds(12)).seconds === 12))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/json.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/json.w_compile_tf-aws.md index 0b1750b941f..bd9545fafc3 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/json.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/json.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const x = {"a":1}; ((obj, args) => { obj[args[0]] = args[1]; })(x, ["b",2]); const y = (x)["b"]; @@ -32,9 +30,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const x = {"a":1}; const a = {"c":3}; ((obj, args) => { obj[args[0]] = args[1]; })(x, [2,a]); @@ -249,12 +245,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -269,24 +264,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure2.js")({ }) `); } @@ -301,13 +288,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } const a = {"a":1}; const b = {"b":2}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/number.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/number.w_compile_tf-aws.md index cfccc99a286..311f4b7e115 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/number.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/number.w_compile_tf-aws.md @@ -2,16 +2,14 @@ ## inflight.$Closure1.js ```js -module.exports = function({ std_Number }) { +module.exports = function({ $std_Number }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: num.fromJson(Json 123) == 123")})((((args) => { if (typeof args !== "number") {throw new Error("unable to parse " + typeof args + " " + args + " as a number")}; return JSON.parse(JSON.stringify(args)) })(123) === 123))}; } } @@ -22,16 +20,14 @@ module.exports = function({ std_Number }) { ## inflight.$Closure2.js ```js -module.exports = function({ std_Number }) { +module.exports = function({ $std_Number }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: num.fromStr(\"888\") == 888")})((((args) => { if (isNaN(args)) {throw new Error("unable to parse \"" + args + "\" as a number")}; return parseInt(args) })("888") === 888))}; } } @@ -241,14 +237,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const std_NumberClient = std.Number._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - std_Number: ${std_NumberClient.text}, + require("./inflight.$Closure1.js")({ + $std_Number: ${context._lift(std.Number)}, }) `); } @@ -263,26 +257,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const std_NumberClient = std.Number._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - std_Number: ${std_NumberClient.text}, + require("./inflight.$Closure2.js")({ + $std_Number: ${context._lift(std.Number)}, }) `); } @@ -297,13 +282,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {((cond) => {if (!cond) throw new Error("assertion failed: num.fromJson(Json 12) == 12")})((((args) => { if (typeof args !== "number") {throw new Error("unable to parse " + typeof args + " " + args + " as a number")}; return JSON.parse(JSON.stringify(args)) })(12) === 12))}; this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:fromJson",new $Closure1(this,"$Closure1")); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/string.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/string.w_compile_tf-aws.md index 6ef01635321..cc7fa9460fd 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/string.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/std/string.w_compile_tf-aws.md @@ -2,23 +2,21 @@ ## inflight.$Closure1.js ```js -module.exports = function({ PARSE_ERROR, std_String }) { +module.exports = function({ $PARSE_ERROR, $std_String }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: str.fromJson(Json \"World\") == \"World\"")})((((args) => { if (typeof args !== "string") {throw new Error("unable to parse " + typeof args + " " + args + " as a string")}; return JSON.parse(JSON.stringify(args)) })("World") === "World"))}; try { ((args) => { if (typeof args !== "string") {throw new Error("unable to parse " + typeof args + " " + args + " as a string")}; return JSON.parse(JSON.stringify(args)) })(123); } catch ($error_s) { const s = $error_s.message; - {((cond) => {if (!cond) throw new Error("assertion failed: s == PARSE_ERROR")})((s === PARSE_ERROR))}; + {((cond) => {if (!cond) throw new Error("assertion failed: s == PARSE_ERROR")})((s === $PARSE_ERROR))}; } } } @@ -36,9 +34,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"hello wing\".startsWith(\"h\")")})("hello wing".startsWith("h"))}; {((cond) => {if (!cond) throw new Error("assertion failed: !\"hello wing\".startsWith(\"H\")")})((!"hello wing".startsWith("H")))}; {((cond) => {if (!cond) throw new Error("assertion failed: !\"hello wing\".startsWith(\"w\")")})((!"hello wing".startsWith("w")))}; @@ -58,9 +54,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"hello wing\".substring(0, 5) == \"hello\"")})(((await "hello wing".substring(0,5)) === "hello"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"hello wing\".substring(0, 100) == \"hello wing\"")})(((await "hello wing".substring(0,100)) === "hello wing"))}; } @@ -79,9 +73,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"hello wing \".trim() == \"hello wing\"")})(((await "hello wing ".trim()) === "hello wing"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"hello wing\".trim() == \"hello wing\"")})(((await "hello wing".trim()) === "hello wing"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"\".trim() == \"\"")})(((await "".trim()) === ""))}; @@ -102,9 +94,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"hello wing\".contains(\"hello\")")})("hello wing".includes("hello"))}; {((cond) => {if (!cond) throw new Error("assertion failed: !\"hello wing\".contains(\"Hello\")")})((!"hello wing".includes("Hello")))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"hello wing\".contains(\"w\")")})("hello wing".includes("w"))}; @@ -124,9 +114,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"hello\".length == 5")})(("hello".length === 5))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"\".length == 0")})(("".length === 0))}; } @@ -145,9 +133,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"boom\".at(0) == \"b\"")})(((await "boom".at(0)) === "b"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"boom\".at(-4) == \"b\"")})(((await "boom".at((-4))) === "b"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"boom\".at(-1) == \"m\"")})(((await "boom".at((-1))) === "m"))}; @@ -167,9 +153,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"boom\".concat(\"boom\") == \"boomboom\"")})(((await "boom".concat("boom")) === "boomboom"))}; } } @@ -187,9 +171,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"boom\".endsWith(\"m\")")})("boom".endsWith("m"))}; {((cond) => {if (!cond) throw new Error("assertion failed: !\"boom\".endsWith(\"b\")")})((!"boom".endsWith("b")))}; } @@ -208,9 +190,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"boom\".indexOf(\"m\") == 3")})(("boom".indexOf("m") === 3))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"boom\".indexOf(\"a\") == -1")})(("boom".indexOf("a") === (-1)))}; } @@ -229,9 +209,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"BOOM\".lowercase() == \"boom\"")})(("BOOM".toLocaleLowerCase() === "boom"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"BooM\".lowercase() == \"boom\"")})(("BooM".toLocaleLowerCase() === "boom"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"boom\".lowercase() == \"boom\"")})(("boom".toLocaleLowerCase() === "boom"))}; @@ -252,9 +230,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"BOOM\".uppercase() == \"BOOM\"")})(("BOOM".toLocaleUpperCase() === "BOOM"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"BooM\".uppercase() == \"BOOM\"")})(("BooM".toLocaleUpperCase() === "BOOM"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"boom\".uppercase() == \"BOOM\"")})(("boom".toLocaleUpperCase() === "BOOM"))}; @@ -275,9 +251,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"hello;wing\".split(\";\").at(0) == \"hello\"")})(((await (await "hello;wing".split(";")).at(0)) === "hello"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"hello;wing\".split(\";\").at(1) == \"wing\"")})(((await (await "hello;wing".split(";")).at(1)) === "wing"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"hello wing\".split(\" \").at(0) == \"hello\"")})(((await (await "hello wing".split(" ")).at(0)) === "hello"))}; @@ -1219,16 +1193,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const PARSE_ERROR_client = context._lift(PARSE_ERROR); - const std_StringClient = std.String._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - PARSE_ERROR: ${PARSE_ERROR_client}, - std_String: ${std_StringClient.text}, + require("./inflight.$Closure1.js")({ + $PARSE_ERROR: ${context._lift(PARSE_ERROR)}, + $std_String: ${context._lift(std.String)}, }) `); } @@ -1244,9 +1215,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(PARSE_ERROR, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(PARSE_ERROR, host, []); } @@ -1257,12 +1225,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure2.js")({ }) `); } @@ -1277,24 +1244,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure3 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure3.js")({ }) `); } @@ -1309,24 +1268,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure4 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure4.js")({ }) `); } @@ -1341,24 +1292,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure5 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure5.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure5.js")({ }) `); } @@ -1373,24 +1316,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure6 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure6.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure6.js")({ }) `); } @@ -1405,24 +1340,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure7 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure7.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure7.js")({ }) `); } @@ -1437,24 +1364,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure8 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure8.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure8.js")({ }) `); } @@ -1469,24 +1388,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure9 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure9.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure9.js")({ }) `); } @@ -1501,24 +1412,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure10 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure10.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure10.js")({ }) `); } @@ -1533,24 +1436,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure11 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure11.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure11.js")({ }) `); } @@ -1565,24 +1460,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure12 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure12.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure12.js")({ }) `); } @@ -1597,24 +1484,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure13 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure13.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure13.js")({ }) `); } @@ -1629,15 +1508,8 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } - const assertThrows = (expected, block) => { + const assertThrows = ((expected, block) => { let error = false; try { (block()); @@ -1648,14 +1520,12 @@ class $Root extends $stdlib.std.Resource { error = true; } {((cond) => {if (!cond) throw new Error("assertion failed: error")})(error)}; - } - ; + }); const PARSE_ERROR = "unable to parse number 123 as a string"; {((cond) => {if (!cond) throw new Error("assertion failed: str.fromJson(Json \"Hello\") == \"Hello\"")})((((args) => { if (typeof args !== "string") {throw new Error("unable to parse " + typeof args + " " + args + " as a string")}; return JSON.parse(JSON.stringify(args)) })("Hello") === "Hello"))}; - (assertThrows(PARSE_ERROR, () => { + (assertThrows(PARSE_ERROR,(() => { ((args) => { if (typeof args !== "string") {throw new Error("unable to parse " + typeof args + " " + args + " as a string")}; return JSON.parse(JSON.stringify(args)) })(123); - } - )); + }))); this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:fromJson",new $Closure1(this,"$Closure1")); {((cond) => {if (!cond) throw new Error("assertion failed: \"hello\".length == 5")})(("hello".length === 5))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"\".length == 0")})(("".length === 0))}; diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/table/add_row.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/table/add_row.w_compile_tf-aws.md index 8bb648ea282..c0f53d10c9e 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/table/add_row.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/table/add_row.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ table, marioInfo, peachInfo, std_Json }) { +module.exports = function({ $marioInfo, $peachInfo, $std_Json, $table }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(table.get(\"mario\")) == Json.stringify(marioInfo)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([(await table.get("mario"))]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([marioInfo])))}; - {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(table.get(\"peach\")) == Json.stringify(peachInfo)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([(await table.get("peach"))]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([peachInfo])))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(table.get(\"mario\")) == Json.stringify(marioInfo)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([(await $table.get("mario"))]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([$marioInfo])))}; + {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(table.get(\"peach\")) == Json.stringify(peachInfo)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([(await $table.get("peach"))]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([$peachInfo])))}; } } return $Closure1; @@ -203,20 +201,15 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const table_client = context._lift(table); - const marioInfo_client = context._lift(marioInfo); - const peachInfo_client = context._lift(peachInfo); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - table: ${table_client}, - marioInfo: ${marioInfo_client}, - peachInfo: ${peachInfo_client}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $marioInfo: ${context._lift(marioInfo)}, + $peachInfo: ${context._lift(peachInfo)}, + $std_Json: ${context._lift(std.Json)}, + $table: ${context._lift(table)}, }) `); } @@ -232,11 +225,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(marioInfo, host, []); - $Closure1._registerBindObject(peachInfo, host, []); - $Closure1._registerBindObject(table, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(marioInfo, host, []); $Closure1._registerBindObject(peachInfo, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/table/list.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/table/list.w_compile_tf-aws.md index 5d7cf81d7e7..1e82beec964 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/table/list.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/table/list.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ table, std_String }) { +module.exports = function({ $std_String, $table }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await table.insert("eyal",Object.freeze({"gender":"male"}))); - (await table.insert("revital",Object.freeze({"gender":"female"}))); + async handle() { + (await $table.insert("eyal",Object.freeze({"gender":"male"}))); + (await $table.insert("revital",Object.freeze({"gender":"female"}))); const unorderded = {}; - for (const u of (await table.list())) { + for (const u of (await $table.list())) { ((obj, args) => { obj[args[0]] = args[1]; })(unorderded, [((args) => { if (typeof args !== "string") {throw new Error("unable to parse " + typeof args + " " + args + " as a string")}; return JSON.parse(JSON.stringify(args)) })((u)["name"]),u]); } const revital = (unorderded)["revital"]; @@ -189,16 +187,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const table_client = context._lift(table); - const std_StringClient = std.String._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - table: ${table_client}, - std_String: ${std_StringClient.text}, + require("./inflight.$Closure1.js")({ + $std_String: ${context._lift(std.String)}, + $table: ${context._lift(table)}, }) `); } @@ -214,9 +209,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(table, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(table, host, ["insert", "list"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/topic/on_message.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/topic/on_message.w_compile_tf-aws.md index 9de1c636b54..8a04b9ebaf5 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/topic/on_message.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/topic/on_message.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ c }) { +module.exports = function({ $c }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await c.inc()); + async handle() { + (await $c.inc()); } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ c }) { ## inflight.$Closure2.js ```js -module.exports = function({ c }) { +module.exports = function({ $c }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await c.inc()); + async handle() { + (await $c.inc()); } } return $Closure2; @@ -42,29 +38,27 @@ module.exports = function({ c }) { ## inflight.$Closure3.js ```js -module.exports = function({ t, predicate, TestHelper }) { +module.exports = function({ $TestHelper, $predicate, $t }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { for (const i of ((s,e,i) => { function* iterator(start,end,inclusive) { let i = start; let limit = inclusive ? ((end < start) ? end - 1 : end + 1) : end; while (i < limit) yield i++; while (i > limit) yield i--; }; return iterator(s,e,i); })(0,5,false)) { - (await t.publish("msg")); + (await $t.publish("msg")); } let i = 0; while ((i < 600)) { i = (i + 1); - if ((await predicate.test())) { - {((cond) => {if (!cond) throw new Error("assertion failed: predicate.test()")})((await predicate.test()))}; + if ((await $predicate.test())) { + {((cond) => {if (!cond) throw new Error("assertion failed: predicate.test()")})((await $predicate.test()))}; return; } - (await TestHelper.sleep(100)); + (await $TestHelper.sleep(100)); } - {((cond) => {if (!cond) throw new Error("assertion failed: predicate.test()")})((await predicate.test()))}; + {((cond) => {if (!cond) throw new Error("assertion failed: predicate.test()")})((await $predicate.test()))}; } } return $Closure3; @@ -76,13 +70,11 @@ module.exports = function({ t, predicate, TestHelper }) { ```js module.exports = function({ }) { class Predicate { - constructor({ c }) { - this.c = c; - } - async $inflight_init() { + constructor({ $this_c }) { + this.$this_c = $this_c; } - async test() { - return ((await this.c.peek()) === 10); + async test() { + return ((await this.$this_c.peek()) === 10); } } return Predicate; @@ -96,9 +88,7 @@ module.exports = function({ }) { class TestHelper { constructor({ }) { } - async $inflight_init() { - } - static async sleep(milli) { + static async sleep(milli) { return (require("/sleep.js")["sleep"])(milli) } } @@ -459,22 +449,20 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, c) { super(scope, id); this.c = c; - this._addInflightOps("test"); + this._addInflightOps("test", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Predicate.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Predicate.js")({ }) `); } _toInflight() { - const c_client = this._lift(this.c); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const PredicateClient = ${Predicate._toInflightType(this).text}; const client = new PredicateClient({ - c: ${c_client}, + $this_c: ${this._lift(this.c)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -482,9 +470,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Predicate._registerBindObject(this.c, host, []); - } if (ops.includes("test")) { Predicate._registerBindObject(this.c, host, ["peek"]); } @@ -494,12 +479,11 @@ class $Root extends $stdlib.std.Resource { class TestHelper extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("sleep"); + this._addInflightOps("sleep", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.TestHelper.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.TestHelper.js")({ }) `); } @@ -514,29 +498,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } - static _registerTypeBind(host, ops) { - if (ops.includes("sleep")) { - } - super._registerTypeBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const c_client = context._lift(c); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c: ${c_client}, + require("./inflight.$Closure1.js")({ + $c: ${context._lift(c)}, }) `); } @@ -552,9 +524,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(c, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(c, host, ["inc"]); } @@ -565,14 +534,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const c_client = context._lift(c); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c: ${c_client}, + require("./inflight.$Closure2.js")({ + $c: ${context._lift(c)}, }) `); } @@ -588,9 +555,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(c, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(c, host, ["inc"]); } @@ -601,18 +565,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const t_client = context._lift(t); - const predicate_client = context._lift(predicate); - const TestHelperClient = TestHelper._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - t: ${t_client}, - predicate: ${predicate_client}, - TestHelper: ${TestHelperClient.text}, + require("./inflight.$Closure3.js")({ + $TestHelper: ${context._lift(TestHelper)}, + $predicate: ${context._lift(predicate)}, + $t: ${context._lift(t)}, }) `); } @@ -628,10 +588,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(predicate, host, []); - $Closure3._registerBindObject(t, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(TestHelper, host, ["sleep"]); $Closure3._registerBindObject(predicate, host, ["test"]); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/env.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/env.w_compile_tf-aws.md index db0da2dd3a0..53aa77d916a 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/env.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/env.w_compile_tf-aws.md @@ -2,19 +2,17 @@ ## inflight.$Closure1.js ```js -module.exports = function({ RANDOM, NIL, util_Util }) { +module.exports = function({ $NIL, $RANDOM, $util_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: util.env(\"WING_TARGET\").length > 0")})(((await util_Util.env("WING_TARGET")).length > 0))}; - const noValue = ((await util_Util.tryEnv(RANDOM)) ?? NIL); - {((cond) => {if (!cond) throw new Error("assertion failed: noValue == NIL")})((noValue === NIL))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: util.env(\"WING_TARGET\").length > 0")})(((await $util_Util.env("WING_TARGET")).length > 0))}; + const noValue = ((await $util_Util.tryEnv($RANDOM)) ?? $NIL); + {((cond) => {if (!cond) throw new Error("assertion failed: noValue == NIL")})((noValue === $NIL))}; } } return $Closure1; @@ -158,18 +156,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const RANDOM_client = context._lift(RANDOM); - const NIL_client = context._lift(NIL); - const util_UtilClient = util.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - RANDOM: ${RANDOM_client}, - NIL: ${NIL_client}, - util_Util: ${util_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $NIL: ${context._lift(NIL)}, + $RANDOM: ${context._lift(RANDOM)}, + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -185,10 +179,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(NIL, host, []); - $Closure1._registerBindObject(RANDOM, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(NIL, host, []); $Closure1._registerBindObject(RANDOM, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/sleep.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/sleep.w_compile_tf-aws.md index 6871de95e6f..07df2b0eef4 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/sleep.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/sleep.w_compile_tf-aws.md @@ -2,19 +2,17 @@ ## inflight.$Closure1.js ```js -module.exports = function({ oneHundredMiliseconds, JSHelper, util_Util }) { +module.exports = function({ $JSHelper, $oneHundredMiliseconds, $util_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const start = (await JSHelper.getTime()); - (await util_Util.sleep(oneHundredMiliseconds)); - const end = (await JSHelper.getTime()); + async handle() { + const start = (await $JSHelper.getTime()); + (await $util_Util.sleep($oneHundredMiliseconds)); + const end = (await $JSHelper.getTime()); const delta = (end - start); {((cond) => {if (!cond) throw new Error("assertion failed: delta >= 100")})((delta >= 100))}; } @@ -30,9 +28,7 @@ module.exports = function({ }) { class JSHelper { constructor({ }) { } - async $inflight_init() { - } - static async getTime() { + static async getTime() { return (require("/sleep-helper.js")["getTime"])() } } @@ -176,12 +172,11 @@ class $Root extends $stdlib.std.Resource { class JSHelper extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("getTime"); + this._addInflightOps("getTime", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.JSHelper.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.JSHelper.js")({ }) `); } @@ -196,33 +191,19 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } - static _registerTypeBind(host, ops) { - if (ops.includes("getTime")) { - } - super._registerTypeBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const oneHundredMiliseconds_client = context._lift(oneHundredMiliseconds); - const JSHelperClient = JSHelper._toInflightType(context); - const util_UtilClient = util.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - oneHundredMiliseconds: ${oneHundredMiliseconds_client}, - JSHelper: ${JSHelperClient.text}, - util_Util: ${util_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $JSHelper: ${context._lift(JSHelper)}, + $oneHundredMiliseconds: ${context._lift(oneHundredMiliseconds)}, + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -238,9 +219,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(oneHundredMiliseconds, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(JSHelper, host, ["getTime"]); $Closure1._registerBindObject(oneHundredMiliseconds, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/wait-until.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/wait-until.w_compile_tf-aws.md index 349b6f1c81e..e676cd29a9d 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/wait-until.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/util/wait-until.w_compile_tf-aws.md @@ -2,22 +2,20 @@ ## inflight.$Closure1.js ```js -module.exports = function({ JSHelper, util_Util }) { +module.exports = function({ $JSHelper, $util_Util }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const start = (await JSHelper.getTime()); - if ((await util_Util.waitUntil(async () => { + async handle() { + const start = (await $JSHelper.getTime()); + if ((await $util_Util.waitUntil(async () => { return true; } ))) { - {((cond) => {if (!cond) throw new Error("assertion failed: JSHelper.getTime() - start < 1000")})((((await JSHelper.getTime()) - start) < 1000))}; + {((cond) => {if (!cond) throw new Error("assertion failed: JSHelper.getTime() - start < 1000")})((((await $JSHelper.getTime()) - start) < 1000))}; } else { {((cond) => {if (!cond) throw new Error("assertion failed: false")})(false)}; @@ -31,25 +29,23 @@ module.exports = function({ JSHelper, util_Util }) { ## inflight.$Closure2.js ```js -module.exports = function({ oneSecond, JSHelper, util_Util }) { +module.exports = function({ $JSHelper, $oneSecond, $util_Util }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const start = (await JSHelper.getTime()); - if ((await util_Util.waitUntil(async () => { + async handle() { + const start = (await $JSHelper.getTime()); + if ((await $util_Util.waitUntil(async () => { return false; } - ,{ timeout: oneSecond }))) { + ,{ timeout: $oneSecond }))) { {((cond) => {if (!cond) throw new Error("assertion failed: false")})(false)}; } else { - {((cond) => {if (!cond) throw new Error("assertion failed: JSHelper.getTime() - start > 1 * 1000")})((((await JSHelper.getTime()) - start) > (1 * 1000)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: JSHelper.getTime() - start > 1 * 1000")})((((await $JSHelper.getTime()) - start) > (1 * 1000)))}; } } } @@ -60,24 +56,22 @@ module.exports = function({ oneSecond, JSHelper, util_Util }) { ## inflight.$Closure3.js ```js -module.exports = function({ invokeCounter, oneSecond, JSHelper, util_Util }) { +module.exports = function({ $JSHelper, $invokeCounter, $oneSecond, $util_Util }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const start = (await JSHelper.getTime()); - const returnTrueAfter3Seconds = async () => { - (await invokeCounter.inc()); - return (((await JSHelper.getTime()) - start) > (3 * 1000)); + async handle() { + const start = (await $JSHelper.getTime()); + const returnTrueAfter3Seconds = async () => { + (await $invokeCounter.inc()); + return (((await $JSHelper.getTime()) - start) > (3 * 1000)); } ; - if ((await util_Util.waitUntil(returnTrueAfter3Seconds,{ interval: oneSecond }))) { - const invocations = (await invokeCounter.peek()); + if ((await $util_Util.waitUntil(returnTrueAfter3Seconds,{ interval: $oneSecond }))) { + const invocations = (await $invokeCounter.peek()); {((cond) => {if (!cond) throw new Error("assertion failed: invocations > 1 && invocations < 10 ")})(((invocations > 1) && (invocations < 10)))}; } else { @@ -92,27 +86,25 @@ module.exports = function({ invokeCounter, oneSecond, JSHelper, util_Util }) { ## inflight.$Closure4.js ```js -module.exports = function({ invokeCounter, oneSecond, fiveSeconds, JSHelper, util_Util }) { +module.exports = function({ $JSHelper, $fiveSeconds, $invokeCounter, $oneSecond, $util_Util }) { class $Closure4 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const start = (await JSHelper.getTime()); - const returnFalse = async () => { - (await invokeCounter.inc()); + async handle() { + const start = (await $JSHelper.getTime()); + const returnFalse = async () => { + (await $invokeCounter.inc()); return false; } ; - if ((await util_Util.waitUntil(returnFalse,{ interval: oneSecond, timeout: fiveSeconds }))) { + if ((await $util_Util.waitUntil(returnFalse,{ interval: $oneSecond, timeout: $fiveSeconds }))) { {((cond) => {if (!cond) throw new Error("assertion failed: false")})(false)}; } else { - const invokeCount = (await invokeCounter.peek()); + const invokeCount = (await $invokeCounter.peek()); {((cond) => {if (!cond) throw new Error("assertion failed: invokeCount > 3 && invokeCount < 7")})(((invokeCount > 3) && (invokeCount < 7)))}; } } @@ -124,26 +116,24 @@ module.exports = function({ invokeCounter, oneSecond, fiveSeconds, JSHelper, uti ## inflight.$Closure5.js ```js -module.exports = function({ invokeCounter, util_Util }) { +module.exports = function({ $invokeCounter, $util_Util }) { class $Closure5 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { try { - (await util_Util.waitUntil(async () => { - (await invokeCounter.inc()); + (await $util_Util.waitUntil(async () => { + (await $invokeCounter.inc()); {((msg) => {throw new Error(msg)})("ERROR")}; } )); {((cond) => {if (!cond) throw new Error("assertion failed: false")})(false)}; } catch { - {((cond) => {if (!cond) throw new Error("assertion failed: invokeCounter.peek() == 1")})(((await invokeCounter.peek()) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: invokeCounter.peek() == 1")})(((await $invokeCounter.peek()) === 1))}; } } } @@ -158,9 +148,7 @@ module.exports = function({ }) { class JSHelper { constructor({ }) { } - async $inflight_init() { - } - static async getTime() { + static async getTime() { return (require("/sleep-helper.js")["getTime"])() } } @@ -591,12 +579,11 @@ class $Root extends $stdlib.std.Resource { class JSHelper extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("getTime"); + this._addInflightOps("getTime", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.JSHelper.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.JSHelper.js")({ }) `); } @@ -611,31 +598,18 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } - static _registerTypeBind(host, ops) { - if (ops.includes("getTime")) { - } - super._registerTypeBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const JSHelperClient = JSHelper._toInflightType(context); - const util_UtilClient = util.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - JSHelper: ${JSHelperClient.text}, - util_Util: ${util_UtilClient.text}, + require("./inflight.$Closure1.js")({ + $JSHelper: ${context._lift(JSHelper)}, + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -651,8 +625,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } if (ops.includes("handle")) { $Closure1._registerBindObject(JSHelper, host, ["getTime"]); } @@ -663,18 +635,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const oneSecond_client = context._lift(oneSecond); - const JSHelperClient = JSHelper._toInflightType(context); - const util_UtilClient = util.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - oneSecond: ${oneSecond_client}, - JSHelper: ${JSHelperClient.text}, - util_Util: ${util_UtilClient.text}, + require("./inflight.$Closure2.js")({ + $JSHelper: ${context._lift(JSHelper)}, + $oneSecond: ${context._lift(oneSecond)}, + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -690,9 +658,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(oneSecond, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(JSHelper, host, ["getTime"]); $Closure2._registerBindObject(oneSecond, host, []); @@ -704,20 +669,15 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const invokeCounter_client = context._lift(invokeCounter); - const oneSecond_client = context._lift(oneSecond); - const JSHelperClient = JSHelper._toInflightType(context); - const util_UtilClient = util.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - invokeCounter: ${invokeCounter_client}, - oneSecond: ${oneSecond_client}, - JSHelper: ${JSHelperClient.text}, - util_Util: ${util_UtilClient.text}, + require("./inflight.$Closure3.js")({ + $JSHelper: ${context._lift(JSHelper)}, + $invokeCounter: ${context._lift(invokeCounter)}, + $oneSecond: ${context._lift(oneSecond)}, + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -733,10 +693,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(invokeCounter, host, []); - $Closure3._registerBindObject(oneSecond, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(JSHelper, host, ["getTime"]); $Closure3._registerBindObject(invokeCounter, host, ["inc", "peek"]); @@ -749,22 +705,16 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; - const invokeCounter_client = context._lift(invokeCounter); - const oneSecond_client = context._lift(oneSecond); - const fiveSeconds_client = context._lift(fiveSeconds); - const JSHelperClient = JSHelper._toInflightType(context); - const util_UtilClient = util.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - invokeCounter: ${invokeCounter_client}, - oneSecond: ${oneSecond_client}, - fiveSeconds: ${fiveSeconds_client}, - JSHelper: ${JSHelperClient.text}, - util_Util: ${util_UtilClient.text}, + require("./inflight.$Closure4.js")({ + $JSHelper: ${context._lift(JSHelper)}, + $fiveSeconds: ${context._lift(fiveSeconds)}, + $invokeCounter: ${context._lift(invokeCounter)}, + $oneSecond: ${context._lift(oneSecond)}, + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -780,11 +730,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure4._registerBindObject(fiveSeconds, host, []); - $Closure4._registerBindObject(invokeCounter, host, []); - $Closure4._registerBindObject(oneSecond, host, []); - } if (ops.includes("handle")) { $Closure4._registerBindObject(JSHelper, host, ["getTime"]); $Closure4._registerBindObject(fiveSeconds, host, []); @@ -798,16 +743,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure5.js"; - const invokeCounter_client = context._lift(invokeCounter); - const util_UtilClient = util.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - invokeCounter: ${invokeCounter_client}, - util_Util: ${util_UtilClient.text}, + require("./inflight.$Closure5.js")({ + $invokeCounter: ${context._lift(invokeCounter)}, + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -823,9 +765,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure5._registerBindObject(invokeCounter, host, []); - } if (ops.includes("handle")) { $Closure5._registerBindObject(invokeCounter, host, ["inc", "peek"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/sdk_tests/website/website.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/sdk_tests/website/website.w_compile_tf-aws.md index 61b1bc855a7..db6729df3cc 100644 --- a/tools/hangar/__snapshots__/test_corpus/sdk_tests/website/website.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/sdk_tests/website/website.w_compile_tf-aws.md @@ -2,19 +2,17 @@ ## inflight.$Closure1.js ```js -module.exports = function({ w, indexFile, otherFile, config, std_Json, Util }) { +module.exports = function({ $Util, $config, $indexFile, $otherFile, $std_Json, $w_url }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(Util.http(w.url).get(\"body\")) == Json.stringify(indexFile)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([((await Util.http(w.url)))["body"]]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([indexFile])))}; - {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(Util.http(w.url + \"/inner-folder/other.html\").get(\"body\")) == Json.stringify(otherFile)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([((await Util.http((w.url + "/inner-folder/other.html"))))["body"]]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([otherFile])))}; - {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(Util.http(w.url + \"/config.json\").get(\"body\")) == Json.stringify(Json.stringify(config))")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([((await Util.http((w.url + "/config.json"))))["body"]]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([((args) => { return JSON.stringify(args[0], null, args[1]) })([config])])))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(Util.http(w.url).get(\"body\")) == Json.stringify(indexFile)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([((await $Util.http($w_url)))["body"]]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([$indexFile])))}; + {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(Util.http(w.url + \"/inner-folder/other.html\").get(\"body\")) == Json.stringify(otherFile)")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([((await $Util.http(($w_url + "/inner-folder/other.html"))))["body"]]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([$otherFile])))}; + {((cond) => {if (!cond) throw new Error("assertion failed: Json.stringify(Util.http(w.url + \"/config.json\").get(\"body\")) == Json.stringify(Json.stringify(config))")})((((args) => { return JSON.stringify(args[0], null, args[1]) })([((await $Util.http(($w_url + "/config.json"))))["body"]]) === ((args) => { return JSON.stringify(args[0], null, args[1]) })([((args) => { return JSON.stringify(args[0], null, args[1]) })([$config])])))}; } } return $Closure1; @@ -28,9 +26,7 @@ module.exports = function({ }) { class Util { constructor({ }) { } - async $inflight_init() { - } - static async http(url) { + static async http(url) { return (require("/http.js")["http"])(url) } } @@ -339,15 +335,14 @@ class $Root extends $stdlib.std.Resource { class Util extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("http"); + this._addInflightOps("http", "$inflight_init"); } - static readFile(path) { + static readFile(path) { return (require("/fs.js")["readFile"])(path) } static _toInflightType(context) { - const self_client_path = "././inflight.Util.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Util.js")({ }) `); } @@ -362,39 +357,22 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } - static _registerTypeBind(host, ops) { - if (ops.includes("http")) { - } - super._registerTypeBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const w_client = context._lift(w); - const indexFile_client = context._lift(indexFile); - const otherFile_client = context._lift(otherFile); - const config_client = context._lift(config); - const std_JsonClient = std.Json._toInflightType(context); - const UtilClient = Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - w: ${w_client}, - indexFile: ${indexFile_client}, - otherFile: ${otherFile_client}, - config: ${config_client}, - std_Json: ${std_JsonClient.text}, - Util: ${UtilClient.text}, + require("./inflight.$Closure1.js")({ + $Util: ${context._lift(Util)}, + $config: ${context._lift(config)}, + $indexFile: ${context._lift(indexFile)}, + $otherFile: ${context._lift(otherFile)}, + $std_Json: ${context._lift(std.Json)}, + $w_url: ${context._lift(w.url)}, }) `); } @@ -410,18 +388,12 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(config, host, []); - $Closure1._registerBindObject(indexFile, host, []); - $Closure1._registerBindObject(otherFile, host, []); - $Closure1._registerBindObject(w, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(Util, host, ["http"]); $Closure1._registerBindObject(config, host, []); $Closure1._registerBindObject(indexFile, host, []); $Closure1._registerBindObject(otherFile, host, []); - $Closure1._registerBindObject(w.url, host, []); + $Closure1._registerBindObject(w.url, host, ["get"]); } super._registerBind(host, ops); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/anon_function.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/anon_function.w_compile_tf-aws.md index 3c459eb7d03..93fb3327490 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/anon_function.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/anon_function.w_compile_tf-aws.md @@ -42,20 +42,18 @@ const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); class $Root extends $stdlib.std.Resource { constructor(scope, id) { super(scope, id); - const myfunc = (x) => { + const myfunc = ((x) => { {console.log(String.raw({ raw: ["", ""] }, x))}; x = (x + 1); if ((x > 3.14)) { return; } (myfunc(x)); - } - ; + }); (myfunc(1)); - (( (x) => { + (((x) => { {((cond) => {if (!cond) throw new Error("assertion failed: x == 1")})((x === 1))}; - } - )(1)); + })(1)); } } class $App extends $AppBase { diff --git a/tools/hangar/__snapshots__/test_corpus/valid/api.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/api.w_compile_tf-aws.md index 5ecb57b2b4f..7a8db21ef02 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/api.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/api.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ counter, std_Json }) { +module.exports = function({ $counter, $std_Json }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(request) { - const count = (await counter.inc()); + async handle(request) { + const count = (await $counter.inc()); const bodyResponse = Object.freeze({"count":count}); const resp = { "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([bodyResponse]), @@ -29,17 +27,15 @@ module.exports = function({ counter, std_Json }) { ## inflight.$Closure2.js ```js -module.exports = function({ api }) { +module.exports = function({ $api_url }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const url = api.url; + async handle() { + const url = $api_url; {((cond) => {if (!cond) throw new Error("assertion failed: url.startsWith(\"http\")")})(url.startsWith("http"))}; } } @@ -50,17 +46,15 @@ module.exports = function({ api }) { ## inflight.$Closure3.js ```js -module.exports = function({ __parent_this_3 }) { +module.exports = function({ $__parent_this_3_api_url }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { - const text = String.raw({ raw: ["", "/endpoint2"] }, __parent_this_3.api.url); + async handle(req) { + const text = String.raw({ raw: ["", "/endpoint2"] }, $__parent_this_3_api_url); return { "status": 200, "body": text,} @@ -76,10 +70,7 @@ module.exports = function({ __parent_this_3 }) { ```js module.exports = function({ }) { class A { - constructor({ api }) { - this.api = api; - } - async $inflight_init() { + constructor({ }) { } } return A; @@ -142,7 +133,7 @@ module.exports = function({ }) { }, "rest_api_id": "${aws_api_gateway_rest_api.A_cloudApi_api_37FCEF91.id}", "triggers": { - "redeployment": "66f9e4b69146527e1951e6308dc9128a3ca41abb" + "redeployment": "ee737a93987c97858ba9524a5b87b2ff1b0e62e4" } }, "cloudApi_api_deployment_545514BF": { @@ -329,10 +320,9 @@ module.exports = function({ }) { }, "environment": { "variables": { - "CLOUD_API_C8B1D888": "${aws_api_gateway_stage.A_cloudApi_api_stage_6D822CCE.invoke_url}", "WING_FUNCTION_NAME": "cloud-Api-OnRequest-73c5308f-c85168bb", "WING_TARGET": "tf-aws", - "WING_TOKEN_TFTOKEN_TOKEN_41": "${jsonencode(aws_api_gateway_stage.A_cloudApi_api_stage_6D822CCE.invoke_url)}" + "WING_TOKEN_TFTOKEN_TOKEN_42": "${jsonencode(aws_api_gateway_stage.A_cloudApi_api_stage_6D822CCE.invoke_url)}" } }, "function_name": "cloud-Api-OnRequest-73c5308f-c85168bb", @@ -384,7 +374,6 @@ module.exports = function({ }) { }, "environment": { "variables": { - "CLOUD_API_C82DF3A5": "${aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url}", "WING_FUNCTION_NAME": "Handler-c8315524", "WING_TARGET": "tf-aws", "WING_TOKEN_TFTOKEN_TOKEN_21": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" @@ -497,16 +486,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const counter_client = context._lift(counter); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counter: ${counter_client}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $counter: ${context._lift(counter)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -522,9 +508,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(counter, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(counter, host, ["inc"]); } @@ -535,14 +518,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const api_client = context._lift(api); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api: ${api_client}, + require("./inflight.$Closure2.js")({ + $api_url: ${context._lift(api.url)}, }) `); } @@ -558,9 +539,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(api, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(api.url, host, []); } @@ -576,14 +554,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const __parent_this_3_client = context._lift(__parent_this_3); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - __parent_this_3: ${__parent_this_3_client}, + require("./inflight.$Closure3.js")({ + $__parent_this_3_api_url: ${context._lift(__parent_this_3.api.url)}, }) `); } @@ -599,9 +575,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(__parent_this_3, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(__parent_this_3.api.url, host, []); } @@ -609,33 +582,25 @@ class $Root extends $stdlib.std.Resource { } } (this.api.get("/endpoint1",new $Closure3(this,"$Closure3"))); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.A.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.A.js")({ }) `); } _toInflight() { - const api_client = this._lift(this.api); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const AClient = ${A._toInflightType(this).text}; const client = new AClient({ - api: ${api_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - A._registerBindObject(this.api, host, []); - } - super._registerBind(host, ops); - } } const api = this.node.root.newAbstract("@winglang/sdk.cloud.Api",this,"cloud.Api"); const counter = this.node.root.newAbstract("@winglang/sdk.cloud.Counter",this,"cloud.Counter"); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/api_path_vars.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/api_path_vars.w_compile_tf-aws.md index 459e17a6b0d..6282301d606 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/api_path_vars.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/api_path_vars.w_compile_tf-aws.md @@ -2,16 +2,14 @@ ## inflight.$Closure1.js ```js -module.exports = function({ std_Json }) { +module.exports = function({ $std_Json }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { + async handle(req) { return { "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([Object.freeze({"user":(req.vars)["name"]})]), "headers": Object.freeze({"content-type":"application/json"}), @@ -26,18 +24,16 @@ module.exports = function({ std_Json }) { ## inflight.$Closure2.js ```js -module.exports = function({ api, http_Util, std_Json }) { +module.exports = function({ $api_url, $http_Util, $std_Json }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const username = "tsuf"; - const res = (await http_Util.get(String.raw({ raw: ["", "/users/", ""] }, api.url, username))); + const res = (await $http_Util.get(String.raw({ raw: ["", "/users/", ""] }, $api_url, username))); {((cond) => {if (!cond) throw new Error("assertion failed: res.status == 200")})((res.status === 200))}; {((cond) => {if (!cond) throw new Error("assertion failed: Json.parse(res.body ?? \"\").get(\"user\") == username")})((((JSON.parse((res.body ?? ""))))["user"] === username))}; } @@ -231,7 +227,6 @@ module.exports = function({ api, http_Util, std_Json }) { }, "environment": { "variables": { - "CLOUD_API_C82DF3A5": "${aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url}", "WING_FUNCTION_NAME": "Handler-c8f4f2a1", "WING_TARGET": "tf-aws", "WING_TOKEN_TFTOKEN_TOKEN_21": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" @@ -321,14 +316,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -343,30 +336,19 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const api_client = context._lift(api); - const http_UtilClient = http.Util._toInflightType(context); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api: ${api_client}, - http_Util: ${http_UtilClient.text}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure2.js")({ + $api_url: ${context._lift(api.url)}, + $http_Util: ${context._lift(http.Util)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -382,9 +364,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(api, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(api.url, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/api_valid_path.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/api_valid_path.w_compile_tf-aws.md index 910e1782aba..98e592331b8 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/api_valid_path.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/api_valid_path.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { + async handle(req) { return { "body": "ok", "status": 200,} @@ -280,12 +278,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -300,17 +297,10 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } const api = this.node.root.newAbstract("@winglang/sdk.cloud.Api",this,"cloud.Api"); const handler = new $Closure1(this,"$Closure1"); - const testInvalidPath = (path) => { + const testInvalidPath = ((path) => { let error = ""; const expected = String.raw({ raw: ["Invalid path ", ". Url cannot contain \":\", params contains only alpha-numeric chars or \"_\"."] }, path); try { @@ -321,9 +311,8 @@ class $Root extends $stdlib.std.Resource { error = e; } {((cond) => {if (!cond) throw new Error("assertion failed: error == expected")})((error === expected))}; - } - ; - const testValidPath = (path) => { + }); + const testValidPath = ((path) => { let error = ""; try { (api.get(path,handler)); @@ -333,8 +322,7 @@ class $Root extends $stdlib.std.Resource { error = e; } {((cond) => {if (!cond) throw new Error("assertion failed: error == \"\"")})((error === ""))}; - } - ; + }); (testInvalidPath("/test/{sup:er/:annoying//path}")); (testInvalidPath("/test/{::another:annoying:path}")); (testInvalidPath("/test/n0t_alphanumer1cPa:th")); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/assert.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/assert.w_compile_tf-aws.md index 0971d37666f..d55dafe526f 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/assert.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/assert.w_compile_tf-aws.md @@ -2,31 +2,29 @@ ## inflight.$Closure1.js ```js -module.exports = function({ s1, s2 }) { +module.exports = function({ $s1, $s2 }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: \"\" == \"\"")})(("" === ""))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"\'\" == \"\'\"")})(("'" === "'"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"\\\"\" == \"\\\"\"")})(("\"" === "\""))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"`\" == \"`\"")})(("`" === "`"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"``\" == \"``\"")})(("``" === "``"))}; {((cond) => {if (!cond) throw new Error("assertion failed: \"`s1`\" == \"`s1`\"")})(("`s1`" === "`s1`"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: s1 == s1")})((s1 === s1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: \"${s1}\" == \"${s1}\"")})((String.raw({ raw: ["", ""] }, s1) === String.raw({ raw: ["", ""] }, s1)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: \"${s1}\" != \"${s2}\"")})((String.raw({ raw: ["", ""] }, s1) !== String.raw({ raw: ["", ""] }, s2)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: \"a${s1}\" == \"a${s1}\"")})((String.raw({ raw: ["a", ""] }, s1) === String.raw({ raw: ["a", ""] }, s1)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: \"a${s1}\" != \"b${s1}\"")})((String.raw({ raw: ["a", ""] }, s1) !== String.raw({ raw: ["b", ""] }, s1)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: \"${s1}a\" == \"${s1}a\"")})((String.raw({ raw: ["", "a"] }, s1) === String.raw({ raw: ["", "a"] }, s1)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: \"${s1}a\" != \"${s1}b\"")})((String.raw({ raw: ["", "a"] }, s1) !== String.raw({ raw: ["", "b"] }, s1)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: \"`\'${s1}\" == \"`\'${s1}\"")})((String.raw({ raw: ["`'", ""] }, s1) === String.raw({ raw: ["`'", ""] }, s1)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: \"a${s1}b${s2}c\" == \"a${s1}b${s2}c\"")})((String.raw({ raw: ["a", "b", "c"] }, s1, s2) === String.raw({ raw: ["a", "b", "c"] }, s1, s2)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: s1 == s1")})(($s1 === $s1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: \"${s1}\" == \"${s1}\"")})((String.raw({ raw: ["", ""] }, $s1) === String.raw({ raw: ["", ""] }, $s1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: \"${s1}\" != \"${s2}\"")})((String.raw({ raw: ["", ""] }, $s1) !== String.raw({ raw: ["", ""] }, $s2)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: \"a${s1}\" == \"a${s1}\"")})((String.raw({ raw: ["a", ""] }, $s1) === String.raw({ raw: ["a", ""] }, $s1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: \"a${s1}\" != \"b${s1}\"")})((String.raw({ raw: ["a", ""] }, $s1) !== String.raw({ raw: ["b", ""] }, $s1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: \"${s1}a\" == \"${s1}a\"")})((String.raw({ raw: ["", "a"] }, $s1) === String.raw({ raw: ["", "a"] }, $s1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: \"${s1}a\" != \"${s1}b\"")})((String.raw({ raw: ["", "a"] }, $s1) !== String.raw({ raw: ["", "b"] }, $s1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: \"`\'${s1}\" == \"`\'${s1}\"")})((String.raw({ raw: ["`'", ""] }, $s1) === String.raw({ raw: ["`'", ""] }, $s1)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: \"a${s1}b${s2}c\" == \"a${s1}b${s2}c\"")})((String.raw({ raw: ["a", "b", "c"] }, $s1, $s2) === String.raw({ raw: ["a", "b", "c"] }, $s1, $s2)))}; } } return $Closure1; @@ -169,16 +167,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const s1_client = context._lift(s1); - const s2_client = context._lift(s2); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - s1: ${s1_client}, - s2: ${s2_client}, + require("./inflight.$Closure1.js")({ + $s1: ${context._lift(s1)}, + $s2: ${context._lift(s2)}, }) `); } @@ -194,10 +189,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(s1, host, []); - $Closure1._registerBindObject(s2, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(s1, host, []); $Closure1._registerBindObject(s2, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/asynchronous_model_implicit_await_in_functions.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/asynchronous_model_implicit_await_in_functions.w_compile_tf-aws.md index e0991718272..0f640e2b030 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/asynchronous_model_implicit_await_in_functions.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/asynchronous_model_implicit_await_in_functions.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(s) { + async handle(s) { } } return $Closure1; @@ -21,18 +19,16 @@ module.exports = function({ }) { ## inflight.$Closure2.js ```js -module.exports = function({ strToStr }) { +module.exports = function({ $strToStr }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(s) { - (await strToStr.invoke("one")); - {console.log((await strToStr.invoke("two")))}; + async handle(s) { + (await $strToStr.invoke("one")); + {console.log((await $strToStr.invoke("two")))}; } } return $Closure2; @@ -254,12 +250,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -274,26 +269,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const strToStr_client = context._lift(strToStr); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - strToStr: ${strToStr_client}, + require("./inflight.$Closure2.js")({ + $strToStr: ${context._lift(strToStr)}, }) `); } @@ -309,9 +295,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(strToStr, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(strToStr, host, ["invoke"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/bring_awscdk.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/bring_awscdk.w_compile_tf-aws.md index 50d942d1955..75a7affdf33 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/bring_awscdk.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/bring_awscdk.w_compile_tf-aws.md @@ -4,10 +4,7 @@ ```js module.exports = function({ }) { class CdkDockerImageFunction { - constructor({ function }) { - this.function = function; - } - async $inflight_init() { + constructor({ }) { } } return CdkDockerImageFunction; @@ -64,33 +61,25 @@ class $Root extends $stdlib.std.Resource { this.function = this.node.root.new("aws-cdk-lib.aws_lambda.DockerImageFunction",awscdk.aws_lambda.DockerImageFunction,this,"DockerImageFunction",{ "code": (awscdk.aws_lambda.DockerImageCode.fromImageAsset("./test.ts")),} ); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.CdkDockerImageFunction.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.CdkDockerImageFunction.js")({ }) `); } _toInflight() { - const function_client = this._lift(this.function); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const CdkDockerImageFunctionClient = ${CdkDockerImageFunction._toInflightType(this).text}; const client = new CdkDockerImageFunctionClient({ - function: ${function_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - CdkDockerImageFunction._registerBindObject(this.function, host, []); - } - super._registerBind(host, ops); - } } this.node.root.new("aws-cdk-lib.App",awscdk.App,); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/bring_cdktf.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/bring_cdktf.w_compile_tf-aws.md index 6c3d9df185a..e1135b13b73 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/bring_cdktf.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/bring_cdktf.w_compile_tf-aws.md @@ -6,8 +6,6 @@ module.exports = function({ }) { class Foo { constructor({ }) { } - async $inflight_init() { - } } return Foo; } @@ -82,11 +80,11 @@ class $Root extends $stdlib.std.Resource { "bucket": "foo", "key": "bar",} ); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } @@ -101,11 +99,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } this.node.root.new("@cdktf/provider-aws.s3Bucket.S3Bucket",aws.s3Bucket.S3Bucket,this,"Bucket",{ bucketPrefix: "hello", versioning: { "enabled": true, diff --git a/tools/hangar/__snapshots__/test_corpus/valid/bring_jsii.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/bring_jsii.w_compile_tf-aws.md index 9e74ce4594f..fec54c8ba01 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/bring_jsii.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/bring_jsii.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ greeting }) { +module.exports = function({ $greeting }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: greeting == \"Hello, wingnuts\"")})((greeting === "Hello, wingnuts"))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: greeting == \"Hello, wingnuts\"")})(($greeting === "Hello, wingnuts"))}; } } return $Closure1; @@ -157,14 +155,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const greeting_client = context._lift(greeting); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - greeting: ${greeting_client}, + require("./inflight.$Closure1.js")({ + $greeting: ${context._lift(greeting)}, }) `); } @@ -180,9 +176,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(greeting, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(greeting, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/bring_jsii_path.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/bring_jsii_path.w_compile_tf-aws.md index daf0b9f4483..6b9c72e2969 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/bring_jsii_path.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/bring_jsii_path.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ greeting }) { +module.exports = function({ $greeting }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: greeting == \"Hello, wingnuts\"")})((greeting === "Hello, wingnuts"))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: greeting == \"Hello, wingnuts\"")})(($greeting === "Hello, wingnuts"))}; } } return $Closure1; @@ -157,14 +155,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const greeting_client = context._lift(greeting); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - greeting: ${greeting_client}, + require("./inflight.$Closure1.js")({ + $greeting: ${context._lift(greeting)}, }) `); } @@ -180,9 +176,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(greeting, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(greeting, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/bucket_events.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/bucket_events.w_compile_tf-aws.md index 86efcdaffad..7dd8ae7b525 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/bucket_events.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/bucket_events.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key) { + async handle(key) { {console.log(String.raw({ raw: ["deleted ", ""] }, key))}; } } @@ -29,9 +27,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key) { + async handle(key) { {console.log(String.raw({ raw: ["updated ", ""] }, key))}; } } @@ -49,9 +45,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key) { + async handle(key) { {console.log(String.raw({ raw: ["created ", ""] }, key))}; } } @@ -62,17 +56,15 @@ module.exports = function({ }) { ## inflight.$Closure4.js ```js -module.exports = function({ other }) { +module.exports = function({ $other }) { class $Closure4 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key, event) { - (await other.put(String.raw({ raw: ["last_", "_key"] }, event),key)); + async handle(key, event) { + (await $other.put(String.raw({ raw: ["last_", "_key"] }, event),key)); } } return $Closure4; @@ -89,9 +81,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key) { + async handle(key) { {console.log("other bucket event called!")}; } } @@ -102,21 +92,19 @@ module.exports = function({ }) { ## inflight.$Closure6.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure6 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await b.put("a","1")); - (await b.put("b","1")); - (await b.put("b","100")); - (await b.put("c","1")); - (await b.delete("c")); + async handle() { + (await $b.put("a","1")); + (await $b.put("b","1")); + (await $b.put("b","100")); + (await $b.put("c","1")); + (await $b.delete("c")); } } return $Closure6; @@ -1345,12 +1333,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -1365,24 +1352,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure2.js")({ }) `); } @@ -1397,24 +1376,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure3 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure3.js")({ }) `); } @@ -1429,26 +1400,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure4 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; - const other_client = context._lift(other); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - other: ${other_client}, + require("./inflight.$Closure4.js")({ + $other: ${context._lift(other)}, }) `); } @@ -1464,9 +1426,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure4._registerBindObject(other, host, []); - } if (ops.includes("handle")) { $Closure4._registerBindObject(other, host, ["put"]); } @@ -1477,12 +1436,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure5.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure5.js")({ }) `); } @@ -1497,26 +1455,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure6 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure6.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure6.js")({ + $b: ${context._lift(b)}, }) `); } @@ -1532,9 +1481,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure6._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure6._registerBindObject(b, host, ["delete", "put"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/bucket_keys.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/bucket_keys.w_compile_tf-aws.md index bb04a8a9d88..c6535245e04 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/bucket_keys.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/bucket_keys.w_compile_tf-aws.md @@ -2,22 +2,20 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await b.put("foo","text")); - (await b.put("foo/","text")); - (await b.put("foo/bar","text")); - (await b.put("foo/bar/","text")); - (await b.put("foo/bar/baz","text")); - const objs = (await b.list()); + async handle() { + (await $b.put("foo","text")); + (await $b.put("foo/","text")); + (await $b.put("foo/bar","text")); + (await $b.put("foo/bar/","text")); + (await $b.put("foo/bar/baz","text")); + const objs = (await $b.list()); {((cond) => {if (!cond) throw new Error("assertion failed: objs.at(0) == \"foo\"")})(((await objs.at(0)) === "foo"))}; {((cond) => {if (!cond) throw new Error("assertion failed: objs.at(1) == \"foo/\"")})(((await objs.at(1)) === "foo/"))}; {((cond) => {if (!cond) throw new Error("assertion failed: objs.at(2) == \"foo/bar\"")})(((await objs.at(2)) === "foo/bar"))}; @@ -210,14 +208,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, }) `); } @@ -233,9 +229,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["list", "put"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/call_static_of_myself.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/call_static_of_myself.w_compile_tf-aws.md new file mode 100644 index 00000000000..e509c7ede34 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/call_static_of_myself.w_compile_tf-aws.md @@ -0,0 +1,301 @@ +# [call_static_of_myself.w](../../../../../examples/tests/valid/call_static_of_myself.w) | compile | tf-aws + +## inflight.$Closure1.js +```js +module.exports = function({ $Bar, $Foo, $foo }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + class Zoo { + static async zoo() { + return 3; + } + } + const bar = new $Bar(); + {((cond) => {if (!cond) throw new Error("assertion failed: Foo.foo() == 1")})(((await $Foo.foo()) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: Bar.bar() == 2")})(((await $Bar.bar()) === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: Zoo.zoo() == 3")})(((await Zoo.zoo()) === 3))}; + {((cond) => {if (!cond) throw new Error("assertion failed: foo.callThis() == 1")})(((await $foo.callThis()) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: bar.callThis() == 2")})(((await bar.callThis()) === 2))}; + } + } + return $Closure1; +} + +``` + +## inflight.Bar.js +```js +module.exports = function({ }) { + class Bar { + static async bar() { + return 2; + } + async callThis() { + return (await Bar.bar()); + } + } + return Bar; +} + +``` + +## inflight.Foo.js +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + static async foo() { + return 1; + } + static async bar() { + return (await Foo.foo()); + } + async callThis() { + return (await Foo.bar()); + } + } + return Foo; +} + +``` + +## main.tf.json +```json +{ + "//": { + "metadata": { + "backend": "local", + "stackName": "root", + "version": "0.17.0" + }, + "outputs": { + "root": { + "Default": { + "cloud.TestRunner": { + "TestFunctionArns": "WING_TEST_RUNNER_FUNCTION_ARNS" + } + } + } + } + }, + "output": { + "WING_TEST_RUNNER_FUNCTION_ARNS": { + "value": "[[\"root/Default/Default/test:test\",\"${aws_lambda_function.testtest_Handler_295107CC.arn}\"]]" + } + }, + "provider": { + "aws": [ + {} + ] + }, + "resource": { + "aws_iam_role": { + "testtest_Handler_IamRole_15693C93": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRole", + "uniqueId": "testtest_Handler_IamRole_15693C93" + } + }, + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}" + } + }, + "aws_iam_role_policy": { + "testtest_Handler_IamRolePolicy_AF0279BD": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicy", + "uniqueId": "testtest_Handler_IamRolePolicy_AF0279BD" + } + }, + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"none:null\",\"Resource\":\"*\"}]}", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_iam_role_policy_attachment": { + "testtest_Handler_IamRolePolicyAttachment_ADF4752D": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicyAttachment", + "uniqueId": "testtest_Handler_IamRolePolicyAttachment_ADF4752D" + } + }, + "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_lambda_function": { + "testtest_Handler_295107CC": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/Default", + "uniqueId": "testtest_Handler_295107CC" + } + }, + "environment": { + "variables": { + "WING_FUNCTION_NAME": "Handler-c8f4f2a1", + "WING_TARGET": "tf-aws" + } + }, + "function_name": "Handler-c8f4f2a1", + "handler": "index.handler", + "publish": true, + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.arn}", + "runtime": "nodejs18.x", + "s3_bucket": "${aws_s3_bucket.Code.bucket}", + "s3_key": "${aws_s3_object.testtest_Handler_S3Object_9F4E28A7.key}", + "timeout": 30, + "vpc_config": { + "security_group_ids": [], + "subnet_ids": [] + } + } + }, + "aws_s3_bucket": { + "Code": { + "//": { + "metadata": { + "path": "root/Default/Code", + "uniqueId": "Code" + } + }, + "bucket_prefix": "code-c84a50b1-" + } + }, + "aws_s3_object": { + "testtest_Handler_S3Object_9F4E28A7": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/S3Object", + "uniqueId": "testtest_Handler_S3Object_9F4E28A7" + } + }, + "bucket": "${aws_s3_bucket.Code.bucket}", + "key": "", + "source": "" + } + } + } +} +``` + +## preflight.js +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("foo", "bar", "callThis", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class Bar extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("bar", "callThis", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Bar.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BarClient = ${Bar._toInflightType(this).text}; + const client = new BarClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $Bar: ${context._lift(Bar)}, + $Foo: ${context._lift(Foo)}, + $foo: ${context._lift(foo)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(Foo, host, ["foo"]); + $Closure1._registerBindObject(foo, host, ["callThis"]); + } + super._registerBind(host, ops); + } + } + const foo = new Foo(this,"Foo"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "call_static_of_myself", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); + +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/call_static_of_myself.w_test_sim.md b/tools/hangar/__snapshots__/test_corpus/valid/call_static_of_myself.w_test_sim.md new file mode 100644 index 00000000000..d71ff2984e6 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/call_static_of_myself.w_test_sim.md @@ -0,0 +1,12 @@ +# [call_static_of_myself.w](../../../../../examples/tests/valid/call_static_of_myself.w) | test | sim + +## stdout.log +```log +pass ─ call_static_of_myself.wsim » root/env0/test:test + + +Tests 1 passed (1) +Test Files 1 passed (1) +Duration +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/calling_inflight_variants.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/calling_inflight_variants.w_compile_tf-aws.md index 8161b02b854..e352a11e789 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/calling_inflight_variants.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/calling_inflight_variants.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { return 1; } } @@ -22,19 +20,17 @@ module.exports = function({ }) { ## inflight.$Closure2.js ```js -module.exports = function({ foo }) { +module.exports = function({ $foo }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: foo.callFn(true) == 1")})(((await foo.callFn(true)) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: foo.callFn(false) == 2")})(((await foo.callFn(false)) === 2))}; - (await foo.callFn2()); + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: foo.callFn(true) == 1")})(((await $foo.callFn(true)) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: foo.callFn(false) == 2")})(((await $foo.callFn(false)) === 2))}; + (await $foo.callFn2()); } } return $Closure2; @@ -46,35 +42,35 @@ module.exports = function({ foo }) { ```js module.exports = function({ }) { class Foo { - constructor({ inflight1 }) { - this.inflight1 = inflight1; + constructor({ $this_inflight1 }) { + this.$this_inflight1 = $this_inflight1; } - async $inflight_init() { - this.inflight2 = async () => { - return 2; - } - ; - const ret = (await this.inflight2()); - {((cond) => {if (!cond) throw new Error("assertion failed: ret == 2")})((ret === 2))}; - } - async makeFn(x) { + async makeFn(x) { if ((x === true)) { - return this.inflight1; + return this.$this_inflight1; } else { return this.inflight2; } } - async callFn(x) { + async callFn(x) { const partialFn = (await this.makeFn(x)); return (await partialFn()); } - async callFn2() { - const one = (await this.inflight1()); + async callFn2() { + const one = (await this.$this_inflight1()); const two = (await this.inflight2()); {((cond) => {if (!cond) throw new Error("assertion failed: one == 1")})((one === 1))}; {((cond) => {if (!cond) throw new Error("assertion failed: two == 2")})((two === 2))}; } + async $inflight_init() { + this.inflight2 = async () => { + return 2; + } + ; + const ret = (await this.inflight2()); + {((cond) => {if (!cond) throw new Error("assertion failed: ret == 2")})((ret === 2))}; + } } return Foo; } @@ -209,7 +205,6 @@ const $outdir = process.env.WING_SYNTH_DIR ?? "."; const std = $stdlib.std; const $wing_is_test = process.env.WING_IS_TEST === "true"; const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); -const cloud = require('@winglang/sdk').cloud; class $Root extends $stdlib.std.Resource { constructor(scope, id) { super(scope, id); @@ -221,12 +216,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -241,31 +235,22 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } this.inflight1 = new $Closure1(this,"$Closure1"); - this._addInflightOps("makeFn", "callFn", "callFn2", "inflight2"); + this._addInflightOps("makeFn", "callFn", "callFn2", "$inflight_init", "inflight2"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } _toInflight() { - const inflight1_client = this._lift(this.inflight1); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const FooClient = ${Foo._toInflightType(this).text}; const client = new FooClient({ - inflight1: ${inflight1_client}, + $this_inflight1: ${this._lift(this.inflight1)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -274,15 +259,18 @@ class $Root extends $stdlib.std.Resource { } _registerBind(host, ops) { if (ops.includes("$inflight_init")) { - Foo._registerBindObject(this.inflight1, host, []); + Foo._registerBindObject(this, host, ["inflight2"]); } if (ops.includes("callFn")) { + Foo._registerBindObject(this, host, ["makeFn"]); } if (ops.includes("callFn2")) { Foo._registerBindObject(this.inflight1, host, ["handle"]); + Foo._registerBindObject(this, host, ["inflight2"]); } if (ops.includes("makeFn")) { Foo._registerBindObject(this.inflight1, host, ["handle"]); + Foo._registerBindObject(this, host, ["inflight2"]); } super._registerBind(host, ops); } @@ -291,14 +279,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const foo_client = context._lift(foo); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - foo: ${foo_client}, + require("./inflight.$Closure2.js")({ + $foo: ${context._lift(foo)}, }) `); } @@ -314,9 +300,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(foo, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(foo, host, ["callFn", "callFn2"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/capture_containers.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/capture_containers.w_compile_tf-aws.md index 92b67e7662f..97e23705da5 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/capture_containers.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/capture_containers.w_compile_tf-aws.md @@ -2,25 +2,23 @@ ## inflight.$Closure1.js ```js -module.exports = function({ arr, mySet, myMap, arrOfMap, j }) { +module.exports = function({ $Object_keys_myMap__length, $__bang__in___arrOfMap_at_0____, $__world__in__myMap__, $_arr_at_0__, $_arr_at_1__, $_j___b__, $_mySet_has__my___, $arr_length, $mySet_size }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: arr.at(0) == \"hello\"")})(((await arr.at(0)) === "hello"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: arr.at(1) == \"world\"")})(((await arr.at(1)) === "world"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: arr.length == 2")})((arr.length === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: mySet.has(\"my\")")})((await mySet.has("my")))}; - {((cond) => {if (!cond) throw new Error("assertion failed: mySet.size == 2")})((mySet.size === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: myMap.has(\"world\")")})(("world" in (myMap)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: myMap.size() == 2")})((Object.keys(myMap).length === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: arrOfMap.at(0).has(\"bang\")")})(("bang" in ((await arrOfMap.at(0)))))}; - {((cond) => {if (!cond) throw new Error("assertion failed: j.get(\"b\") == \"world\"")})(((j)["b"] === "world"))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: arr.at(0) == \"hello\"")})(($_arr_at_0__ === "hello"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: arr.at(1) == \"world\"")})(($_arr_at_1__ === "world"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: arr.length == 2")})(($arr_length === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: mySet.has(\"my\")")})($_mySet_has__my___)}; + {((cond) => {if (!cond) throw new Error("assertion failed: mySet.size == 2")})(($mySet_size === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: myMap.has(\"world\")")})($__world__in__myMap__)}; + {((cond) => {if (!cond) throw new Error("assertion failed: myMap.size() == 2")})(($Object_keys_myMap__length === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: arrOfMap.at(0).has(\"bang\")")})($__bang__in___arrOfMap_at_0____)}; + {((cond) => {if (!cond) throw new Error("assertion failed: j.get(\"b\") == \"world\"")})(($_j___b__ === "world"))}; } } return $Closure1; @@ -164,22 +162,20 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const arr_client = context._lift(arr); - const mySet_client = context._lift(mySet); - const myMap_client = context._lift(myMap); - const arrOfMap_client = context._lift(arrOfMap); - const j_client = context._lift(j); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - arr: ${arr_client}, - mySet: ${mySet_client}, - myMap: ${myMap_client}, - arrOfMap: ${arrOfMap_client}, - j: ${j_client}, + require("./inflight.$Closure1.js")({ + $Object_keys_myMap__length: ${context._lift(Object.keys(myMap).length)}, + $__bang__in___arrOfMap_at_0____: ${context._lift(("bang" in ((arrOfMap.at(0)))))}, + $__world__in__myMap__: ${context._lift(("world" in (myMap)))}, + $_arr_at_0__: ${context._lift((arr.at(0)))}, + $_arr_at_1__: ${context._lift((arr.at(1)))}, + $_j___b__: ${context._lift((j)["b"])}, + $_mySet_has__my___: ${context._lift((mySet.has("my")))}, + $arr_length: ${context._lift(arr.length)}, + $mySet_size: ${context._lift(mySet.size)}, }) `); } @@ -195,19 +191,16 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(arr, host, []); - $Closure1._registerBindObject(arrOfMap, host, []); - $Closure1._registerBindObject(j, host, []); - $Closure1._registerBindObject(myMap, host, []); - $Closure1._registerBindObject(mySet, host, []); - } if (ops.includes("handle")) { - $Closure1._registerBindObject(arr, host, ["at", "length"]); - $Closure1._registerBindObject(arrOfMap, host, ["at"]); - $Closure1._registerBindObject(j, host, []); - $Closure1._registerBindObject(myMap, host, ["has", "size"]); - $Closure1._registerBindObject(mySet, host, ["has", "size"]); + $Closure1._registerBindObject(Object.keys(myMap).length, host, []); + $Closure1._registerBindObject(("bang" in ((arrOfMap.at(0)))), host, []); + $Closure1._registerBindObject(("world" in (myMap)), host, []); + $Closure1._registerBindObject((arr.at(0)), host, []); + $Closure1._registerBindObject((arr.at(1)), host, []); + $Closure1._registerBindObject((j)["b"], host, []); + $Closure1._registerBindObject((mySet.has("my")), host, []); + $Closure1._registerBindObject(arr.length, host, []); + $Closure1._registerBindObject(mySet.size, host, []); } super._registerBind(host, ops); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/capture_in_binary.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/capture_in_binary.w_compile_tf-aws.md index 0b0c7563d49..fb0e1a08235 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/capture_in_binary.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/capture_in_binary.w_compile_tf-aws.md @@ -2,19 +2,17 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b, x }) { +module.exports = function({ $b, $x }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await b.put("file","foo")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.get(\"file\") == \"foo\"")})(((await b.get("file")) === "foo"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: 12 == x")})((12 === x))}; + async handle() { + (await $b.put("file","foo")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.get(\"file\") == \"foo\"")})(((await $b.get("file")) === "foo"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: 12 == x")})((12 === $x))}; } } return $Closure1; @@ -202,16 +200,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); - const x_client = context._lift(x); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, - x: ${x_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, + $x: ${context._lift(x)}, }) `); } @@ -227,10 +222,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - $Closure1._registerBindObject(x, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["get", "put"]); $Closure1._registerBindObject(x, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/capture_mutables.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/capture_mutables.w_compile_tf-aws.md index cb59acf103e..14b36662975 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/capture_mutables.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/capture_mutables.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ a, s, m, aCloned }) { +module.exports = function({ $Object_keys_m__length, $aCloned_length, $a_length, $s_size }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: a.length == 1")})((a.length === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: s.size == 1")})((s.size === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: m.size() == 1")})((Object.keys(m).length === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: aCloned.length == 1")})((aCloned.length === 1))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: a.length == 1")})(($a_length === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: s.size == 1")})(($s_size === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: m.size() == 1")})(($Object_keys_m__length === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: aCloned.length == 1")})(($aCloned_length === 1))}; } } return $Closure1; @@ -25,17 +23,15 @@ module.exports = function({ a, s, m, aCloned }) { ## inflight.$Closure2.js ```js -module.exports = function({ handler }) { +module.exports = function({ $handler }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await handler()); + async handle() { + (await $handler()); } } return $Closure2; @@ -178,20 +174,15 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const a_client = context._lift(a); - const s_client = context._lift(s); - const m_client = context._lift(m); - const aCloned_client = context._lift(aCloned); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - a: ${a_client}, - s: ${s_client}, - m: ${m_client}, - aCloned: ${aCloned_client}, + require("./inflight.$Closure1.js")({ + $Object_keys_m__length: ${context._lift(Object.keys(m).length)}, + $aCloned_length: ${context._lift(aCloned.length)}, + $a_length: ${context._lift(a.length)}, + $s_size: ${context._lift(s.size)}, }) `); } @@ -207,17 +198,11 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(a, host, []); - $Closure1._registerBindObject(aCloned, host, []); - $Closure1._registerBindObject(m, host, []); - $Closure1._registerBindObject(s, host, []); - } if (ops.includes("handle")) { - $Closure1._registerBindObject(a, host, ["length"]); - $Closure1._registerBindObject(aCloned, host, ["length"]); - $Closure1._registerBindObject(m, host, ["size"]); - $Closure1._registerBindObject(s, host, ["size"]); + $Closure1._registerBindObject(Object.keys(m).length, host, []); + $Closure1._registerBindObject(aCloned.length, host, []); + $Closure1._registerBindObject(a.length, host, []); + $Closure1._registerBindObject(s.size, host, []); } super._registerBind(host, ops); } @@ -226,14 +211,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const handler_client = context._lift(handler); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - handler: ${handler_client}, + require("./inflight.$Closure2.js")({ + $handler: ${context._lift(handler)}, }) `); } @@ -249,9 +232,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(handler, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(handler, host, ["handle"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/capture_primitives.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/capture_primitives.w_compile_tf-aws.md index 3bbc931e32f..054c966454d 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/capture_primitives.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/capture_primitives.w_compile_tf-aws.md @@ -2,29 +2,27 @@ ## inflight.$Closure1.js ```js -module.exports = function({ myStr, myNum, mySecondBool, myBool, myDur }) { +module.exports = function({ $myBool, $myDur_hours, $myDur_minutes, $myDur_seconds, $myNum, $mySecondBool, $myStr }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(s) { - {console.log(myStr)}; - const n = myNum; + async handle(s) { + {console.log($myStr)}; + const n = $myNum; {console.log(String.raw({ raw: ["", ""] }, n))}; - {((cond) => {if (!cond) throw new Error("assertion failed: mySecondBool == false")})((mySecondBool === false))}; - if (myBool) { + {((cond) => {if (!cond) throw new Error("assertion failed: mySecondBool == false")})(($mySecondBool === false))}; + if ($myBool) { {console.log("bool=true")}; } else { {console.log("bool=false")}; } - const min = myDur.minutes; - const sec = myDur.seconds; - const hr = myDur.hours; + const min = $myDur_minutes; + const sec = $myDur_seconds; + const hr = $myDur_hours; const split = (await String.raw({ raw: ["min=", " sec=", " hr=", ""] }, min, sec, hr).split(" ")); {((cond) => {if (!cond) throw new Error("assertion failed: split.length == 3")})((split.length === 3))}; } @@ -170,22 +168,18 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const myStr_client = context._lift(myStr); - const myNum_client = context._lift(myNum); - const mySecondBool_client = context._lift(mySecondBool); - const myBool_client = context._lift(myBool); - const myDur_client = context._lift(myDur); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - myStr: ${myStr_client}, - myNum: ${myNum_client}, - mySecondBool: ${mySecondBool_client}, - myBool: ${myBool_client}, - myDur: ${myDur_client}, + require("./inflight.$Closure1.js")({ + $myBool: ${context._lift(myBool)}, + $myDur_hours: ${context._lift(myDur.hours)}, + $myDur_minutes: ${context._lift(myDur.minutes)}, + $myDur_seconds: ${context._lift(myDur.seconds)}, + $myNum: ${context._lift(myNum)}, + $mySecondBool: ${context._lift(mySecondBool)}, + $myStr: ${context._lift(myStr)}, }) `); } @@ -201,16 +195,11 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(myBool, host, []); - $Closure1._registerBindObject(myDur, host, []); - $Closure1._registerBindObject(myNum, host, []); - $Closure1._registerBindObject(mySecondBool, host, []); - $Closure1._registerBindObject(myStr, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(myBool, host, []); - $Closure1._registerBindObject(myDur, host, []); + $Closure1._registerBindObject(myDur.hours, host, []); + $Closure1._registerBindObject(myDur.minutes, host, []); + $Closure1._registerBindObject(myDur.seconds, host, []); $Closure1._registerBindObject(myNum, host, []); $Closure1._registerBindObject(mySecondBool, host, []); $Closure1._registerBindObject(myStr, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/capture_reassigable_class_field.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/capture_reassigable_class_field.w_compile_tf-aws.md index c10058e7ad3..c1250ac05b3 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/capture_reassigable_class_field.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/capture_reassigable_class_field.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(k) { + async handle(k) { } } return $Closure1; @@ -21,17 +19,15 @@ module.exports = function({ }) { ## inflight.$Closure2.js ```js -module.exports = function({ counter }) { +module.exports = function({ $counter }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(key) { - (await counter.inc(1,key)); + async handle(key) { + (await $counter.inc(1,key)); } } return $Closure2; @@ -41,27 +37,25 @@ module.exports = function({ counter }) { ## inflight.$Closure3.js ```js -module.exports = function({ kv, counter, util_Util }) { +module.exports = function({ $counter, $kv, $util_Util }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await kv.set("k",Object.freeze({"value":"v"}))); - (await kv.set("k2",Object.freeze({"value":"v"}))); - (await kv.get("k")); - (await kv.get("k")); - (await kv.get("k2")); - {((cond) => {if (!cond) throw new Error("assertion failed: util.waitUntil((): bool => {\n return counter.peek(\"k\") == 2;\n })")})((await util_Util.waitUntil(async () => { - return ((await counter.peek("k")) === 2); + async handle() { + (await $kv.set("k",Object.freeze({"value":"v"}))); + (await $kv.set("k2",Object.freeze({"value":"v"}))); + (await $kv.get("k")); + (await $kv.get("k")); + (await $kv.get("k2")); + {((cond) => {if (!cond) throw new Error("assertion failed: util.waitUntil((): bool => {\n return counter.peek(\"k\") == 2;\n })")})((await $util_Util.waitUntil(async () => { + return ((await $counter.peek("k")) === 2); } )))}; - {((cond) => {if (!cond) throw new Error("assertion failed: util.waitUntil((): bool => {\n return counter.peek(\"k2\") == 1;\n })")})((await util_Util.waitUntil(async () => { - return ((await counter.peek("k2")) === 1); + {((cond) => {if (!cond) throw new Error("assertion failed: util.waitUntil((): bool => {\n return counter.peek(\"k2\") == 1;\n })")})((await $util_Util.waitUntil(async () => { + return ((await $counter.peek("k2")) === 1); } )))}; } @@ -75,18 +69,16 @@ module.exports = function({ kv, counter, util_Util }) { ```js module.exports = function({ }) { class KeyValueStore { - constructor({ bucket, onUpdateCallback }) { - this.bucket = bucket; - this.onUpdateCallback = onUpdateCallback; + constructor({ $this_bucket, $this_onUpdateCallback }) { + this.$this_bucket = $this_bucket; + this.$this_onUpdateCallback = $this_onUpdateCallback; } - async $inflight_init() { + async get(key) { + (await this.$this_onUpdateCallback(key)); + return (await this.$this_bucket.getJson(key)); } - async get(key) { - (await this.onUpdateCallback(key)); - return (await this.bucket.getJson(key)); - } - async set(key, value) { - (await this.bucket.putJson(key,value)); + async set(key, value) { + (await this.$this_bucket.putJson(key,value)); } } return KeyValueStore; @@ -300,12 +292,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -320,36 +311,26 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } this.onUpdateCallback = new $Closure1(this,"$Closure1"); - this._addInflightOps("get", "set"); + this._addInflightOps("get", "set", "$inflight_init"); } - onUpdate(fn) { + onUpdate(fn) { this.onUpdateCallback = fn; } static _toInflightType(context) { - const self_client_path = "././inflight.KeyValueStore.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.KeyValueStore.js")({ }) `); } _toInflight() { - const bucket_client = this._lift(this.bucket); - const onUpdateCallback_client = this._lift(this.onUpdateCallback); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const KeyValueStoreClient = ${KeyValueStore._toInflightType(this).text}; const client = new KeyValueStoreClient({ - bucket: ${bucket_client}, - onUpdateCallback: ${onUpdateCallback_client}, + $this_bucket: ${this._lift(this.bucket)}, + $this_onUpdateCallback: ${this._lift(this.onUpdateCallback)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -357,10 +338,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - KeyValueStore._registerBindObject(this.bucket, host, []); - KeyValueStore._registerBindObject(this.onUpdateCallback, host, []); - } if (ops.includes("get")) { KeyValueStore._registerBindObject(this.bucket, host, ["getJson"]); KeyValueStore._registerBindObject(this.onUpdateCallback, host, ["handle"]); @@ -375,14 +352,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const counter_client = context._lift(counter); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counter: ${counter_client}, + require("./inflight.$Closure2.js")({ + $counter: ${context._lift(counter)}, }) `); } @@ -398,9 +373,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(counter, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(counter, host, ["inc"]); } @@ -411,18 +383,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const kv_client = context._lift(kv); - const counter_client = context._lift(counter); - const util_UtilClient = util.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - kv: ${kv_client}, - counter: ${counter_client}, - util_Util: ${util_UtilClient.text}, + require("./inflight.$Closure3.js")({ + $counter: ${context._lift(counter)}, + $kv: ${context._lift(kv)}, + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -438,10 +406,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(counter, host, []); - $Closure3._registerBindObject(kv, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(counter, host, ["peek"]); $Closure3._registerBindObject(kv, host, ["get", "set"]); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/capture_reassignable.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/capture_reassignable.w_compile_tf-aws.md index 9c36c12edf1..3f52b31ba62 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/capture_reassignable.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/capture_reassignable.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ x }) { +module.exports = function({ $x }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: x == 5")})((x === 5))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: x == 5")})(($x === 5))}; } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ x }) { ## inflight.$Closure2.js ```js -module.exports = function({ handler }) { +module.exports = function({ $handler }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await handler()); + async handle() { + (await $handler()); } } return $Closure2; @@ -176,14 +172,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const x_client = context._lift(x); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - x: ${x_client}, + require("./inflight.$Closure1.js")({ + $x: ${context._lift(x)}, }) `); } @@ -199,9 +193,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(x, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(x, host, []); } @@ -212,14 +203,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const handler_client = context._lift(handler); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - handler: ${handler_client}, + require("./inflight.$Closure2.js")({ + $handler: ${context._lift(handler)}, }) `); } @@ -235,9 +224,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(handler, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(handler, host, ["handle"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/capture_resource_and_data.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/capture_resource_and_data.w_compile_tf-aws.md index 1e62ee3e061..c955dfc7076 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/capture_resource_and_data.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/capture_resource_and_data.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ data, res, queue }) { +module.exports = function({ $data_size, $queue, $res }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: data.size == 3")})((data.size === 3))}; - (await res.put("file.txt","world")); - {((cond) => {if (!cond) throw new Error("assertion failed: res.get(\"file.txt\") == \"world\"")})(((await res.get("file.txt")) === "world"))}; - (await queue.push("spirulina")); + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: data.size == 3")})(($data_size === 3))}; + (await $res.put("file.txt","world")); + {((cond) => {if (!cond) throw new Error("assertion failed: res.get(\"file.txt\") == \"world\"")})(((await $res.get("file.txt")) === "world"))}; + (await $queue.push("spirulina")); } } return $Closure1; @@ -215,18 +213,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const data_client = context._lift(data); - const res_client = context._lift(res); - const queue_client = context._lift(queue); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - data: ${data_client}, - res: ${res_client}, - queue: ${queue_client}, + require("./inflight.$Closure1.js")({ + $data_size: ${context._lift(data.size)}, + $queue: ${context._lift(queue)}, + $res: ${context._lift(res)}, }) `); } @@ -242,13 +236,8 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(data, host, []); - $Closure1._registerBindObject(queue, host, []); - $Closure1._registerBindObject(res, host, []); - } if (ops.includes("handle")) { - $Closure1._registerBindObject(data, host, ["size"]); + $Closure1._registerBindObject(data.size, host, []); $Closure1._registerBindObject(queue, host, ["push"]); $Closure1._registerBindObject(res, host, ["get", "put"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/capture_resource_with_no_inflight.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/capture_resource_with_no_inflight.w_compile_tf-aws.md index 4cb0e03e326..7d657d38b6e 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/capture_resource_with_no_inflight.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/capture_resource_with_no_inflight.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ a }) { +module.exports = function({ $a_field }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: \"hey\" == a.field")})(("hey" === a.field))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: \"hey\" == a.field")})(("hey" === $a_field))}; } } return $Closure1; @@ -24,10 +22,7 @@ module.exports = function({ a }) { ```js module.exports = function({ }) { class A { - constructor({ field }) { - this.field = field; - } - async $inflight_init() { + constructor({ }) { } } return A; @@ -171,46 +166,36 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.field = "hey"; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.A.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.A.js")({ }) `); } _toInflight() { - const field_client = this._lift(this.field); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const AClient = ${A._toInflightType(this).text}; const client = new AClient({ - field: ${field_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - A._registerBindObject(this.field, host, []); - } - super._registerBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const a_client = context._lift(a); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - a: ${a_client}, + require("./inflight.$Closure1.js")({ + $a_field: ${context._lift(a.field)}, }) `); } @@ -226,9 +211,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(a, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(a.field, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/capture_tokens.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/capture_tokens.w_compile_tf-aws.md index d8970868f88..15fdd14e084 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/capture_tokens.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/capture_tokens.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ r }) { +module.exports = function({ $r }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await r.foo()); + async handle() { + (await $r.foo()); } } return $Closure1; @@ -22,18 +20,16 @@ module.exports = function({ r }) { ## inflight.$Closure2.js ```js -module.exports = function({ url, api, MyResource }) { +module.exports = function({ $MyResource, $api_url, $url }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: MyResource.isValidUrl(url)")})((await MyResource.isValidUrl(url)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: MyResource.isValidUrl(api.url)")})((await MyResource.isValidUrl(api.url)))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: MyResource.isValidUrl(url)")})((await $MyResource.isValidUrl($url)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: MyResource.isValidUrl(api.url)")})((await $MyResource.isValidUrl($api_url)))}; } } return $Closure2; @@ -45,18 +41,16 @@ module.exports = function({ url, api, MyResource }) { ```js module.exports = function({ }) { class MyResource { - constructor({ api, url }) { - this.api = api; - this.url = url; - } - async $inflight_init() { + constructor({ $this_api_url, $this_url }) { + this.$this_api_url = $this_api_url; + this.$this_url = $this_url; } - static async isValidUrl(url) { + static async isValidUrl(url) { return (require("/url_utils.js")["isValidUrl"])(url) } - async foo() { - {((cond) => {if (!cond) throw new Error("assertion failed: MyResource.isValidUrl(this.url)")})((await MyResource.isValidUrl(this.url)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: MyResource.isValidUrl(this.api.url)")})((await MyResource.isValidUrl(this.api.url)))}; + async foo() { + {((cond) => {if (!cond) throw new Error("assertion failed: MyResource.isValidUrl(this.url)")})((await MyResource.isValidUrl(this.$this_url)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: MyResource.isValidUrl(this.api.url)")})((await MyResource.isValidUrl(this.$this_api_url)))}; } } return MyResource; @@ -258,11 +252,10 @@ module.exports = function({ }) { }, "environment": { "variables": { - "CLOUD_API_C8DACDCC": "${aws_api_gateway_stage.MyResource_cloudApi_api_stage_A26656F9.invoke_url}", "WING_FUNCTION_NAME": "Handler-c8ed8f29", "WING_TARGET": "tf-aws", - "WING_TOKEN_TFTOKEN_TOKEN_10": "${jsonencode(aws_api_gateway_stage.MyResource_cloudApi_api_stage_A26656F9.invoke_url)}", - "WING_TOKEN_TFTOKEN_TOKEN_7": "${jsonencode(aws_api_gateway_stage.MyResource_cloudApi_api_stage_A26656F9.invoke_url)}" + "WING_TOKEN_TFTOKEN_TOKEN_7": "${jsonencode(aws_api_gateway_stage.MyResource_cloudApi_api_stage_A26656F9.invoke_url)}", + "WING_TOKEN_TFTOKEN_TOKEN_8": "${jsonencode(aws_api_gateway_stage.MyResource_cloudApi_api_stage_A26656F9.invoke_url)}" } }, "function_name": "Handler-c8ed8f29", @@ -287,11 +280,10 @@ module.exports = function({ }) { }, "environment": { "variables": { - "CLOUD_API_C82DF3A5": "${aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url}", "WING_FUNCTION_NAME": "Handler-c8ecc6d5", "WING_TARGET": "tf-aws", - "WING_TOKEN_TFTOKEN_TOKEN_31": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}", - "WING_TOKEN_TFTOKEN_TOKEN_33": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" + "WING_TOKEN_TFTOKEN_TOKEN_30": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}", + "WING_TOKEN_TFTOKEN_TOKEN_31": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" } }, "function_name": "Handler-c8ecc6d5", @@ -363,24 +355,21 @@ class $Root extends $stdlib.std.Resource { super(scope, id); this.api = this.node.root.newAbstract("@winglang/sdk.cloud.Api",this,"cloud.Api"); this.url = this.api.url; - this._addInflightOps("isValidUrl", "foo"); + this._addInflightOps("isValidUrl", "foo", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.MyResource.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.MyResource.js")({ }) `); } _toInflight() { - const api_client = this._lift(this.api); - const url_client = this._lift(this.url); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const MyResourceClient = ${MyResource._toInflightType(this).text}; const client = new MyResourceClient({ - api: ${api_client}, - url: ${url_client}, + $this_api_url: ${this._lift(this.api.url)}, + $this_url: ${this._lift(this.url)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -388,35 +377,23 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - MyResource._registerBindObject(this.api, host, []); - MyResource._registerBindObject(this.url, host, []); - } if (ops.includes("foo")) { - MyResource._registerBindObject(MyResource, host, ["isValidUrl"]); MyResource._registerBindObject(this.api.url, host, []); MyResource._registerBindObject(this.url, host, []); } super._registerBind(host, ops); } - static _registerTypeBind(host, ops) { - if (ops.includes("isValidUrl")) { - } - super._registerTypeBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const r_client = context._lift(r); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - r: ${r_client}, + require("./inflight.$Closure1.js")({ + $r: ${context._lift(r)}, }) `); } @@ -432,9 +409,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(r, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(r, host, ["foo"]); } @@ -445,18 +419,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const url_client = context._lift(url); - const api_client = context._lift(api); - const MyResourceClient = MyResource._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - url: ${url_client}, - api: ${api_client}, - MyResource: ${MyResourceClient.text}, + require("./inflight.$Closure2.js")({ + $MyResource: ${context._lift(MyResource)}, + $api_url: ${context._lift(api.url)}, + $url: ${context._lift(url)}, }) `); } @@ -472,10 +442,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(api, host, []); - $Closure2._registerBindObject(url, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(MyResource, host, ["isValidUrl"]); $Closure2._registerBindObject(api.url, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/captures.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/captures.w_compile_tf-aws.md index d57f6942426..5e005cb108f 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/captures.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/captures.w_compile_tf-aws.md @@ -2,26 +2,24 @@ ## inflight.$Closure1.js ```js -module.exports = function({ bucket1, bucket2, bucket3 }) { +module.exports = function({ $bucket1, $bucket2, $bucket3 }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(event) { - (await bucket1.put("file.txt","data")); - (await bucket2.get("file.txt")); - (await bucket2.get("file2.txt")); - (await bucket3.get("file3.txt")); - for (const stuff of (await bucket1.list())) { + async handle(event) { + (await $bucket1.put("file.txt","data")); + (await $bucket2.get("file.txt")); + (await $bucket2.get("file2.txt")); + (await $bucket3.get("file3.txt")); + for (const stuff of (await $bucket1.list())) { {console.log(stuff)}; } - {console.log((await bucket2.publicUrl("file.txt")))}; + {console.log((await $bucket2.publicUrl("file.txt")))}; try { - (await bucket1.publicUrl("file.txt")); + (await $bucket1.publicUrl("file.txt")); } catch ($error_error) { const error = $error_error.message; @@ -468,18 +466,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const bucket1_client = context._lift(bucket1); - const bucket2_client = context._lift(bucket2); - const bucket3_client = context._lift(bucket3); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - bucket1: ${bucket1_client}, - bucket2: ${bucket2_client}, - bucket3: ${bucket3_client}, + require("./inflight.$Closure1.js")({ + $bucket1: ${context._lift(bucket1)}, + $bucket2: ${context._lift(bucket2)}, + $bucket3: ${context._lift(bucket3)}, }) `); } @@ -495,11 +489,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(bucket1, host, []); - $Closure1._registerBindObject(bucket2, host, []); - $Closure1._registerBindObject(bucket3, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(bucket1, host, ["list", "publicUrl", "put"]); $Closure1._registerBindObject(bucket2, host, ["get", "publicUrl"]); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/class.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/class.w_compile_tf-aws.md index 240174e134c..c385d557c12 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/class.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/class.w_compile_tf-aws.md @@ -2,20 +2,18 @@ ## inflight.$Closure1.js ```js -module.exports = function({ c5 }) { +module.exports = function({ $c5 }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: c5.x == 123")})((c5.x === 123))}; - {((cond) => {if (!cond) throw new Error("assertion failed: c5.y == 321")})((c5.y === 321))}; - (await c5.set(111)); - {((cond) => {if (!cond) throw new Error("assertion failed: c5.y == 111")})((c5.y === 111))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: c5.x == 123")})(($c5.x === 123))}; + {((cond) => {if (!cond) throw new Error("assertion failed: c5.y == 321")})(($c5.y === 321))}; + (await $c5.set(111)); + {((cond) => {if (!cond) throw new Error("assertion failed: c5.y == 111")})(($c5.y === 111))}; } } return $Closure1; @@ -25,19 +23,17 @@ module.exports = function({ c5 }) { ## inflight.$Closure2.js ```js -module.exports = function({ student }) { +module.exports = function({ $student_hrlyWage, $student_major, $student_name }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: student.name == \"Tom\"")})((student.name === "Tom"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: student.major == \"MySpace\"")})((student.major === "MySpace"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: student.hrlyWage == 38")})((student.hrlyWage === 38))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: student.name == \"Tom\"")})(($student_name === "Tom"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: student.major == \"MySpace\"")})(($student_major === "MySpace"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: student.hrlyWage == 38")})(($student_hrlyWage === 38))}; } } return $Closure2; @@ -47,17 +43,15 @@ module.exports = function({ student }) { ## inflight.$Closure3.js ```js -module.exports = function({ ta }) { +module.exports = function({ $ta_hrlyWage }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: ta.hrlyWage == 10")})((ta.hrlyWage === 10))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: ta.hrlyWage == 10")})(($ta_hrlyWage === 10))}; } } return $Closure3; @@ -67,17 +61,15 @@ module.exports = function({ ta }) { ## inflight.$Closure4.js ```js -module.exports = function({ B }) { +module.exports = function({ $B }) { class $Closure4 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const b = new B("ba"); + async handle() { + const b = new $B("ba"); {((cond) => {if (!cond) throw new Error("assertion failed: b.sound == \"ba\"")})((b.sound === "ba"))}; } } @@ -90,7 +82,7 @@ module.exports = function({ B }) { ```js module.exports = function({ }) { class A { - constructor(sound) { + constructor(sound) { this.sound = sound; } } @@ -101,9 +93,9 @@ module.exports = function({ }) { ## inflight.B.js ```js -module.exports = function({ A }) { - class B extends A { - constructor(sound) { +module.exports = function({ $A }) { + class B extends $A { + constructor(sound) { super(sound); } } @@ -114,12 +106,10 @@ module.exports = function({ A }) { ## inflight.Bam.js ```js -module.exports = function({ Boom }) { - class Bam extends Boom { +module.exports = function({ $Boom }) { + class Bam extends $Boom { constructor({ }) { - super({}); - } - async $inflight_init() { + super({ }); } } return Bam; @@ -133,8 +123,6 @@ module.exports = function({ }) { class Bar { constructor({ }) { } - async $inflight_init() { - } } return Bar; } @@ -143,12 +131,10 @@ module.exports = function({ }) { ## inflight.Baz.js ```js -module.exports = function({ Bar }) { - class Baz extends Bar { +module.exports = function({ $Bar }) { + class Baz extends $Bar { constructor({ }) { - super({}); - } - async $inflight_init() { + super({ }); } } return Baz; @@ -162,8 +148,6 @@ module.exports = function({ }) { class Boom { constructor({ }) { } - async $inflight_init() { - } } return Boom; } @@ -176,8 +160,6 @@ module.exports = function({ }) { class C1 { constructor({ }) { } - async $inflight_init() { - } } return C1; } @@ -188,10 +170,7 @@ module.exports = function({ }) { ```js module.exports = function({ }) { class C2 { - constructor({ x }) { - this.x = x; - } - async $inflight_init() { + constructor({ }) { } } return C2; @@ -203,11 +182,7 @@ module.exports = function({ }) { ```js module.exports = function({ }) { class C3 { - constructor({ x, y }) { - this.x = x; - this.y = y; - } - async $inflight_init() { + constructor({ }) { } } return C3; @@ -221,8 +196,6 @@ module.exports = function({ }) { class C4 { constructor({ }) { } - async $inflight_init() { - } } return C4; } @@ -235,13 +208,13 @@ module.exports = function({ }) { class C5 { constructor({ }) { } - async $inflight_init() { + async set(b) { + this.y = b; + } + async $inflight_init() { this.x = 123; this.y = 321; } - async set(b) { - this.y = b; - } } return C5; } @@ -250,14 +223,12 @@ module.exports = function({ }) { ## inflight.Foo.js ```js -module.exports = function({ Bar }) { - class Foo extends Bar { +module.exports = function({ $Bar }) { + class Foo extends $Bar { constructor({ }) { - super({}); + super({ }); } - async $inflight_init() { - } - async doStuff(h) { + async doStuff(h) { } } return Foo; @@ -267,13 +238,10 @@ module.exports = function({ Bar }) { ## inflight.PaidStudent.js ```js -module.exports = function({ Student }) { - class PaidStudent extends Student { - constructor({ hrlyWage, major, name }) { - super({major, name}); - this.hrlyWage = hrlyWage; - } - async $inflight_init() { +module.exports = function({ $Student }) { + class PaidStudent extends $Student { + constructor({ }) { + super({ }); } } return PaidStudent; @@ -285,10 +253,7 @@ module.exports = function({ Student }) { ```js module.exports = function({ }) { class Person { - constructor({ name }) { - this.name = name; - } - async $inflight_init() { + constructor({ }) { } } return Person; @@ -298,13 +263,10 @@ module.exports = function({ }) { ## inflight.Student.js ```js -module.exports = function({ Person }) { - class Student extends Person { - constructor({ major, name }) { - super({name}); - this.major = major; - } - async $inflight_init() { +module.exports = function({ $Person }) { + class Student extends $Person { + constructor({ }) { + super({ }); } } return Student; @@ -314,12 +276,10 @@ module.exports = function({ Person }) { ## inflight.TeacherAid.js ```js -module.exports = function({ PaidStudent }) { - class TeacherAid extends PaidStudent { - constructor({ hrlyWage, major, name }) { - super({hrlyWage, major, name}); - } - async $inflight_init() { +module.exports = function({ $PaidStudent }) { + class TeacherAid extends $PaidStudent { + constructor({ }) { + super({ }); } } return TeacherAid; @@ -660,11 +620,11 @@ class $Root extends $stdlib.std.Resource { class C1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.C1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.C1.js")({ }) `); } @@ -679,43 +639,30 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } class C2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.x = 1; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.C2.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.C2.js")({ }) `); } _toInflight() { - const x_client = this._lift(this.x); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const C2Client = ${C2._toInflightType(this).text}; const client = new C2Client({ - x: ${x_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - C2._registerBindObject(this.x, host, []); - } - super._registerBind(host, ops); - } } class C3 extends $stdlib.std.Resource { constructor(scope, id, a, b) { @@ -724,48 +671,37 @@ class $Root extends $stdlib.std.Resource { if (true) { this.y = b; } + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.C3.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.C3.js")({ }) `); } _toInflight() { - const x_client = this._lift(this.x); - const y_client = this._lift(this.y); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const C3Client = ${C3._toInflightType(this).text}; const client = new C3Client({ - x: ${x_client}, - y: ${y_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - C3._registerBindObject(this.x, host, []); - C3._registerBindObject(this.y, host, []); - } - super._registerBind(host, ops); - } } class C4 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } - static m() { + static m() { return 1; } static _toInflightType(context) { - const self_client_path = "././inflight.C4.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.C4.js")({ }) `); } @@ -780,21 +716,15 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } class C5 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("set", "x", "y"); + this._addInflightOps("set", "$inflight_init", "x", "y"); } static _toInflightType(context) { - const self_client_path = "././inflight.C5.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.C5.js")({ }) `); } @@ -811,8 +741,10 @@ class $Root extends $stdlib.std.Resource { } _registerBind(host, ops) { if (ops.includes("$inflight_init")) { + C5._registerBindObject(this, host, ["x", "y"]); } if (ops.includes("set")) { + C5._registerBindObject(this, host, ["y"]); } super._registerBind(host, ops); } @@ -821,14 +753,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const c5_client = context._lift(c5); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - c5: ${c5_client}, + require("./inflight.$Closure1.js")({ + $c5: ${context._lift(c5)}, }) `); } @@ -844,9 +774,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(c5, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(c5, host, ["set", "x", "y"]); } @@ -857,123 +784,88 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, name) { super(scope, id); this.name = name; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Person.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Person.js")({ }) `); } _toInflight() { - const name_client = this._lift(this.name); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const PersonClient = ${Person._toInflightType(this).text}; const client = new PersonClient({ - name: ${name_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Person._registerBindObject(this.name, host, []); - } - super._registerBind(host, ops); - } } class Student extends Person { constructor(scope, id, name, major) { super(scope,id,name); this.major = major; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Student.js"; - const PersonClient = Person._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Person: ${PersonClient.text}, + require("./inflight.Student.js")({ + $Person: ${context._lift(Person)}, }) `); } _toInflight() { - const major_client = this._lift(this.major); - const name_client = this._lift(this.name); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const StudentClient = ${Student._toInflightType(this).text}; const client = new StudentClient({ - major: ${major_client}, - name: ${name_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Student._registerBindObject(this.major, host, []); - Student._registerBindObject(this.name, host, []); - } - super._registerBind(host, ops); - } } class PaidStudent extends Student { constructor(scope, id, name, major, hrlyWage) { super(scope,id,name,major); this.hrlyWage = hrlyWage; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.PaidStudent.js"; - const StudentClient = Student._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Student: ${StudentClient.text}, + require("./inflight.PaidStudent.js")({ + $Student: ${context._lift(Student)}, }) `); } _toInflight() { - const hrlyWage_client = this._lift(this.hrlyWage); - const major_client = this._lift(this.major); - const name_client = this._lift(this.name); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const PaidStudentClient = ${PaidStudent._toInflightType(this).text}; const client = new PaidStudentClient({ - hrlyWage: ${hrlyWage_client}, - major: ${major_client}, - name: ${name_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - PaidStudent._registerBindObject(this.hrlyWage, host, []); - PaidStudent._registerBindObject(this.major, host, []); - PaidStudent._registerBindObject(this.name, host, []); - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const student_client = context._lift(student); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - student: ${student_client}, + require("./inflight.$Closure2.js")({ + $student_hrlyWage: ${context._lift(student.hrlyWage)}, + $student_major: ${context._lift(student.major)}, + $student_name: ${context._lift(student.name)}, }) `); } @@ -989,9 +881,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(student, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(student.hrlyWage, host, []); $Closure2._registerBindObject(student.major, host, []); @@ -1004,54 +893,37 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, name, major, hrlyWage) { super(scope,id,name,major,hrlyWage); this.hrlyWage = 10; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.TeacherAid.js"; - const PaidStudentClient = PaidStudent._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - PaidStudent: ${PaidStudentClient.text}, + require("./inflight.TeacherAid.js")({ + $PaidStudent: ${context._lift(PaidStudent)}, }) `); } _toInflight() { - const hrlyWage_client = this._lift(this.hrlyWage); - const major_client = this._lift(this.major); - const name_client = this._lift(this.name); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const TeacherAidClient = ${TeacherAid._toInflightType(this).text}; const client = new TeacherAidClient({ - hrlyWage: ${hrlyWage_client}, - major: ${major_client}, - name: ${name_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - TeacherAid._registerBindObject(this.hrlyWage, host, []); - TeacherAid._registerBindObject(this.major, host, []); - TeacherAid._registerBindObject(this.name, host, []); - } - super._registerBind(host, ops); - } } class $Closure3 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const ta_client = context._lift(ta); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - ta: ${ta_client}, + require("./inflight.$Closure3.js")({ + $ta_hrlyWage: ${context._lift(ta.hrlyWage)}, }) `); } @@ -1067,9 +939,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(ta, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(ta.hrlyWage, host, []); } @@ -1079,12 +948,11 @@ class $Root extends $stdlib.std.Resource { class A extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("sound"); + this._addInflightOps("$inflight_init", "sound"); } static _toInflightType(context) { - const self_client_path = "././inflight.A.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.A.js")({ }) `); } @@ -1101,6 +969,7 @@ class $Root extends $stdlib.std.Resource { } _registerBind(host, ops) { if (ops.includes("$inflight_init")) { + A._registerBindObject(this, host, ["sound"]); } super._registerBind(host, ops); } @@ -1108,13 +977,12 @@ class $Root extends $stdlib.std.Resource { class B extends A { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.B.js"; - const AClient = A._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - A: ${AClient.text}, + require("./inflight.B.js")({ + $A: ${context._lift(A)}, }) `); } @@ -1129,24 +997,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } class $Closure4 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; - const BClient = B._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - B: ${BClient.text}, + require("./inflight.$Closure4.js")({ + $B: ${context._lift(B)}, }) `); } @@ -1161,22 +1022,15 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class Bar extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Bar.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Bar.js")({ }) `); } @@ -1191,23 +1045,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } class Foo extends Bar { constructor(scope, id, ) { super(scope,id,); - this._addInflightOps("doStuff"); + this._addInflightOps("doStuff", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; - const BarClient = Bar._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Bar: ${BarClient.text}, + require("./inflight.Foo.js")({ + $Bar: ${context._lift(Bar)}, }) `); } @@ -1222,24 +1069,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("doStuff")) { - } - super._registerBind(host, ops); - } } class Baz extends Bar { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Baz.js"; - const BarClient = Bar._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Bar: ${BarClient.text}, + require("./inflight.Baz.js")({ + $Bar: ${context._lift(Bar)}, }) `); } @@ -1254,20 +1093,15 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } class Boom extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Boom.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Boom.js")({ }) `); } @@ -1282,22 +1116,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } class Bam extends Boom { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Bam.js"; - const BoomClient = Boom._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Boom: ${BoomClient.text}, + require("./inflight.Bam.js")({ + $Boom: ${context._lift(Boom)}, }) `); } @@ -1312,11 +1140,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } new C1(this,"C1"); const c2 = new C2(this,"C2"); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/closure_class.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/closure_class.w_compile_tf-aws.md new file mode 100644 index 00000000000..3cc72c78730 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/closure_class.w_compile_tf-aws.md @@ -0,0 +1,250 @@ +# [closure_class.w](../../../../../examples/tests/valid/closure_class.w) | compile | tf-aws + +## inflight.$Closure1.js +```js +module.exports = function({ $fn }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: fn() == 42")})(((await $fn()) === 42))}; + {((cond) => {if (!cond) throw new Error("assertion failed: fn.another() == \"hello\"")})(((await $fn.another()) === "hello"))}; + } + } + return $Closure1; +} + +``` + +## inflight.MyClosure.js +```js +module.exports = function({ }) { + class MyClosure { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async another() { + return "hello"; + } + async handle() { + return 42; + } + } + return MyClosure; +} + +``` + +## main.tf.json +```json +{ + "//": { + "metadata": { + "backend": "local", + "stackName": "root", + "version": "0.17.0" + }, + "outputs": { + "root": { + "Default": { + "cloud.TestRunner": { + "TestFunctionArns": "WING_TEST_RUNNER_FUNCTION_ARNS" + } + } + } + } + }, + "output": { + "WING_TEST_RUNNER_FUNCTION_ARNS": { + "value": "[[\"root/Default/Default/test:test\",\"${aws_lambda_function.testtest_Handler_295107CC.arn}\"]]" + } + }, + "provider": { + "aws": [ + {} + ] + }, + "resource": { + "aws_iam_role": { + "testtest_Handler_IamRole_15693C93": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRole", + "uniqueId": "testtest_Handler_IamRole_15693C93" + } + }, + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}" + } + }, + "aws_iam_role_policy": { + "testtest_Handler_IamRolePolicy_AF0279BD": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicy", + "uniqueId": "testtest_Handler_IamRolePolicy_AF0279BD" + } + }, + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"none:null\",\"Resource\":\"*\"}]}", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_iam_role_policy_attachment": { + "testtest_Handler_IamRolePolicyAttachment_ADF4752D": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicyAttachment", + "uniqueId": "testtest_Handler_IamRolePolicyAttachment_ADF4752D" + } + }, + "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_lambda_function": { + "testtest_Handler_295107CC": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/Default", + "uniqueId": "testtest_Handler_295107CC" + } + }, + "environment": { + "variables": { + "WING_FUNCTION_NAME": "Handler-c8f4f2a1", + "WING_TARGET": "tf-aws" + } + }, + "function_name": "Handler-c8f4f2a1", + "handler": "index.handler", + "publish": true, + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.arn}", + "runtime": "nodejs18.x", + "s3_bucket": "${aws_s3_bucket.Code.bucket}", + "s3_key": "${aws_s3_object.testtest_Handler_S3Object_9F4E28A7.key}", + "timeout": 30, + "vpc_config": { + "security_group_ids": [], + "subnet_ids": [] + } + } + }, + "aws_s3_bucket": { + "Code": { + "//": { + "metadata": { + "path": "root/Default/Code", + "uniqueId": "Code" + } + }, + "bucket_prefix": "code-c84a50b1-" + } + }, + "aws_s3_object": { + "testtest_Handler_S3Object_9F4E28A7": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/S3Object", + "uniqueId": "testtest_Handler_S3Object_9F4E28A7" + } + }, + "bucket": "${aws_s3_bucket.Code.bucket}", + "key": "", + "source": "" + } + } + } +} +``` + +## preflight.js +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyClosure extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("another", "handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyClosure.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyClosureClient = ${MyClosure._toInflightType(this).text}; + const client = new MyClosureClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $fn: ${context._lift(fn)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(fn, host, ["another", "handle"]); + } + super._registerBind(host, ops); + } + } + const fn = new MyClosure(this,"MyClosure"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "closure_class", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); + +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/closure_class.w_test_sim.md b/tools/hangar/__snapshots__/test_corpus/valid/closure_class.w_test_sim.md new file mode 100644 index 00000000000..5c1e6807402 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/closure_class.w_test_sim.md @@ -0,0 +1,12 @@ +# [closure_class.w](../../../../../examples/tests/valid/closure_class.w) | test | sim + +## stdout.log +```log +pass ─ closure_class.wsim » root/env0/test:test + + +Tests 1 passed (1) +Test Files 1 passed (1) +Duration +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/construct-base.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/construct-base.w_compile_tf-aws.md index 39758ae77d2..db423443d8d 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/construct-base.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/construct-base.w_compile_tf-aws.md @@ -6,8 +6,6 @@ module.exports = function({ }) { class WingResource { constructor({ }) { } - async $inflight_init() { - } } return WingResource; } @@ -75,11 +73,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); {console.log(String.raw({ raw: ["my id is ", ""] }, this.node.id))}; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.WingResource.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.WingResource.js")({ }) `); } @@ -94,20 +92,13 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } - const getPath = (c) => { + const getPath = ((c) => { return c.node.path; - } - ; - const getDisplayName = (r) => { + }); + const getDisplayName = ((r) => { return r.display.title; - } - ; + }); const q = this.node.root.new("@cdktf/provider-aws.sqsQueue.SqsQueue",aws.sqsQueue.SqsQueue,this,"aws.sqsQueue.SqsQueue"); const wr = new WingResource(this,"WingResource"); const another_resource = wr; diff --git a/tools/hangar/__snapshots__/test_corpus/valid/custom_obj_id.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/custom_obj_id.w_compile_tf-aws.md index 6d4dd6bba75..45a9c503597 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/custom_obj_id.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/custom_obj_id.w_compile_tf-aws.md @@ -6,8 +6,6 @@ module.exports = function({ }) { class Foo { constructor({ }) { } - async $inflight_init() { - } } return Foo; } @@ -59,11 +57,11 @@ class $Root extends $stdlib.std.Resource { class Foo extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } @@ -78,11 +76,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } const foo1 = new Foo(this,"Foo"); const bar2 = new Foo(this,"bar2"); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/debug_env.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/debug_env.w_compile_tf-aws.md index d5e74e044f4..e31f937865e 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/debug_env.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/debug_env.w_compile_tf-aws.md @@ -4,10 +4,7 @@ ```js module.exports = function({ }) { class A { - constructor({ b }) { - this.b = b; - } - async $inflight_init() { + constructor({ }) { } } return A; @@ -62,33 +59,25 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.A.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.A.js")({ }) `); } _toInflight() { - const b_client = this._lift(this.b); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const AClient = ${A._toInflightType(this).text}; const client = new AClient({ - b: ${b_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - A._registerBindObject(this.b, host, []); - } - super._registerBind(host, ops); - } } } } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/double_reference.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/double_reference.w_compile_tf-aws.md new file mode 100644 index 00000000000..8a4398df602 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/double_reference.w_compile_tf-aws.md @@ -0,0 +1,327 @@ +# [double_reference.w](../../../../../examples/tests/valid/double_reference.w) | compile | tf-aws + +## inflight.$Closure1.js +```js +module.exports = function({ $bar, $bar_foo, $initCount }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $bar.callFoo()); + (await $bar_foo.method()); + {((cond) => {if (!cond) throw new Error("assertion failed: initCount.peek() == /*1*/ 2")})(((await $initCount.peek()) === 2))}; + } + } + return $Closure1; +} + +``` + +## inflight.Bar.js +```js +module.exports = function({ }) { + class Bar { + constructor({ $this_foo }) { + this.$this_foo = $this_foo; + } + async callFoo() { + (await this.$this_foo.method()); + } + } + return Bar; +} + +``` + +## inflight.Foo.js +```js +module.exports = function({ $initCount }) { + class Foo { + constructor({ }) { + } + async method() { + } + async $inflight_init() { + (await $initCount.inc()); + } + } + return Foo; +} + +``` + +## main.tf.json +```json +{ + "//": { + "metadata": { + "backend": "local", + "stackName": "root", + "version": "0.17.0" + }, + "outputs": { + "root": { + "Default": { + "cloud.TestRunner": { + "TestFunctionArns": "WING_TEST_RUNNER_FUNCTION_ARNS" + } + } + } + } + }, + "output": { + "WING_TEST_RUNNER_FUNCTION_ARNS": { + "value": "[[\"root/Default/Default/test:hello\",\"${aws_lambda_function.testhello_Handler_549C38EE.arn}\"]]" + } + }, + "provider": { + "aws": [ + {} + ] + }, + "resource": { + "aws_dynamodb_table": { + "cloudCounter": { + "//": { + "metadata": { + "path": "root/Default/Default/cloud.Counter/Default", + "uniqueId": "cloudCounter" + } + }, + "attribute": [ + { + "name": "id", + "type": "S" + } + ], + "billing_mode": "PAY_PER_REQUEST", + "hash_key": "id", + "name": "wing-counter-cloud.Counter-c866f225" + } + }, + "aws_iam_role": { + "testhello_Handler_IamRole_84258FE3": { + "//": { + "metadata": { + "path": "root/Default/Default/test:hello/Handler/IamRole", + "uniqueId": "testhello_Handler_IamRole_84258FE3" + } + }, + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}" + } + }, + "aws_iam_role_policy": { + "testhello_Handler_IamRolePolicy_152A5EC1": { + "//": { + "metadata": { + "path": "root/Default/Default/test:hello/Handler/IamRolePolicy", + "uniqueId": "testhello_Handler_IamRolePolicy_152A5EC1" + } + }, + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"dynamodb:GetItem\"],\"Resource\":[\"${aws_dynamodb_table.cloudCounter.arn}\"],\"Effect\":\"Allow\"}]}", + "role": "${aws_iam_role.testhello_Handler_IamRole_84258FE3.name}" + } + }, + "aws_iam_role_policy_attachment": { + "testhello_Handler_IamRolePolicyAttachment_7372FC74": { + "//": { + "metadata": { + "path": "root/Default/Default/test:hello/Handler/IamRolePolicyAttachment", + "uniqueId": "testhello_Handler_IamRolePolicyAttachment_7372FC74" + } + }, + "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "role": "${aws_iam_role.testhello_Handler_IamRole_84258FE3.name}" + } + }, + "aws_lambda_function": { + "testhello_Handler_549C38EE": { + "//": { + "metadata": { + "path": "root/Default/Default/test:hello/Handler/Default", + "uniqueId": "testhello_Handler_549C38EE" + } + }, + "environment": { + "variables": { + "DYNAMODB_TABLE_NAME_49baa65c": "${aws_dynamodb_table.cloudCounter.name}", + "WING_FUNCTION_NAME": "Handler-c85df1b4", + "WING_TARGET": "tf-aws" + } + }, + "function_name": "Handler-c85df1b4", + "handler": "index.handler", + "publish": true, + "role": "${aws_iam_role.testhello_Handler_IamRole_84258FE3.arn}", + "runtime": "nodejs18.x", + "s3_bucket": "${aws_s3_bucket.Code.bucket}", + "s3_key": "${aws_s3_object.testhello_Handler_S3Object_CD1BAB13.key}", + "timeout": 30, + "vpc_config": { + "security_group_ids": [], + "subnet_ids": [] + } + } + }, + "aws_s3_bucket": { + "Code": { + "//": { + "metadata": { + "path": "root/Default/Code", + "uniqueId": "Code" + } + }, + "bucket_prefix": "code-c84a50b1-" + } + }, + "aws_s3_object": { + "testhello_Handler_S3Object_CD1BAB13": { + "//": { + "metadata": { + "path": "root/Default/Default/test:hello/Handler/S3Object", + "uniqueId": "testhello_Handler_S3Object_CD1BAB13" + } + }, + "bucket": "${aws_s3_bucket.Code.bucket}", + "key": "", + "source": "" + } + } + } +} +``` + +## preflight.js +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("method", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + $initCount: ${context._lift(initCount)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + Foo._registerBindObject(initCount, host, ["inc"]); + } + super._registerBind(host, ops); + } + } + class Bar extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.foo = new Foo(this,"Foo"); + this._addInflightOps("callFoo", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Bar.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const BarClient = ${Bar._toInflightType(this).text}; + const client = new BarClient({ + $this_foo: ${this._lift(this.foo)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("callFoo")) { + Bar._registerBindObject(this.foo, host, ["method"]); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $bar: ${context._lift(bar)}, + $bar_foo: ${context._lift(bar.foo)}, + $initCount: ${context._lift(initCount)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(bar, host, ["callFoo"]); + $Closure1._registerBindObject(bar.foo, host, ["method"]); + $Closure1._registerBindObject(initCount, host, ["peek"]); + } + super._registerBind(host, ops); + } + } + const initCount = this.node.root.newAbstract("@winglang/sdk.cloud.Counter",this,"cloud.Counter"); + const bar = new Bar(this,"Bar"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:hello",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "double_reference", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); + +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/double_reference.w_test_sim.md b/tools/hangar/__snapshots__/test_corpus/valid/double_reference.w_test_sim.md new file mode 100644 index 00000000000..500b70d4c4c --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/double_reference.w_test_sim.md @@ -0,0 +1,12 @@ +# [double_reference.w](../../../../../examples/tests/valid/double_reference.w) | test | sim + +## stdout.log +```log +pass ─ double_reference.wsim » root/env0/test:hello + + +Tests 1 passed (1) +Test Files 1 passed (1) +Duration +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/doubler.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/doubler.w_compile_tf-aws.md index 542c32914c5..89706589ab4 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/doubler.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/doubler.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(m) { + async handle(m) { return String.raw({ raw: ["Hello ", "!"] }, m); } } @@ -22,19 +20,17 @@ module.exports = function({ }) { ## inflight.$Closure2.js ```js -module.exports = function({ handler, std_Number, std_Json }) { +module.exports = function({ $handler, $std_Json, $std_Number }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(x) { + async handle(x) { const xStr = ((args) => { if (isNaN(args)) {throw new Error("unable to parse \"" + args + "\" as a number")}; return parseInt(args) })(x); - const y = (await handler(xStr)); - const z = (await handler(y)); + const y = (await $handler(xStr)); + const z = (await $handler(y)); return ((args) => { return JSON.stringify(args[0], null, args[1]) })([z]); } } @@ -52,9 +48,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(x) { + async handle(x) { return (x * 2); } } @@ -65,17 +59,15 @@ module.exports = function({ }) { ## inflight.$Closure4.js ```js -module.exports = function({ f }) { +module.exports = function({ $f }) { class $Closure4 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const result = (await f.invoke("2")); + async handle() { + const result = (await $f.invoke("2")); {((cond) => {if (!cond) throw new Error("assertion failed: result == \"8\"")})((result === "8"))}; } } @@ -88,14 +80,12 @@ module.exports = function({ f }) { ```js module.exports = function({ }) { class Doubler { - constructor({ func }) { - this.func = func; + constructor({ $this_func }) { + this.$this_func = $this_func; } - async $inflight_init() { - } - async invoke(message) { - (await this.func.handle(message)); - (await this.func.handle(message)); + async invoke(message) { + (await this.$this_func.handle(message)); + (await this.$this_func.handle(message)); } } return Doubler; @@ -109,8 +99,6 @@ module.exports = function({ }) { class Doubler2 { constructor({ }) { } - async $inflight_init() { - } } return Doubler2; } @@ -320,22 +308,20 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, func) { super(scope, id); this.func = func; - this._addInflightOps("invoke"); + this._addInflightOps("invoke", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Doubler.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Doubler.js")({ }) `); } _toInflight() { - const func_client = this._lift(this.func); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const DoublerClient = ${Doubler._toInflightType(this).text}; const client = new DoublerClient({ - func: ${func_client}, + $this_func: ${this._lift(this.func)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -343,9 +329,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Doubler._registerBindObject(this.func, host, []); - } if (ops.includes("invoke")) { Doubler._registerBindObject(this.func, host, ["handle"]); } @@ -356,12 +339,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -376,36 +358,26 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class Doubler2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } - makeFunc(handler) { + makeFunc(handler) { const __parent_this_2 = this; class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const handler_client = context._lift(handler); - const std_NumberClient = std.Number._toInflightType(context); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - handler: ${handler_client}, - std_Number: ${std_NumberClient.text}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure2.js")({ + $handler: ${context._lift(handler)}, + $std_Json: ${context._lift(std.Json)}, + $std_Number: ${context._lift(std.Number)}, }) `); } @@ -421,9 +393,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(handler, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(handler, host, ["handle"]); } @@ -433,9 +402,8 @@ class $Root extends $stdlib.std.Resource { return this.node.root.newAbstract("@winglang/sdk.cloud.Function",this,"cloud.Function",new $Closure2(this,"$Closure2")); } static _toInflightType(context) { - const self_client_path = "././inflight.Doubler2.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Doubler2.js")({ }) `); } @@ -450,22 +418,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } class $Closure3 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure3.js")({ }) `); } @@ -480,26 +442,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure4 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; - const f_client = context._lift(f); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - f: ${f_client}, + require("./inflight.$Closure4.js")({ + $f: ${context._lift(f)}, }) `); } @@ -515,9 +468,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure4._registerBindObject(f, host, []); - } if (ops.includes("handle")) { $Closure4._registerBindObject(f, host, ["invoke"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/enums.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/enums.w_compile_tf-aws.md index 334138b84fd..af2a6850474 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/enums.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/enums.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ one, two, SomeEnum }) { +module.exports = function({ $SomeEnum, $one, $two }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: one == SomeEnum.ONE")})((one === SomeEnum.ONE))}; - {((cond) => {if (!cond) throw new Error("assertion failed: two == SomeEnum.TWO")})((two === SomeEnum.TWO))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: one == SomeEnum.ONE")})(($one === $SomeEnum.ONE))}; + {((cond) => {if (!cond) throw new Error("assertion failed: two == SomeEnum.TWO")})(($two === $SomeEnum.TWO))}; } } return $Closure1; @@ -156,25 +154,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const one_client = context._lift(one); - const two_client = context._lift(two); - const SomeEnumClient = $stdlib.core.NodeJsCode.fromInline(` - Object.freeze((function (tmp) { - tmp[tmp["ONE"] = 0] = "ONE"; - tmp[tmp["TWO"] = 1] = "TWO"; - tmp[tmp["THREE"] = 2] = "THREE"; - return tmp; - })({})) - `); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - one: ${one_client}, - two: ${two_client}, - SomeEnum: ${SomeEnumClient.text}, + require("./inflight.$Closure1.js")({ + $SomeEnum: ${context._lift(SomeEnum)}, + $one: ${context._lift(one)}, + $two: ${context._lift(two)}, }) `); } @@ -190,10 +177,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(one, host, []); - $Closure1._registerBindObject(two, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(one, host, []); $Closure1._registerBindObject(two, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/extern_implementation.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/extern_implementation.w_compile_tf-aws.md index 765e712d457..66ed5445f6e 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/extern_implementation.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/extern_implementation.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ f }) { +module.exports = function({ $f }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await f.call()); + async handle() { + (await $f.call()); } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ f }) { ## inflight.$Closure2.js ```js -module.exports = function({ f }) { +module.exports = function({ $f }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await f.print("hey there")); + async handle() { + (await $f.print("hey there")); } } return $Closure2; @@ -46,21 +42,19 @@ module.exports = function({ }) { class Foo { constructor({ }) { } - async $inflight_init() { - } - static async regexInflight(pattern, text) { + static async regexInflight(pattern, text) { return (require("/external_js.js")["regexInflight"])(pattern, text) } - static async getUuid() { + static async getUuid() { return (require("/external_js.js")["getUuid"])() } - static async getData() { + static async getData() { return (require("/external_js.js")["getData"])() } - async print(msg) { + async print(msg) { return (require("/external_js.js")["print"])(msg) } - async call() { + async call() { {((cond) => {if (!cond) throw new Error("assertion failed: Foo.regexInflight(\"[a-z]+-\\\\d+\", \"abc-123\")")})((await Foo.regexInflight("[a-z]+-\\d+","abc-123")))}; const uuid = (await Foo.getUuid()); {((cond) => {if (!cond) throw new Error("assertion failed: uuid.length == 36")})((uuid.length === 36))}; @@ -273,18 +267,17 @@ class $Root extends $stdlib.std.Resource { class Foo extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("regexInflight", "getUuid", "getData", "print", "call"); + this._addInflightOps("regexInflight", "getUuid", "getData", "print", "call", "$inflight_init"); } - static getGreeting(name) { + static getGreeting(name) { return (require("/external_js.js")["getGreeting"])(name) } - static v4() { + static v4() { return (require("/index.js")["v4"])() } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } @@ -299,38 +292,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("call")) { - Foo._registerBindObject(Foo, host, ["getData", "getUuid", "regexInflight"]); - } - if (ops.includes("print")) { - } - super._registerBind(host, ops); - } - static _registerTypeBind(host, ops) { - if (ops.includes("getData")) { - } - if (ops.includes("getUuid")) { - } - if (ops.includes("regexInflight")) { - } - super._registerTypeBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const f_client = context._lift(f); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - f: ${f_client}, + require("./inflight.$Closure1.js")({ + $f: ${context._lift(f)}, }) `); } @@ -346,9 +318,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(f, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(f, host, ["call"]); } @@ -359,14 +328,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const f_client = context._lift(f); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - f: ${f_client}, + require("./inflight.$Closure2.js")({ + $f: ${context._lift(f)}, }) `); } @@ -382,9 +349,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(f, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(f, host, ["print"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/file_counter.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/file_counter.w_compile_tf-aws.md index bf89f6606c8..90ac3be1633 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/file_counter.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/file_counter.w_compile_tf-aws.md @@ -2,19 +2,17 @@ ## inflight.$Closure1.js ```js -module.exports = function({ counter, bucket }) { +module.exports = function({ $bucket, $counter }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(body) { - const next = (await counter.inc()); + async handle(body) { + const next = (await $counter.inc()); const key = String.raw({ raw: ["myfile-", ".txt"] }, "hi"); - (await bucket.put(key,body)); + (await $bucket.put(key,body)); } } return $Closure1; @@ -247,16 +245,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const counter_client = context._lift(counter); - const bucket_client = context._lift(bucket); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - counter: ${counter_client}, - bucket: ${bucket_client}, + require("./inflight.$Closure1.js")({ + $bucket: ${context._lift(bucket)}, + $counter: ${context._lift(counter)}, }) `); } @@ -272,10 +267,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(bucket, host, []); - $Closure1._registerBindObject(counter, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(bucket, host, ["put"]); $Closure1._registerBindObject(counter, host, ["inc"]); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/for_loop.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/for_loop.w_compile_tf-aws.md index 7bf2ad8597d..2acfa3ecd0d 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/for_loop.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/for_loop.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(event) { + async handle(event) { for (const x of ((s,e,i) => { function* iterator(start,end,inclusive) { let i = start; let limit = inclusive ? ((end < start) ? end - 1 : end + 1) : end; while (i < limit) yield i++; while (i > limit) yield i--; }; return iterator(s,e,i); })(0,10,false)) { {((cond) => {if (!cond) throw new Error("assertion failed: x <= 0")})((x <= 0))}; {((cond) => {if (!cond) throw new Error("assertion failed: x > 10")})((x > 10))}; @@ -30,9 +28,7 @@ module.exports = function({ }) { class Foo { constructor({ }) { } - async $inflight_init() { - } - async hello() { + async hello() { for (const p of Object.freeze(["hello"])) { {console.log(p)}; } @@ -179,12 +175,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -199,23 +194,15 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class Foo extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("hello"); + this._addInflightOps("hello", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } @@ -230,13 +217,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("hello")) { - } - super._registerBind(host, ops); - } } const words = Object.freeze(["wing", "lang", "dang"]); const uniqueNumbers = Object.freeze(new Set([1, 2, 3])); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/forward_decl.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/forward_decl.w_compile_tf-aws.md index 1c6981dbad5..1c7225fac6e 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/forward_decl.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/forward_decl.w_compile_tf-aws.md @@ -4,10 +4,7 @@ ```js module.exports = function({ }) { class R { - constructor({ f }) { - this.f = f; - } - async $inflight_init() { + constructor({ }) { } } return R; @@ -61,40 +58,32 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.f = "Hello World!!!"; + this._addInflightOps("$inflight_init"); } - method2() { + method2() { (this.method1()); {console.log(String.raw({ raw: ["", ""] }, this.f))}; (this.method2()); } - method1() { + method1() { } static _toInflightType(context) { - const self_client_path = "././inflight.R.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.R.js")({ }) `); } _toInflight() { - const f_client = this._lift(this.f); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const RClient = ${R._toInflightType(this).text}; const client = new RClient({ - f: ${f_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - R._registerBindObject(this.f, host, []); - } - super._registerBind(host, ops); - } } const x = "hi"; if (true) { diff --git a/tools/hangar/__snapshots__/test_corpus/valid/function_returns_function.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/function_returns_function.w_compile_tf-aws.md index d0df2c2211d..5a059fb1102 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/function_returns_function.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/function_returns_function.w_compile_tf-aws.md @@ -9,11 +9,9 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const iFn = async (s) => { - return async () => { + async handle() { + const iFn = async (s) => { + return async () => { return (s === "wing"); } ; @@ -166,12 +164,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -186,21 +183,12 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } - const fn = (s) => { - return () => { + const fn = ((s) => { + return (() => { return (s === "wing"); - } - ; - } - ; + }); + }); const wingFn = (fn("wing")); const dingFn = (fn("ding")); {((cond) => {if (!cond) throw new Error("assertion failed: wingFn()")})((wingFn()))}; diff --git a/tools/hangar/__snapshots__/test_corpus/valid/function_type.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/function_type.w_compile_tf-aws.md index 9cfa7ba1e0e..e21a322c5ff 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/function_type.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/function_type.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(x) { + async handle(x) { } } return $Closure1; @@ -28,9 +26,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(x) { + async handle(x) { } } return $Closure2; @@ -44,11 +40,9 @@ module.exports = function({ }) { class C { constructor({ }) { } - async $inflight_init() { - } - async my_method3(x) { + async my_method3(x) { } - async my_method4(x) { + async my_method4(x) { } } return C; @@ -102,12 +96,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -122,24 +115,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure2.js")({ }) `); } @@ -154,27 +139,19 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class C extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("my_method3", "my_method4"); + this._addInflightOps("my_method3", "my_method4", "$inflight_init"); } - my_method(x) { + my_method(x) { } - my_method2(x) { + my_method2(x) { } static _toInflightType(context) { - const self_client_path = "././inflight.C.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.C.js")({ }) `); } @@ -189,28 +166,15 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("my_method3")) { - } - if (ops.includes("my_method4")) { - } - super._registerBind(host, ops); - } - } - const my_func = (callback) => { - } - ; - const my_func2 = (callback) => { - } - ; - const my_func3 = (x) => { - } - ; - const my_func4 = (x) => { } - ; + const my_func = ((callback) => { + }); + const my_func2 = ((callback) => { + }); + const my_func3 = ((x) => { + }); + const my_func4 = ((x) => { + }); const my_func5 = new $Closure1(this,"$Closure1"); const my_func6 = new $Closure2(this,"$Closure2"); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/hello.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/hello.w_compile_tf-aws.md index 4832383bfc2..13ab360431c 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/hello.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/hello.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ bucket }) { +module.exports = function({ $bucket }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(message) { - (await bucket.put("wing.txt",String.raw({ raw: ["Hello, ", ""] }, message))); + async handle(message) { + (await $bucket.put("wing.txt",String.raw({ raw: ["Hello, ", ""] }, message))); } } return $Closure1; @@ -224,14 +222,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const bucket_client = context._lift(bucket); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - bucket: ${bucket_client}, + require("./inflight.$Closure1.js")({ + $bucket: ${context._lift(bucket)}, }) `); } @@ -247,9 +243,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(bucket, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(bucket, host, ["put"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/identical_inflights.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/identical_inflights.w_compile_tf-aws.md index 0e14f86253e..cf29cb19094 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/identical_inflights.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/identical_inflights.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { } } return $Closure1; @@ -28,9 +26,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { } } return $Closure2; @@ -84,12 +80,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -104,24 +99,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure2.js")({ }) `); } @@ -136,13 +123,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } const x = new $Closure1(this,"$Closure1"); const y = new $Closure2(this,"$Closure2"); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/impl_interface.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/impl_interface.w_compile_tf-aws.md index 39ce85dc627..37e2b8f0bf5 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/impl_interface.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/impl_interface.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ x }) { +module.exports = function({ $x }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await x.handle("hello world!")); + async handle() { + (await $x.handle("hello world!")); } } return $Closure1; @@ -29,9 +27,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(msg) { + async handle(msg) { return; } } @@ -46,9 +42,7 @@ module.exports = function({ }) { class Dog { constructor({ }) { } - async $inflight_init() { - } - async eat() { + async eat() { return; } } @@ -63,9 +57,7 @@ module.exports = function({ }) { class r { constructor({ }) { } - async $inflight_init() { - } - async method2(x) { + async method2(x) { return x; } } @@ -120,12 +112,11 @@ class $Root extends $stdlib.std.Resource { class A extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.A.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.A.js")({ }) `); } @@ -140,26 +131,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const x_client = context._lift(x); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - x: ${x_client}, + require("./inflight.$Closure1.js")({ + $x: ${context._lift(x)}, }) `); } @@ -175,9 +157,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(x, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(x, host, ["handle"]); } @@ -187,18 +166,17 @@ class $Root extends $stdlib.std.Resource { class r extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("method2"); + this._addInflightOps("method2", "$inflight_init"); } - method1(x) { + method1(x) { return x; } - method3(x) { + method3(x) { return x; } static _toInflightType(context) { - const self_client_path = "././inflight.r.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.r.js")({ }) `); } @@ -213,23 +191,15 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("method2")) { - } - super._registerBind(host, ops); - } } class Dog extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("eat"); + this._addInflightOps("eat", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Dog.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Dog.js")({ }) `); } @@ -244,13 +214,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("eat")) { - } - super._registerBind(host, ops); - } } const x = new A(this,"A"); const y = new $Closure1(this,"$Closure1"); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight-subscribers.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight-subscribers.w_compile_tf-aws.md index 101d0dedf4c..c52e1294df6 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight-subscribers.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight-subscribers.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {console.log("hello, world")}; } } @@ -29,9 +27,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {console.log("hello, world")}; } } @@ -304,12 +300,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -324,24 +319,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure2.js")({ }) `); } @@ -356,13 +343,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } (this.node.root.newAbstract("@winglang/sdk.cloud.Topic",this,"cloud.Topic").onMessage(new $Closure1(this,"$Closure1"),{ timeout: (std.Duration.fromSeconds(180)) })); (this.node.root.newAbstract("@winglang/sdk.cloud.Queue",this,"cloud.Queue").setConsumer(new $Closure2(this,"$Closure2"),{ timeout: (std.Duration.fromSeconds(180)) })); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_capture_static.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_capture_static.w_compile_tf-aws.md index db5129caef3..c169c89ea92 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_capture_static.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_capture_static.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ Preflight }) { +module.exports = function({ $Preflight }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: Preflight.staticMethod(123) == \"foo-123\"")})(((await Preflight.staticMethod(123)) === "foo-123"))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: Preflight.staticMethod(123) == \"foo-123\"")})(((await $Preflight.staticMethod(123)) === "foo-123"))}; } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ Preflight }) { ## inflight.$Closure2.js ```js -module.exports = function({ OuterInflight }) { +module.exports = function({ $OuterInflight }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: OuterInflight.staticMethod(\"hello\") == 5")})(((await OuterInflight.staticMethod("hello")) === 5))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: OuterInflight.staticMethod(\"hello\") == 5")})(((await $OuterInflight.staticMethod("hello")) === 5))}; } } return $Closure2; @@ -49,10 +45,12 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const InnerInflight = require("./inflight.InnerInflight.js")({}); + async handle() { + class InnerInflight { + static async staticMethod() { + return "hello"; + } + } {((cond) => {if (!cond) throw new Error("assertion failed: InnerInflight.staticMethod() == \"hello\"")})(((await InnerInflight.staticMethod()) === "hello"))}; } } @@ -63,18 +61,16 @@ module.exports = function({ }) { ## inflight.$Closure4.js ```js -module.exports = function({ util_Util }) { +module.exports = function({ $util_Util }) { class $Closure4 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { { - const $IF_LET_VALUE = (await util_Util.tryEnv("WING_TARGET")); + const $IF_LET_VALUE = (await $util_Util.tryEnv("WING_TARGET")); if ($IF_LET_VALUE != undefined) { const target = $IF_LET_VALUE; {console.log(String.raw({ raw: ["WING_TARGET=", ""] }, target))}; @@ -90,28 +86,11 @@ module.exports = function({ util_Util }) { ``` -## inflight.InnerInflight.js -```js -module.exports = function({ }) { - class InnerInflight { - constructor() { - } - static async staticMethod() { - return "hello"; - } - } - return InnerInflight; -} - -``` - ## inflight.OuterInflight.js ```js module.exports = function({ }) { class OuterInflight { - constructor() { - } - static async staticMethod(b) { + static async staticMethod(b) { return b.length; } } @@ -126,9 +105,7 @@ module.exports = function({ }) { class Preflight { constructor({ }) { } - async $inflight_init() { - } - static async staticMethod(a) { + static async staticMethod(a) { return String.raw({ raw: ["foo-", ""] }, a); } } @@ -470,12 +447,11 @@ class $Root extends $stdlib.std.Resource { class Preflight extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("staticMethod"); + this._addInflightOps("staticMethod", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Preflight.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Preflight.js")({ }) `); } @@ -490,26 +466,15 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } - static _registerTypeBind(host, ops) { - if (ops.includes("staticMethod")) { - } - super._registerTypeBind(host, ops); - } } class OuterInflight extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("staticMethod"); + this._addInflightOps("staticMethod", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.OuterInflight.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.OuterInflight.js")({ }) `); } @@ -524,29 +489,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } - static _registerTypeBind(host, ops) { - if (ops.includes("staticMethod")) { - } - super._registerTypeBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const PreflightClient = Preflight._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Preflight: ${PreflightClient.text}, + require("./inflight.$Closure1.js")({ + $Preflight: ${context._lift(Preflight)}, }) `); } @@ -562,8 +515,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } if (ops.includes("handle")) { $Closure1._registerBindObject(Preflight, host, ["staticMethod"]); } @@ -574,14 +525,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const OuterInflightClient = OuterInflight._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - OuterInflight: ${OuterInflightClient.text}, + require("./inflight.$Closure2.js")({ + $OuterInflight: ${context._lift(OuterInflight)}, }) `); } @@ -596,24 +545,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure3 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure3.js")({ }) `); } @@ -628,26 +569,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure4 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; - const util_UtilClient = util.Util._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - util_Util: ${util_UtilClient.text}, + require("./inflight.$Closure4.js")({ + $util_Util: ${context._lift(util.Util)}, }) `); } @@ -662,13 +594,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:call static method of preflight",new $Closure1(this,"$Closure1")); this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:call static method of an outer inflight class",new $Closure2(this,"$Closure2")); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_as_struct_members.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_as_struct_members.w_compile_tf-aws.md index 615386d7e1f..6fddf9cfbf9 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_as_struct_members.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_as_struct_members.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ Foo }) { +module.exports = function({ $Foo }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { return { - "foo": new Foo(),} + "foo": new $Foo(),} ; } } @@ -24,17 +22,15 @@ module.exports = function({ Foo }) { ## inflight.$Closure2.js ```js -module.exports = function({ getBar }) { +module.exports = function({ $getBar }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const bar = (await getBar()); + async handle() { + const bar = (await $getBar()); {((cond) => {if (!cond) throw new Error("assertion failed: bar.foo.get() == 42")})(((await bar.foo.get()) === 42))}; } } @@ -47,9 +43,7 @@ module.exports = function({ getBar }) { ```js module.exports = function({ }) { class Foo { - constructor() { - } - async get() { + async get() { return 42; } } @@ -192,12 +186,11 @@ class $Root extends $stdlib.std.Resource { class Foo extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("get"); + this._addInflightOps("get", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } @@ -212,26 +205,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("get")) { - } - super._registerBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const FooClient = Foo._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Foo: ${FooClient.text}, + require("./inflight.$Closure1.js")({ + $Foo: ${context._lift(Foo)}, }) `); } @@ -246,26 +230,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const getBar_client = context._lift(getBar); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - getBar: ${getBar_client}, + require("./inflight.$Closure2.js")({ + $getBar: ${context._lift(getBar)}, }) `); } @@ -281,9 +256,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(getBar, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(getBar, host, ["handle"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_capture_const.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_capture_const.w_compile_tf-aws.md index 0b0aa79600a..f9b4e75830f 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_capture_const.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_capture_const.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ myConst, Foo }) { +module.exports = function({ $Foo, $myConst }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const x = new Foo(); - {((cond) => {if (!cond) throw new Error("assertion failed: x.getValue() == myConst")})(((await x.getValue()) === myConst))}; + async handle() { + const x = new $Foo(); + {((cond) => {if (!cond) throw new Error("assertion failed: x.getValue() == myConst")})(((await x.getValue()) === $myConst))}; } } return $Closure1; @@ -23,12 +21,10 @@ module.exports = function({ myConst, Foo }) { ## inflight.Foo.js ```js -module.exports = function({ myConst }) { +module.exports = function({ $myConst }) { class Foo { - constructor() { - } - async getValue() { - return myConst; + async getValue() { + return $myConst; } } return Foo; @@ -171,14 +167,12 @@ class $Root extends $stdlib.std.Resource { class Foo extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("getValue"); + this._addInflightOps("getValue", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; - const myConst_client = context._lift(myConst); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - myConst: ${myConst_client}, + require("./inflight.Foo.js")({ + $myConst: ${context._lift(myConst)}, }) `); } @@ -194,9 +188,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Foo._registerBindObject(myConst, host, []); - } if (ops.includes("getValue")) { Foo._registerBindObject(myConst, host, []); } @@ -207,16 +198,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const myConst_client = context._lift(myConst); - const FooClient = Foo._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - myConst: ${myConst_client}, - Foo: ${FooClient.text}, + require("./inflight.$Closure1.js")({ + $Foo: ${context._lift(Foo)}, + $myConst: ${context._lift(myConst)}, }) `); } @@ -232,9 +220,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(myConst, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(myConst, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_definitions.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_definitions.w_compile_tf-aws.md index bb6bb09ae7a..8e469c7ddb2 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_definitions.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_definitions.w_compile_tf-aws.md @@ -9,10 +9,12 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const C = require("./inflight.C.js")({}); + async handle() { + class C { + async foo() { + return "c1"; + } + } const c = new C(); {((cond) => {if (!cond) throw new Error("assertion failed: c.foo() == \"c1\"")})(((await c.foo()) === "c1"))}; } @@ -24,17 +26,15 @@ module.exports = function({ }) { ## inflight.$Closure2.js ```js -module.exports = function({ F }) { +module.exports = function({ $F }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - return (await new F().foo()); + async handle() { + return (await new $F().foo()); } } return $Closure2; @@ -44,22 +44,20 @@ module.exports = function({ F }) { ## inflight.$Closure3.js ```js -module.exports = function({ a, fn, d, innerD, B }) { +module.exports = function({ $B, $a, $d, $fn, $innerD }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: a.goo() == \"a2\"")})(((await a.goo()) === "a2"))}; - const b = new B(); + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: a.goo() == \"a2\"")})(((await $a.goo()) === "a2"))}; + const b = new $B(); {((cond) => {if (!cond) throw new Error("assertion failed: b.foo() == \"b1\"")})(((await b.foo()) === "b1"))}; - (await fn()); - {((cond) => {if (!cond) throw new Error("assertion failed: d.callInner() == \"f1\"")})(((await d.callInner()) === "f1"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: innerD() == \"f1\"")})(((await innerD()) === "f1"))}; + (await $fn()); + {((cond) => {if (!cond) throw new Error("assertion failed: d.callInner() == \"f1\"")})(((await $d.callInner()) === "f1"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: innerD() == \"f1\"")})(((await $innerD()) === "f1"))}; } } return $Closure3; @@ -73,9 +71,7 @@ module.exports = function({ }) { class A { constructor({ }) { } - async $inflight_init() { - } - async goo() { + async goo() { return "a2"; } } @@ -88,9 +84,7 @@ module.exports = function({ }) { ```js module.exports = function({ }) { class B { - constructor() { - } - async foo() { + async foo() { return "b1"; } } @@ -99,32 +93,15 @@ module.exports = function({ }) { ``` -## inflight.C.js -```js -module.exports = function({ }) { - class C { - constructor() { - } - async foo() { - return "c1"; - } - } - return C; -} - -``` - ## inflight.D.js ```js module.exports = function({ }) { class D { - constructor({ inner }) { - this.inner = inner; - } - async $inflight_init() { + constructor({ $this_inner }) { + this.$this_inner = $this_inner; } - async callInner() { - return (await this.inner()); + async callInner() { + return (await this.$this_inner()); } } return D; @@ -138,8 +115,6 @@ module.exports = function({ }) { class E { constructor({ }) { } - async $inflight_init() { - } } return E; } @@ -150,9 +125,7 @@ module.exports = function({ }) { ```js module.exports = function({ }) { class F { - constructor() { - } - async foo() { + async foo() { return "f1"; } } @@ -295,15 +268,14 @@ class $Root extends $stdlib.std.Resource { class A extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("goo"); + this._addInflightOps("goo", "$inflight_init"); } - foo() { + foo() { return "a1"; } static _toInflightType(context) { - const self_client_path = "././inflight.A.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.A.js")({ }) `); } @@ -318,23 +290,15 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("goo")) { - } - super._registerBind(host, ops); - } } class B extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("foo"); + this._addInflightOps("foo", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.B.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.B.js")({ }) `); } @@ -349,24 +313,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("foo")) { - } - super._registerBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -381,13 +337,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class D extends $stdlib.std.Resource { constructor(scope, id, ) { @@ -395,14 +344,14 @@ class $Root extends $stdlib.std.Resource { class E extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } - foo() { + foo() { return "e1"; } static _toInflightType(context) { - const self_client_path = "././inflight.E.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.E.js")({ }) `); } @@ -417,23 +366,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } const pb = new E(this,"E"); {((cond) => {if (!cond) throw new Error("assertion failed: pb.foo() == \"e1\"")})(((pb.foo()) === "e1"))}; class F extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("foo"); + this._addInflightOps("foo", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.F.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.F.js")({ }) `); } @@ -448,27 +391,18 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("foo")) { - } - super._registerBind(host, ops); - } } const __parent_this_2 = this; class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const FClient = F._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - F: ${FClient.text}, + require("./inflight.$Closure2.js")({ + $F: ${context._lift(F)}, }) `); } @@ -483,34 +417,25 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } this.inner = new $Closure2(this,"$Closure2"); - this._addInflightOps("callInner"); + this._addInflightOps("callInner", "$inflight_init"); } - getInner() { + getInner() { return this.inner; } static _toInflightType(context) { - const self_client_path = "././inflight.D.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.D.js")({ }) `); } _toInflight() { - const inner_client = this._lift(this.inner); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const DClient = ${D._toInflightType(this).text}; const client = new DClient({ - inner: ${inner_client}, + $this_inner: ${this._lift(this.inner)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -518,9 +443,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - D._registerBindObject(this.inner, host, []); - } if (ops.includes("callInner")) { D._registerBindObject(this.inner, host, ["handle"]); } @@ -531,22 +453,16 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const a_client = context._lift(a); - const fn_client = context._lift(fn); - const d_client = context._lift(d); - const innerD_client = context._lift(innerD); - const BClient = B._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - a: ${a_client}, - fn: ${fn_client}, - d: ${d_client}, - innerD: ${innerD_client}, - B: ${BClient.text}, + require("./inflight.$Closure3.js")({ + $B: ${context._lift(B)}, + $a: ${context._lift(a)}, + $d: ${context._lift(d)}, + $fn: ${context._lift(fn)}, + $innerD: ${context._lift(innerD)}, }) `); } @@ -562,12 +478,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(a, host, []); - $Closure3._registerBindObject(d, host, []); - $Closure3._registerBindObject(fn, host, []); - $Closure3._registerBindObject(innerD, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(a, host, ["goo"]); $Closure3._registerBindObject(d, host, ["callInner"]); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_inner_capture_mutable.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_inner_capture_mutable.w_compile_tf-aws.md index 38efcd557c9..51ca1cfd80a 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_inner_capture_mutable.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_inner_capture_mutable.w_compile_tf-aws.md @@ -9,15 +9,19 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const y = [1]; let i = 10; - const Inner = require("./inflight.Inner.js")({y, i}); + class Inner { + async dang() { + (await y.push(2)); + i = (i + 1); + return ((await y.at(0)) + 10); + } + } {((cond) => {if (!cond) throw new Error("assertion failed: new Inner().dang() == 11")})(((await new Inner().dang()) === 11))}; {((cond) => {if (!cond) throw new Error("assertion failed: y.at(1) == 2")})(((await y.at(1)) === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: i == 10")})((i === 10))}; + {((cond) => {if (!cond) throw new Error("assertion failed: i == 11")})((i === 11))}; } } return $Closure1; @@ -25,23 +29,6 @@ module.exports = function({ }) { ``` -## inflight.Inner.js -```js -module.exports = function({ y, i }) { - class Inner { - constructor() { - } - async dang() { - (await y.push(2)); - i = (i + 1); - return ((await y.at(0)) + 10); - } - } - return Inner; -} - -``` - ## main.tf.json ```json { @@ -178,12 +165,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -198,13 +184,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:inner inflight class capture immutable",new $Closure1(this,"$Closure1")); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_inside_inflight_closure.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_inside_inflight_closure.w_compile_tf-aws.md index 6fe225388d5..67f74a5035a 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_inside_inflight_closure.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_inside_inflight_closure.w_compile_tf-aws.md @@ -2,18 +2,23 @@ ## inflight.$Closure1.js ```js -module.exports = function({ __parent_this_1 }) { +module.exports = function({ $__parent_this_1_b }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(payload) { - (await __parent_this_1.b.put("k","v")); - const InflightClass = require("./inflight.InflightClass.js")({}); + async handle(payload) { + (await $__parent_this_1_b.put("k","v")); + class InflightClass { + async method() { + {((cond) => {if (!cond) throw new Error("assertion failed: this.field == \"value\"")})((this.field === "value"))}; + } + constructor() { + this.field = "value"; + } + } const c = new InflightClass(); (await c.method()); } @@ -25,17 +30,15 @@ module.exports = function({ __parent_this_1 }) { ## inflight.$Closure2.js ```js -module.exports = function({ f }) { +module.exports = function({ $f }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await f.invoke("text")); + async handle() { + (await $f.invoke("text")); } } return $Closure2; @@ -52,11 +55,13 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const x = 12; - const Foo = require("./inflight.Foo.js")({x}); + class Foo { + async getX() { + return x; + } + } const foo = new Foo(); const y = (await foo.getX()); {((cond) => {if (!cond) throw new Error("assertion failed: y == 12")})((y === 12))}; @@ -67,45 +72,11 @@ module.exports = function({ }) { ``` -## inflight.Foo.js -```js -module.exports = function({ x }) { - class Foo { - constructor() { - } - async getX() { - return x; - } - } - return Foo; -} - -``` - -## inflight.InflightClass.js -```js -module.exports = function({ }) { - class InflightClass { - constructor() { - this.field = "value"; - } - async method() { - {((cond) => {if (!cond) throw new Error("assertion failed: this.field == \"value\"")})((this.field === "value"))}; - } - } - return InflightClass; -} - -``` - ## inflight.PreflightClass.js ```js module.exports = function({ }) { class PreflightClass { - constructor({ b }) { - this.b = b; - } - async $inflight_init() { + constructor({ }) { } } return PreflightClass; @@ -426,21 +397,20 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.b = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("$inflight_init"); } - preflight_method() { + preflight_method() { const __parent_this_1 = this; class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const __parent_this_1_client = context._lift(__parent_this_1); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - __parent_this_1: ${__parent_this_1_client}, + require("./inflight.$Closure1.js")({ + $__parent_this_1_b: ${context._lift(__parent_this_1.b)}, }) `); } @@ -456,9 +426,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(__parent_this_1, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(__parent_this_1.b, host, ["put"]); } @@ -469,44 +436,33 @@ class $Root extends $stdlib.std.Resource { return this.node.root.newAbstract("@winglang/sdk.cloud.Function",this,"cloud.Function",inflight_closure); } static _toInflightType(context) { - const self_client_path = "././inflight.PreflightClass.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.PreflightClass.js")({ }) `); } _toInflight() { - const b_client = this._lift(this.b); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const PreflightClassClient = ${PreflightClass._toInflightType(this).text}; const client = new PreflightClassClient({ - b: ${b_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - PreflightClass._registerBindObject(this.b, host, []); - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const f_client = context._lift(f); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - f: ${f_client}, + require("./inflight.$Closure2.js")({ + $f: ${context._lift(f)}, }) `); } @@ -522,9 +478,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(f, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(f, host, ["invoke"]); } @@ -535,12 +488,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure3.js")({ }) `); } @@ -555,13 +507,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } const p = new PreflightClass(this,"PreflightClass"); const f = (p.preflight_method()); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_modifiers.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_modifiers.w_compile_tf-aws.md index 0276d662ef9..6a0ebad2c0c 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_modifiers.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_modifiers.w_compile_tf-aws.md @@ -4,10 +4,10 @@ ```js module.exports = function({ }) { class C { - constructor() { - this.field = 12; + async method() { } - async method() { + constructor() { + this.field = 12; } } return C; @@ -60,12 +60,11 @@ class $Root extends $stdlib.std.Resource { class C extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("method", "field"); + this._addInflightOps("method", "$inflight_init", "field"); } static _toInflightType(context) { - const self_client_path = "././inflight.C.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.C.js")({ }) `); } @@ -82,8 +81,7 @@ class $Root extends $stdlib.std.Resource { } _registerBind(host, ops) { if (ops.includes("$inflight_init")) { - } - if (ops.includes("method")) { + C._registerBindObject(this, host, ["field"]); } super._registerBind(host, ops); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_outside_inflight_closure.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_outside_inflight_closure.w_compile_tf-aws.md index 5d96f9999ab..eb3425c9a88 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_outside_inflight_closure.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_outside_inflight_closure.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ BinaryOperation }) { +module.exports = function({ $BinaryOperation }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const op = new BinaryOperation(10,20); + async handle() { + const op = new $BinaryOperation(10,20); {((cond) => {if (!cond) throw new Error("assertion failed: op.add() == 30")})(((await op.add()) === 30))}; } } @@ -25,13 +23,13 @@ module.exports = function({ BinaryOperation }) { ```js module.exports = function({ }) { class BinaryOperation { - constructor(lhs, rhs) { + async add() { + return (this.lhs + this.rhs); + } + constructor(lhs, rhs) { this.lhs = lhs; this.rhs = rhs; } - async add() { - return (this.lhs + this.rhs); - } } return BinaryOperation; } @@ -173,12 +171,11 @@ class $Root extends $stdlib.std.Resource { class BinaryOperation extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("add", "lhs", "rhs"); + this._addInflightOps("add", "$inflight_init", "lhs", "rhs"); } static _toInflightType(context) { - const self_client_path = "././inflight.BinaryOperation.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.BinaryOperation.js")({ }) `); } @@ -195,8 +192,10 @@ class $Root extends $stdlib.std.Resource { } _registerBind(host, ops) { if (ops.includes("$inflight_init")) { + BinaryOperation._registerBindObject(this, host, ["lhs", "rhs"]); } if (ops.includes("add")) { + BinaryOperation._registerBindObject(this, host, ["lhs", "rhs"]); } super._registerBind(host, ops); } @@ -205,14 +204,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const BinaryOperationClient = BinaryOperation._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - BinaryOperation: ${BinaryOperationClient.text}, + require("./inflight.$Closure1.js")({ + $BinaryOperation: ${context._lift(BinaryOperation)}, }) `); } @@ -227,13 +224,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:inflight class outside inflight closure",new $Closure1(this,"$Closure1")); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_structural_interace_handler.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_structural_interace_handler.w_compile_tf-aws.md index 73a09ac694b..abf57b12475 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_structural_interace_handler.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_structural_interace_handler.w_compile_tf-aws.md @@ -2,20 +2,25 @@ ## inflight.$Closure1.js ```js -module.exports = function({ NotGoo }) { +module.exports = function({ $NotGoo }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const YesGoo = require("./inflight.YesGoo.js")({}); + async handle() { + class YesGoo { + async handle() { + return 456; + } + async anotherMethod() { + {console.log("also fine")}; + } + } const y = new YesGoo(); {((cond) => {if (!cond) throw new Error("assertion failed: y.handle() == 456")})(((await y.handle()) === 456))}; - const x = new NotGoo(); + const x = new $NotGoo(); {((cond) => {if (!cond) throw new Error("assertion failed: x.handle() == 123")})(((await x.handle()) === 123))}; } } @@ -28,9 +33,7 @@ module.exports = function({ NotGoo }) { ```js module.exports = function({ }) { class NotGoo { - constructor() { - } - async handle() { + async handle() { return 123; } } @@ -39,24 +42,6 @@ module.exports = function({ }) { ``` -## inflight.YesGoo.js -```js -module.exports = function({ }) { - class YesGoo { - constructor() { - } - async handle() { - return 456; - } - async anotherMethod() { - {console.log("also fine")}; - } - } - return YesGoo; -} - -``` - ## main.tf.json ```json { @@ -192,12 +177,11 @@ class $Root extends $stdlib.std.Resource { class NotGoo extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.NotGoo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.NotGoo.js")({ }) `); } @@ -212,26 +196,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const NotGooClient = NotGoo._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - NotGoo: ${NotGooClient.text}, + require("./inflight.$Closure1.js")({ + $NotGoo: ${context._lift(NotGoo)}, }) `); } @@ -246,13 +221,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:structure interface types for 'handle'",new $Closure1(this,"$Closure1")); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_without_init.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_without_init.w_compile_tf-aws.md index fa992b6d8de..2ea212e44d4 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_without_init.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_class_without_init.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ Foo }) { +module.exports = function({ $Foo }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - new Foo(); + async handle() { + new $Foo(); } } return $Closure1; @@ -24,8 +22,6 @@ module.exports = function({ Foo }) { ```js module.exports = function({ }) { class Foo { - constructor() { - } } return Foo; } @@ -167,11 +163,11 @@ class $Root extends $stdlib.std.Resource { class Foo extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } @@ -186,24 +182,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const FooClient = Foo._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Foo: ${FooClient.text}, + require("./inflight.$Closure1.js")({ + $Foo: ${context._lift(Foo)}, }) `); } @@ -218,13 +207,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:inflight class without init",new $Closure1(this,"$Closure1")); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflight_concat.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflight_concat.w_compile_tf-aws.md index 82de55198bb..a5b41759242 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflight_concat.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflight_concat.w_compile_tf-aws.md @@ -4,13 +4,11 @@ ```js module.exports = function({ }) { class R { - constructor({ s1 }) { - this.s1 = s1; + constructor({ $_this_s1_concat___world___ }) { + this.$_this_s1_concat___world___ = $_this_s1_concat___world___; } - async $inflight_init() { - } - async foo() { - {console.log((await this.s1.concat(" world")))}; + async foo() { + {console.log(this.$_this_s1_concat___world___)}; } } return R; @@ -65,22 +63,20 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.s1 = "hello"; - this._addInflightOps("foo"); + this._addInflightOps("foo", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.R.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.R.js")({ }) `); } _toInflight() { - const s1_client = this._lift(this.s1); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const RClient = ${R._toInflightType(this).text}; const client = new RClient({ - s1: ${s1_client}, + $_this_s1_concat___world___: ${this._lift((this.s1.concat(" world")))}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -88,11 +84,8 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - R._registerBindObject(this.s1, host, []); - } if (ops.includes("foo")) { - R._registerBindObject(this.s1, host, []); + R._registerBindObject((this.s1.concat(" world")), host, []); } super._registerBind(host, ops); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/inflights_calling_inflights.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/inflights_calling_inflights.w_compile_tf-aws.md index 4223de41b42..639464601ed 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/inflights_calling_inflights.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/inflights_calling_inflights.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ globalBucket }) { +module.exports = function({ $globalBucket }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(event, file) { - (await globalBucket.put(file,event)); + async handle(event, file) { + (await $globalBucket.put(file,event)); } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ globalBucket }) { ## inflight.$Closure2.js ```js -module.exports = function({ storeInBucket }) { +module.exports = function({ $storeInBucket }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(event) { - (await storeInBucket(event,"file1")); + async handle(event) { + (await $storeInBucket(event,"file1")); } } return $Closure2; @@ -42,18 +38,16 @@ module.exports = function({ storeInBucket }) { ## inflight.$Closure3.js ```js -module.exports = function({ func1, globalBucket }) { +module.exports = function({ $func1, $globalBucket }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await func1.invoke("hi1")); - {((cond) => {if (!cond) throw new Error("assertion failed: globalBucket.get(\"file1\") == \"hi1\"")})(((await globalBucket.get("file1")) === "hi1"))}; + async handle() { + (await $func1.invoke("hi1")); + {((cond) => {if (!cond) throw new Error("assertion failed: globalBucket.get(\"file1\") == \"hi1\"")})(((await $globalBucket.get("file1")) === "hi1"))}; } } return $Closure3; @@ -63,17 +57,15 @@ module.exports = function({ func1, globalBucket }) { ## inflight.$Closure4.js ```js -module.exports = function({ globalBucket }) { +module.exports = function({ $globalBucket }) { class $Closure4 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(s) { - (await globalBucket.list()); + async handle(s) { + (await $globalBucket.list()); return "hello"; } } @@ -84,17 +76,15 @@ module.exports = function({ globalBucket }) { ## inflight.$Closure5.js ```js -module.exports = function({ x }) { +module.exports = function({ $x }) { class $Closure5 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const val = (await x.foo()); + async handle() { + const val = (await $x.foo()); {((cond) => {if (!cond) throw new Error("assertion failed: val == \"hello\"")})((val === "hello"))}; } } @@ -107,13 +97,11 @@ module.exports = function({ x }) { ```js module.exports = function({ }) { class MyResource { - constructor({ closure }) { - this.closure = closure; - } - async $inflight_init() { + constructor({ $this_closure }) { + this.$this_closure = $this_closure; } - async foo() { - return (await this.closure("anything")); + async foo() { + return (await this.$this_closure("anything")); } } return MyResource; @@ -436,14 +424,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const globalBucket_client = context._lift(globalBucket); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - globalBucket: ${globalBucket_client}, + require("./inflight.$Closure1.js")({ + $globalBucket: ${context._lift(globalBucket)}, }) `); } @@ -459,9 +445,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(globalBucket, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(globalBucket, host, ["put"]); } @@ -472,14 +455,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const storeInBucket_client = context._lift(storeInBucket); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - storeInBucket: ${storeInBucket_client}, + require("./inflight.$Closure2.js")({ + $storeInBucket: ${context._lift(storeInBucket)}, }) `); } @@ -495,9 +476,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(storeInBucket, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(storeInBucket, host, ["handle"]); } @@ -508,16 +486,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const func1_client = context._lift(func1); - const globalBucket_client = context._lift(globalBucket); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - func1: ${func1_client}, - globalBucket: ${globalBucket_client}, + require("./inflight.$Closure3.js")({ + $func1: ${context._lift(func1)}, + $globalBucket: ${context._lift(globalBucket)}, }) `); } @@ -533,10 +508,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(func1, host, []); - $Closure3._registerBindObject(globalBucket, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(func1, host, ["invoke"]); $Closure3._registerBindObject(globalBucket, host, ["get"]); @@ -552,14 +523,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; - const globalBucket_client = context._lift(globalBucket); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - globalBucket: ${globalBucket_client}, + require("./inflight.$Closure4.js")({ + $globalBucket: ${context._lift(globalBucket)}, }) `); } @@ -575,9 +544,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure4._registerBindObject(globalBucket, host, []); - } if (ops.includes("handle")) { $Closure4._registerBindObject(globalBucket, host, ["list"]); } @@ -585,22 +551,20 @@ class $Root extends $stdlib.std.Resource { } } this.closure = new $Closure4(this,"$Closure4"); - this._addInflightOps("foo"); + this._addInflightOps("foo", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.MyResource.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.MyResource.js")({ }) `); } _toInflight() { - const closure_client = this._lift(this.closure); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const MyResourceClient = ${MyResource._toInflightType(this).text}; const client = new MyResourceClient({ - closure: ${closure_client}, + $this_closure: ${this._lift(this.closure)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -608,9 +572,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - MyResource._registerBindObject(this.closure, host, []); - } if (ops.includes("foo")) { MyResource._registerBindObject(this.closure, host, ["handle"]); } @@ -621,14 +582,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure5.js"; - const x_client = context._lift(x); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - x: ${x_client}, + require("./inflight.$Closure5.js")({ + $x: ${context._lift(x)}, }) `); } @@ -644,9 +603,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure5._registerBindObject(x, host, []); - } if (ops.includes("handle")) { $Closure5._registerBindObject(x, host, ["foo"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/issue_2889.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/issue_2889.w_compile_tf-aws.md index 6bd90ecc88b..e2e6de6a257 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/issue_2889.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/issue_2889.w_compile_tf-aws.md @@ -2,16 +2,14 @@ ## inflight.$Closure1.js ```js -module.exports = function({ std_Json }) { +module.exports = function({ $std_Json }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { + async handle(req) { const issues = (JSON.parse("[{\"foo\": \"bar\"}, {\"foo\": \"baz\"}, {\"foo\": \"qux\"}]")); return { "status": 200, @@ -27,17 +25,15 @@ module.exports = function({ std_Json }) { ## inflight.$Closure2.js ```js -module.exports = function({ api, http_Util, std_Json }) { +module.exports = function({ $api_url, $http_Util, $std_Json }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const res = (await http_Util.get((api.url + "/foo"))); + async handle() { + const res = (await $http_Util.get(($api_url + "/foo"))); const body = (JSON.parse((res.body ?? ""))); const a1 = (body)[0]; {((cond) => {if (!cond) throw new Error("assertion failed: a1.get(\"foo\") == \"bar\"")})(((a1)["foo"] === "bar"))}; @@ -232,7 +228,6 @@ module.exports = function({ api, http_Util, std_Json }) { }, "environment": { "variables": { - "CLOUD_API_C82DF3A5": "${aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url}", "WING_FUNCTION_NAME": "Handler-c88c3aa2", "WING_TARGET": "tf-aws", "WING_TOKEN_TFTOKEN_TOKEN_21": "${jsonencode(aws_api_gateway_stage.cloudApi_api_stage_BBB283E4.invoke_url)}" @@ -322,14 +317,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -344,30 +337,19 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const api_client = context._lift(api); - const http_UtilClient = http.Util._toInflightType(context); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - api: ${api_client}, - http_Util: ${http_UtilClient.text}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure2.js")({ + $api_url: ${context._lift(api.url)}, + $http_Util: ${context._lift(http.Util)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -383,9 +365,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(api, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(api.url, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/json.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/json.w_compile_tf-aws.md index 752ac73517d..442259174cd 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/json.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/json.w_compile_tf-aws.md @@ -4,10 +4,7 @@ ```js module.exports = function({ }) { class Foo { - constructor({ SumStr }) { - this.SumStr = SumStr; - } - async $inflight_init() { + constructor({ }) { } } return Foo; @@ -61,33 +58,25 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.SumStr = "wow!"; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } _toInflight() { - const SumStr_client = this._lift(this.SumStr); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const FooClient = ${Foo._toInflightType(this).text}; const client = new FooClient({ - SumStr: ${SumStr_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Foo._registerBindObject(this.SumStr, host, []); - } - super._registerBind(host, ops); - } } const jsonNumber = 123; const jsonBool = true; @@ -101,10 +90,9 @@ class $Root extends $stdlib.std.Resource { const jj = someNumber; const jj1 = Object.freeze({"foo":someNumber}); const jj2 = [someNumber, Object.freeze({"bar":someNumber})]; - const getStr = () => { + const getStr = (() => { return "hello"; - } - ; + }); const jj3 = (getStr()); {((cond) => {if (!cond) throw new Error("assertion failed: jj3 == Json \"hello\"")})((jj3 === "hello"))}; const f = new Foo(this,"Foo"); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/json_bucket.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/json_bucket.w_compile_tf-aws.md index aa975f78564..01504f20fc0 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/json_bucket.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/json_bucket.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b, fileName }) { +module.exports = function({ $b, $fileName }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(msg) { - const x = (await b.getJson(fileName)); + async handle(msg) { + const x = (await $b.getJson($fileName)); {((cond) => {if (!cond) throw new Error("assertion failed: x.get(\"persons\").getAt(0).get(\"fears\").getAt(1) == \"failure\"")})((((((x)["persons"])[0])["fears"])[1] === "failure"))}; } } @@ -23,18 +21,16 @@ module.exports = function({ b, fileName }) { ## inflight.$Closure2.js ```js -module.exports = function({ b, fileName, j, getJson }) { +module.exports = function({ $b, $fileName, $getJson, $j }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await b.putJson(fileName,j)); - (await getJson.invoke("")); + async handle() { + (await $b.putJson($fileName,$j)); + (await $getJson.invoke("")); } } return $Closure2; @@ -290,16 +286,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); - const fileName_client = context._lift(fileName); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, - fileName: ${fileName_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, + $fileName: ${context._lift(fileName)}, }) `); } @@ -315,10 +308,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - $Closure1._registerBindObject(fileName, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["getJson"]); $Closure1._registerBindObject(fileName, host, []); @@ -330,20 +319,15 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const b_client = context._lift(b); - const fileName_client = context._lift(fileName); - const j_client = context._lift(j); - const getJson_client = context._lift(getJson); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, - fileName: ${fileName_client}, - j: ${j_client}, - getJson: ${getJson_client}, + require("./inflight.$Closure2.js")({ + $b: ${context._lift(b)}, + $fileName: ${context._lift(fileName)}, + $getJson: ${context._lift(getJson)}, + $j: ${context._lift(j)}, }) `); } @@ -359,12 +343,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(b, host, []); - $Closure2._registerBindObject(fileName, host, []); - $Closure2._registerBindObject(getJson, host, []); - $Closure2._registerBindObject(j, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(b, host, ["putJson"]); $Closure2._registerBindObject(fileName, host, []); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/json_static.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/json_static.w_compile_tf-aws.md index d42fa426080..2e51f0e7bc5 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/json_static.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/json_static.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ jj, std_Json }) { +module.exports = function({ $jj, $std_Json }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const ss = ((args) => { return JSON.stringify(args[0], null, args[1]) })([jj]); + async handle() { + const ss = ((args) => { return JSON.stringify(args[0], null, args[1]) })([$jj]); {((cond) => {if (!cond) throw new Error("assertion failed: ss == \"{\\\"a\\\":123,\\\"b\\\":{\\\"c\\\":456,\\\"d\\\":789}}\"")})((ss === "{\"a\":123,\"b\":{\"c\":456,\"d\":789}}"))}; } } @@ -23,16 +21,14 @@ module.exports = function({ jj, std_Json }) { ## inflight.$Closure2.js ```js -module.exports = function({ std_Json }) { +module.exports = function({ $std_Json }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const hasCheck = Object.freeze({"a":"hello","b":"wing"}); {((cond) => {if (!cond) throw new Error("assertion failed: Json.has(hasCheck, \"a\") == true")})((((args) => { return args[0].hasOwnProperty(args[1]); })([hasCheck,"a"]) === true))}; {((cond) => {if (!cond) throw new Error("assertion failed: Json.has(hasCheck, \"c\") == false")})((((args) => { return args[0].hasOwnProperty(args[1]); })([hasCheck,"c"]) === false))}; @@ -245,16 +241,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const jj_client = context._lift(jj); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - jj: ${jj_client}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $jj: ${context._lift(jj)}, + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -270,9 +263,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(jj, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(jj, host, []); } @@ -283,14 +273,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure2.js")({ + $std_Json: ${context._lift(std.Json)}, }) `); } @@ -305,13 +293,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } const x = Object.freeze({"a":123,"b":Object.freeze({"c":456,"d":789})}); const k = (Object.keys(x)); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/lift_expr_with_this.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/lift_expr_with_this.w_compile_tf-aws.md new file mode 100644 index 00000000000..07ee9ef5140 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/lift_expr_with_this.w_compile_tf-aws.md @@ -0,0 +1,242 @@ +# [lift_expr_with_this.w](../../../../../examples/tests/valid/lift_expr_with_this.w) | compile | tf-aws + +## inflight.$Closure1.js +```js +module.exports = function({ }) { + class $Closure1 { + constructor({ $foo_this_value }) { + this.$foo_this_value = $foo_this_value; + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: foo_this.value == \"hello\"")})((this.$foo_this_value === "hello"))}; + } + } + return $Closure1; +} + +``` + +## inflight.Foo.js +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + } + return Foo; +} + +``` + +## main.tf.json +```json +{ + "//": { + "metadata": { + "backend": "local", + "stackName": "root", + "version": "0.17.0" + }, + "outputs": { + "root": { + "Default": { + "cloud.TestRunner": { + "TestFunctionArns": "WING_TEST_RUNNER_FUNCTION_ARNS" + } + } + } + } + }, + "output": { + "WING_TEST_RUNNER_FUNCTION_ARNS": { + "value": "[[\"root/Default/Default/test:test\",\"${aws_lambda_function.testtest_Handler_295107CC.arn}\"]]" + } + }, + "provider": { + "aws": [ + {} + ] + }, + "resource": { + "aws_iam_role": { + "testtest_Handler_IamRole_15693C93": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRole", + "uniqueId": "testtest_Handler_IamRole_15693C93" + } + }, + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}" + } + }, + "aws_iam_role_policy": { + "testtest_Handler_IamRolePolicy_AF0279BD": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicy", + "uniqueId": "testtest_Handler_IamRolePolicy_AF0279BD" + } + }, + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"none:null\",\"Resource\":\"*\"}]}", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_iam_role_policy_attachment": { + "testtest_Handler_IamRolePolicyAttachment_ADF4752D": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicyAttachment", + "uniqueId": "testtest_Handler_IamRolePolicyAttachment_ADF4752D" + } + }, + "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_lambda_function": { + "testtest_Handler_295107CC": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/Default", + "uniqueId": "testtest_Handler_295107CC" + } + }, + "environment": { + "variables": { + "WING_FUNCTION_NAME": "Handler-c8f4f2a1", + "WING_TARGET": "tf-aws" + } + }, + "function_name": "Handler-c8f4f2a1", + "handler": "index.handler", + "publish": true, + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.arn}", + "runtime": "nodejs18.x", + "s3_bucket": "${aws_s3_bucket.Code.bucket}", + "s3_key": "${aws_s3_object.testtest_Handler_S3Object_9F4E28A7.key}", + "timeout": 30, + "vpc_config": { + "security_group_ids": [], + "subnet_ids": [] + } + } + }, + "aws_s3_bucket": { + "Code": { + "//": { + "metadata": { + "path": "root/Default/Code", + "uniqueId": "Code" + } + }, + "bucket_prefix": "code-c84a50b1-" + } + }, + "aws_s3_object": { + "testtest_Handler_S3Object_9F4E28A7": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/S3Object", + "uniqueId": "testtest_Handler_S3Object_9F4E28A7" + } + }, + "bucket": "${aws_s3_bucket.Code.bucket}", + "key": "", + "source": "" + } + } + } +} +``` + +## preflight.js +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.value = "hello"; + this._addInflightOps("$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + $foo_this_value: ${this._lift(foo_this.value)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(foo_this.value, host, []); + } + super._registerBind(host, ops); + } + } + const foo_this = new Foo(this,"Foo"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "lift_expr_with_this", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); + +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/lift_expr_with_this.w_test_sim.md b/tools/hangar/__snapshots__/test_corpus/valid/lift_expr_with_this.w_test_sim.md new file mode 100644 index 00000000000..9a7b7161532 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/lift_expr_with_this.w_test_sim.md @@ -0,0 +1,12 @@ +# [lift_expr_with_this.w](../../../../../examples/tests/valid/lift_expr_with_this.w) | test | sim + +## stdout.log +```log +pass ─ lift_expr_with_this.wsim » root/env0/test:test + + +Tests 1 passed (1) +Test Files 1 passed (1) +Duration +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/lift_redefinition.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/lift_redefinition.w_compile_tf-aws.md new file mode 100644 index 00000000000..32824b5fcd0 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/lift_redefinition.w_compile_tf-aws.md @@ -0,0 +1,207 @@ +# [lift_redefinition.w](../../../../../examples/tests/valid/lift_redefinition.w) | compile | tf-aws + +## inflight.$Closure1.js +```js +module.exports = function({ $y }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: y == \"hello\"")})(($y === "hello"))}; + const y = "z"; + {((cond) => {if (!cond) throw new Error("assertion failed: y == \"z\"")})((y === "z"))}; + } + } + return $Closure1; +} + +``` + +## main.tf.json +```json +{ + "//": { + "metadata": { + "backend": "local", + "stackName": "root", + "version": "0.17.0" + }, + "outputs": { + "root": { + "Default": { + "cloud.TestRunner": { + "TestFunctionArns": "WING_TEST_RUNNER_FUNCTION_ARNS" + } + } + } + } + }, + "output": { + "WING_TEST_RUNNER_FUNCTION_ARNS": { + "value": "[[\"root/Default/Default/test:test\",\"${aws_lambda_function.testtest_Handler_295107CC.arn}\"]]" + } + }, + "provider": { + "aws": [ + {} + ] + }, + "resource": { + "aws_iam_role": { + "testtest_Handler_IamRole_15693C93": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRole", + "uniqueId": "testtest_Handler_IamRole_15693C93" + } + }, + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}" + } + }, + "aws_iam_role_policy": { + "testtest_Handler_IamRolePolicy_AF0279BD": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicy", + "uniqueId": "testtest_Handler_IamRolePolicy_AF0279BD" + } + }, + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"none:null\",\"Resource\":\"*\"}]}", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_iam_role_policy_attachment": { + "testtest_Handler_IamRolePolicyAttachment_ADF4752D": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicyAttachment", + "uniqueId": "testtest_Handler_IamRolePolicyAttachment_ADF4752D" + } + }, + "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_lambda_function": { + "testtest_Handler_295107CC": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/Default", + "uniqueId": "testtest_Handler_295107CC" + } + }, + "environment": { + "variables": { + "WING_FUNCTION_NAME": "Handler-c8f4f2a1", + "WING_TARGET": "tf-aws" + } + }, + "function_name": "Handler-c8f4f2a1", + "handler": "index.handler", + "publish": true, + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.arn}", + "runtime": "nodejs18.x", + "s3_bucket": "${aws_s3_bucket.Code.bucket}", + "s3_key": "${aws_s3_object.testtest_Handler_S3Object_9F4E28A7.key}", + "timeout": 30, + "vpc_config": { + "security_group_ids": [], + "subnet_ids": [] + } + } + }, + "aws_s3_bucket": { + "Code": { + "//": { + "metadata": { + "path": "root/Default/Code", + "uniqueId": "Code" + } + }, + "bucket_prefix": "code-c84a50b1-" + } + }, + "aws_s3_object": { + "testtest_Handler_S3Object_9F4E28A7": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/S3Object", + "uniqueId": "testtest_Handler_S3Object_9F4E28A7" + } + }, + "bucket": "${aws_s3_bucket.Code.bucket}", + "key": "", + "source": "" + } + } + } +} +``` + +## preflight.js +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $y: ${context._lift(y)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(y, host, []); + } + super._registerBind(host, ops); + } + } + const y = "hello"; + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "lift_redefinition", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); + +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/lift_redefinition.w_test_sim.md b/tools/hangar/__snapshots__/test_corpus/valid/lift_redefinition.w_test_sim.md new file mode 100644 index 00000000000..7074e03b542 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/lift_redefinition.w_test_sim.md @@ -0,0 +1,12 @@ +# [lift_redefinition.w](../../../../../examples/tests/valid/lift_redefinition.w) | test | sim + +## stdout.log +```log +pass ─ lift_redefinition.wsim » root/env0/test:test + + +Tests 1 passed (1) +Test Files 1 passed (1) +Duration +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/lift_this.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/lift_this.w_compile_tf-aws.md new file mode 100644 index 00000000000..7253acb841c --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/lift_this.w_compile_tf-aws.md @@ -0,0 +1,261 @@ +# [lift_this.w](../../../../../examples/tests/valid/lift_this.w) | compile | tf-aws + +## inflight.$Closure1.js +```js +module.exports = function({ $f }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: f.foo() == 21")})(((await $f.foo()) === 21))}; + } + } + return $Closure1; +} + +``` + +## inflight.Foo.js +```js +module.exports = function({ }) { + class Foo { + constructor({ }) { + } + async bar() { + return this.x; + } + async foo() { + return ((await this.bar()) / 2); + } + async $inflight_init() { + this.x = 42; + } + } + return Foo; +} + +``` + +## main.tf.json +```json +{ + "//": { + "metadata": { + "backend": "local", + "stackName": "root", + "version": "0.17.0" + }, + "outputs": { + "root": { + "Default": { + "cloud.TestRunner": { + "TestFunctionArns": "WING_TEST_RUNNER_FUNCTION_ARNS" + } + } + } + } + }, + "output": { + "WING_TEST_RUNNER_FUNCTION_ARNS": { + "value": "[[\"root/Default/Default/test:test\",\"${aws_lambda_function.testtest_Handler_295107CC.arn}\"]]" + } + }, + "provider": { + "aws": [ + {} + ] + }, + "resource": { + "aws_iam_role": { + "testtest_Handler_IamRole_15693C93": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRole", + "uniqueId": "testtest_Handler_IamRole_15693C93" + } + }, + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}" + } + }, + "aws_iam_role_policy": { + "testtest_Handler_IamRolePolicy_AF0279BD": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicy", + "uniqueId": "testtest_Handler_IamRolePolicy_AF0279BD" + } + }, + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"none:null\",\"Resource\":\"*\"}]}", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_iam_role_policy_attachment": { + "testtest_Handler_IamRolePolicyAttachment_ADF4752D": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicyAttachment", + "uniqueId": "testtest_Handler_IamRolePolicyAttachment_ADF4752D" + } + }, + "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_lambda_function": { + "testtest_Handler_295107CC": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/Default", + "uniqueId": "testtest_Handler_295107CC" + } + }, + "environment": { + "variables": { + "WING_FUNCTION_NAME": "Handler-c8f4f2a1", + "WING_TARGET": "tf-aws" + } + }, + "function_name": "Handler-c8f4f2a1", + "handler": "index.handler", + "publish": true, + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.arn}", + "runtime": "nodejs18.x", + "s3_bucket": "${aws_s3_bucket.Code.bucket}", + "s3_key": "${aws_s3_object.testtest_Handler_S3Object_9F4E28A7.key}", + "timeout": 30, + "vpc_config": { + "security_group_ids": [], + "subnet_ids": [] + } + } + }, + "aws_s3_bucket": { + "Code": { + "//": { + "metadata": { + "path": "root/Default/Code", + "uniqueId": "Code" + } + }, + "bucket_prefix": "code-c84a50b1-" + } + }, + "aws_s3_object": { + "testtest_Handler_S3Object_9F4E28A7": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/S3Object", + "uniqueId": "testtest_Handler_S3Object_9F4E28A7" + } + }, + "bucket": "${aws_s3_bucket.Code.bucket}", + "key": "", + "source": "" + } + } + } +} +``` + +## preflight.js +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class Foo extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this._addInflightOps("bar", "foo", "$inflight_init", "x"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.Foo.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const FooClient = ${Foo._toInflightType(this).text}; + const client = new FooClient({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("$inflight_init")) { + Foo._registerBindObject(this, host, ["x"]); + } + if (ops.includes("bar")) { + Foo._registerBindObject(this, host, ["x"]); + } + if (ops.includes("foo")) { + Foo._registerBindObject(this, host, ["bar"]); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $f: ${context._lift(f)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(f, host, ["foo"]); + } + super._registerBind(host, ops); + } + } + const f = new Foo(this,"Foo"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "lift_this", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); + +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/lift_this.w_test_sim.md b/tools/hangar/__snapshots__/test_corpus/valid/lift_this.w_test_sim.md new file mode 100644 index 00000000000..a68c01afa06 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/lift_this.w_test_sim.md @@ -0,0 +1,12 @@ +# [lift_this.w](../../../../../examples/tests/valid/lift_this.w) | test | sim + +## stdout.log +```log +pass ─ lift_this.wsim » root/env0/test:test + + +Tests 1 passed (1) +Test Files 1 passed (1) +Duration +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure.w_compile_tf-aws.md new file mode 100644 index 00000000000..ab5168d42d1 --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure.w_compile_tf-aws.md @@ -0,0 +1,532 @@ +# [lift_via_closure.w](../../../../../examples/tests/valid/lift_via_closure.w) | compile | tf-aws + +## inflight.$Closure1.js +```js +module.exports = function({ $bucket2 }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $bucket2.put("hello","world")); + } + } + return $Closure1; +} + +``` + +## inflight.$Closure2.js +```js +module.exports = function({ $fn }) { + class $Closure2 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $fn()); + } + } + return $Closure2; +} + +``` + +## inflight.$Closure3.js +```js +module.exports = function({ $bucket2, $fn2, $fn2_bucket }) { + class $Closure3 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $fn2()); + {((cond) => {if (!cond) throw new Error("assertion failed: fn2.bucket.get(\"hello\") == \"world\"")})(((await $fn2_bucket.get("hello")) === "world"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: fn2.listFiles().length == 1")})(((await $fn2.listFiles()).length === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: bucket2.get(\"b2\") == \"world\"")})(((await $bucket2.get("b2")) === "world"))}; + } + } + return $Closure3; +} + +``` + +## inflight.MyClosure.js +```js +module.exports = function({ $bucket2 }) { + class MyClosure { + constructor({ $this_bucket }) { + this.$this_bucket = $this_bucket; + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + {console.log("handle called")}; + (await this.putFile()); + } + async putFile() { + {console.log("putFile called")}; + (await this.$this_bucket.put("hello","world")); + } + async listFiles() { + (await $bucket2.put("b2","world")); + return (await this.$this_bucket.list()); + } + } + return MyClosure; +} + +``` + +## main.tf.json +```json +{ + "//": { + "metadata": { + "backend": "local", + "stackName": "root", + "version": "0.17.0" + }, + "outputs": { + "root": { + "Default": { + "cloud.TestRunner": { + "TestFunctionArns": "WING_TEST_RUNNER_FUNCTION_ARNS" + } + } + } + } + }, + "output": { + "WING_TEST_RUNNER_FUNCTION_ARNS": { + "value": "[[\"root/Default/Default/test:call synthetic closure class as a function\",\"${aws_lambda_function.testcallsyntheticclosureclassasafunction_Handler_577F53A9.arn}\"],[\"root/Default/Default/test:call non-synthetic closure as a function\",\"${aws_lambda_function.testcallnon-syntheticclosureasafunction_Handler_8C8F5E97.arn}\"]]" + } + }, + "provider": { + "aws": [ + {} + ] + }, + "resource": { + "aws_iam_role": { + "testcallnon-syntheticclosureasafunction_Handler_IamRole_A06F3749": { + "//": { + "metadata": { + "path": "root/Default/Default/test:call non-synthetic closure as a function/Handler/IamRole", + "uniqueId": "testcallnon-syntheticclosureasafunction_Handler_IamRole_A06F3749" + } + }, + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}" + }, + "testcallsyntheticclosureclassasafunction_Handler_IamRole_75DB8DE1": { + "//": { + "metadata": { + "path": "root/Default/Default/test:call synthetic closure class as a function/Handler/IamRole", + "uniqueId": "testcallsyntheticclosureclassasafunction_Handler_IamRole_75DB8DE1" + } + }, + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}" + } + }, + "aws_iam_role_policy": { + "testcallnon-syntheticclosureasafunction_Handler_IamRolePolicy_3CCA75F8": { + "//": { + "metadata": { + "path": "root/Default/Default/test:call non-synthetic closure as a function/Handler/IamRolePolicy", + "uniqueId": "testcallnon-syntheticclosureasafunction_Handler_IamRolePolicy_3CCA75F8" + } + }, + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"s3:PutObject*\",\"s3:Abort*\",\"s3:GetObject*\",\"s3:GetBucket*\"],\"Resource\":[\"${aws_s3_bucket.cloudBucket.arn}\",\"${aws_s3_bucket.cloudBucket.arn}/*\"],\"Effect\":\"Allow\"},{\"Action\":[\"s3:List*\",\"s3:PutObject*\",\"s3:Abort*\",\"s3:GetObject*\",\"s3:GetBucket*\"],\"Resource\":[\"${aws_s3_bucket.MyClosure_cloudBucket_4DAD12C0.arn}\",\"${aws_s3_bucket.MyClosure_cloudBucket_4DAD12C0.arn}/*\"],\"Effect\":\"Allow\"}]}", + "role": "${aws_iam_role.testcallnon-syntheticclosureasafunction_Handler_IamRole_A06F3749.name}" + }, + "testcallsyntheticclosureclassasafunction_Handler_IamRolePolicy_64E9CC96": { + "//": { + "metadata": { + "path": "root/Default/Default/test:call synthetic closure class as a function/Handler/IamRolePolicy", + "uniqueId": "testcallsyntheticclosureclassasafunction_Handler_IamRolePolicy_64E9CC96" + } + }, + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"s3:PutObject*\",\"s3:Abort*\"],\"Resource\":[\"${aws_s3_bucket.cloudBucket.arn}\",\"${aws_s3_bucket.cloudBucket.arn}/*\"],\"Effect\":\"Allow\"}]}", + "role": "${aws_iam_role.testcallsyntheticclosureclassasafunction_Handler_IamRole_75DB8DE1.name}" + } + }, + "aws_iam_role_policy_attachment": { + "testcallnon-syntheticclosureasafunction_Handler_IamRolePolicyAttachment_228ED90F": { + "//": { + "metadata": { + "path": "root/Default/Default/test:call non-synthetic closure as a function/Handler/IamRolePolicyAttachment", + "uniqueId": "testcallnon-syntheticclosureasafunction_Handler_IamRolePolicyAttachment_228ED90F" + } + }, + "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "role": "${aws_iam_role.testcallnon-syntheticclosureasafunction_Handler_IamRole_A06F3749.name}" + }, + "testcallsyntheticclosureclassasafunction_Handler_IamRolePolicyAttachment_8F878B5F": { + "//": { + "metadata": { + "path": "root/Default/Default/test:call synthetic closure class as a function/Handler/IamRolePolicyAttachment", + "uniqueId": "testcallsyntheticclosureclassasafunction_Handler_IamRolePolicyAttachment_8F878B5F" + } + }, + "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "role": "${aws_iam_role.testcallsyntheticclosureclassasafunction_Handler_IamRole_75DB8DE1.name}" + } + }, + "aws_lambda_function": { + "testcallnon-syntheticclosureasafunction_Handler_8C8F5E97": { + "//": { + "metadata": { + "path": "root/Default/Default/test:call non-synthetic closure as a function/Handler/Default", + "uniqueId": "testcallnon-syntheticclosureasafunction_Handler_8C8F5E97" + } + }, + "environment": { + "variables": { + "BUCKET_NAME_bbe94f63": "${aws_s3_bucket.MyClosure_cloudBucket_4DAD12C0.bucket}", + "BUCKET_NAME_d755b447": "${aws_s3_bucket.cloudBucket.bucket}", + "WING_FUNCTION_NAME": "Handler-c88b1fea", + "WING_TARGET": "tf-aws" + } + }, + "function_name": "Handler-c88b1fea", + "handler": "index.handler", + "publish": true, + "role": "${aws_iam_role.testcallnon-syntheticclosureasafunction_Handler_IamRole_A06F3749.arn}", + "runtime": "nodejs18.x", + "s3_bucket": "${aws_s3_bucket.Code.bucket}", + "s3_key": "${aws_s3_object.testcallnon-syntheticclosureasafunction_Handler_S3Object_F2F52456.key}", + "timeout": 30, + "vpc_config": { + "security_group_ids": [], + "subnet_ids": [] + } + }, + "testcallsyntheticclosureclassasafunction_Handler_577F53A9": { + "//": { + "metadata": { + "path": "root/Default/Default/test:call synthetic closure class as a function/Handler/Default", + "uniqueId": "testcallsyntheticclosureclassasafunction_Handler_577F53A9" + } + }, + "environment": { + "variables": { + "BUCKET_NAME_d755b447": "${aws_s3_bucket.cloudBucket.bucket}", + "WING_FUNCTION_NAME": "Handler-c822e354", + "WING_TARGET": "tf-aws" + } + }, + "function_name": "Handler-c822e354", + "handler": "index.handler", + "publish": true, + "role": "${aws_iam_role.testcallsyntheticclosureclassasafunction_Handler_IamRole_75DB8DE1.arn}", + "runtime": "nodejs18.x", + "s3_bucket": "${aws_s3_bucket.Code.bucket}", + "s3_key": "${aws_s3_object.testcallsyntheticclosureclassasafunction_Handler_S3Object_CBB724B2.key}", + "timeout": 30, + "vpc_config": { + "security_group_ids": [], + "subnet_ids": [] + } + } + }, + "aws_s3_bucket": { + "Code": { + "//": { + "metadata": { + "path": "root/Default/Code", + "uniqueId": "Code" + } + }, + "bucket_prefix": "code-c84a50b1-" + }, + "MyClosure_cloudBucket_4DAD12C0": { + "//": { + "metadata": { + "path": "root/Default/Default/MyClosure/cloud.Bucket/Default", + "uniqueId": "MyClosure_cloudBucket_4DAD12C0" + } + }, + "bucket_prefix": "cloud-bucket-c8b87a6b-", + "force_destroy": false + }, + "cloudBucket": { + "//": { + "metadata": { + "path": "root/Default/Default/cloud.Bucket/Default", + "uniqueId": "cloudBucket" + } + }, + "bucket_prefix": "cloud-bucket-c87175e7-", + "force_destroy": false + } + }, + "aws_s3_bucket_public_access_block": { + "MyClosure_cloudBucket_PublicAccessBlock_EFF6E688": { + "//": { + "metadata": { + "path": "root/Default/Default/MyClosure/cloud.Bucket/PublicAccessBlock", + "uniqueId": "MyClosure_cloudBucket_PublicAccessBlock_EFF6E688" + } + }, + "block_public_acls": true, + "block_public_policy": true, + "bucket": "${aws_s3_bucket.MyClosure_cloudBucket_4DAD12C0.bucket}", + "ignore_public_acls": true, + "restrict_public_buckets": true + }, + "cloudBucket_PublicAccessBlock_5946CCE8": { + "//": { + "metadata": { + "path": "root/Default/Default/cloud.Bucket/PublicAccessBlock", + "uniqueId": "cloudBucket_PublicAccessBlock_5946CCE8" + } + }, + "block_public_acls": true, + "block_public_policy": true, + "bucket": "${aws_s3_bucket.cloudBucket.bucket}", + "ignore_public_acls": true, + "restrict_public_buckets": true + } + }, + "aws_s3_bucket_server_side_encryption_configuration": { + "MyClosure_cloudBucket_Encryption_31C1B5A0": { + "//": { + "metadata": { + "path": "root/Default/Default/MyClosure/cloud.Bucket/Encryption", + "uniqueId": "MyClosure_cloudBucket_Encryption_31C1B5A0" + } + }, + "bucket": "${aws_s3_bucket.MyClosure_cloudBucket_4DAD12C0.bucket}", + "rule": [ + { + "apply_server_side_encryption_by_default": { + "sse_algorithm": "AES256" + } + } + ] + }, + "cloudBucket_Encryption_77B6AEEF": { + "//": { + "metadata": { + "path": "root/Default/Default/cloud.Bucket/Encryption", + "uniqueId": "cloudBucket_Encryption_77B6AEEF" + } + }, + "bucket": "${aws_s3_bucket.cloudBucket.bucket}", + "rule": [ + { + "apply_server_side_encryption_by_default": { + "sse_algorithm": "AES256" + } + } + ] + } + }, + "aws_s3_object": { + "testcallnon-syntheticclosureasafunction_Handler_S3Object_F2F52456": { + "//": { + "metadata": { + "path": "root/Default/Default/test:call non-synthetic closure as a function/Handler/S3Object", + "uniqueId": "testcallnon-syntheticclosureasafunction_Handler_S3Object_F2F52456" + } + }, + "bucket": "${aws_s3_bucket.Code.bucket}", + "key": "", + "source": "" + }, + "testcallsyntheticclosureclassasafunction_Handler_S3Object_CBB724B2": { + "//": { + "metadata": { + "path": "root/Default/Default/test:call synthetic closure class as a function/Handler/S3Object", + "uniqueId": "testcallsyntheticclosureclassasafunction_Handler_S3Object_CBB724B2" + } + }, + "bucket": "${aws_s3_bucket.Code.bucket}", + "key": "", + "source": "" + } + } + } +} +``` + +## preflight.js +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $bucket2: ${context._lift(bucket2)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(bucket2, host, ["put"]); + } + super._registerBind(host, ops); + } + } + class MyClosure extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.bucket = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("handle", "putFile", "listFiles", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyClosure.js")({ + $bucket2: ${context._lift(bucket2)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyClosureClient = ${MyClosure._toInflightType(this).text}; + const client = new MyClosureClient({ + $this_bucket: ${this._lift(this.bucket)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + MyClosure._registerBindObject(this, host, ["putFile"]); + } + if (ops.includes("listFiles")) { + MyClosure._registerBindObject(bucket2, host, ["put"]); + MyClosure._registerBindObject(this.bucket, host, ["list"]); + } + if (ops.includes("putFile")) { + MyClosure._registerBindObject(this.bucket, host, ["put"]); + } + super._registerBind(host, ops); + } + } + class $Closure2 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure2.js")({ + $fn: ${context._lift(fn)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure2Client = ${$Closure2._toInflightType(this).text}; + const client = new $Closure2Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure2._registerBindObject(fn, host, ["handle"]); + } + super._registerBind(host, ops); + } + } + class $Closure3 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure3.js")({ + $bucket2: ${context._lift(bucket2)}, + $fn2: ${context._lift(fn2)}, + $fn2_bucket: ${context._lift(fn2.bucket)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure3Client = ${$Closure3._toInflightType(this).text}; + const client = new $Closure3Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure3._registerBindObject(bucket2, host, ["get"]); + $Closure3._registerBindObject(fn2, host, ["handle", "listFiles"]); + $Closure3._registerBindObject(fn2.bucket, host, ["get"]); + } + super._registerBind(host, ops); + } + } + const bucket2 = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + const fn = new $Closure1(this,"$Closure1"); + const fn2 = new MyClosure(this,"MyClosure"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:call synthetic closure class as a function",new $Closure2(this,"$Closure2")); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:call non-synthetic closure as a function",new $Closure3(this,"$Closure3")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "lift_via_closure", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); + +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure.w_test_sim.md b/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure.w_test_sim.md new file mode 100644 index 00000000000..a52d7521bcf --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure.w_test_sim.md @@ -0,0 +1,15 @@ +# [lift_via_closure.w](../../../../../examples/tests/valid/lift_via_closure.w) | test | sim + +## stdout.log +```log +pass ─ lift_via_closure.wsim » root/env0/test:call synthetic closure class as a function +pass ┌ lift_via_closure.wsim » root/env1/test:call non-synthetic closure as a function + │ handle called + └ putFile called + + +Tests 2 passed (2) +Test Files 1 passed (1) +Duration +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure_explicit.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure_explicit.w_compile_tf-aws.md new file mode 100644 index 00000000000..6722f9e3f6c --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure_explicit.w_compile_tf-aws.md @@ -0,0 +1,268 @@ +# [lift_via_closure_explicit.w](../../../../../examples/tests/valid/lift_via_closure_explicit.w) | compile | tf-aws + +## inflight.$Closure1.js +```js +module.exports = function({ $fn }) { + class $Closure1 { + constructor({ }) { + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await $fn()); + } + } + return $Closure1; +} + +``` + +## inflight.MyClosure.js +```js +module.exports = function({ }) { + class MyClosure { + constructor({ $this_q }) { + this.$this_q = $this_q; + const $obj = (...args) => this.handle(...args); + Object.setPrototypeOf($obj, this); + return $obj; + } + async handle() { + (await this.$this_q.push("hello")); + } + } + return MyClosure; +} + +``` + +## main.tf.json +```json +{ + "//": { + "metadata": { + "backend": "local", + "stackName": "root", + "version": "0.17.0" + }, + "outputs": { + "root": { + "Default": { + "cloud.TestRunner": { + "TestFunctionArns": "WING_TEST_RUNNER_FUNCTION_ARNS" + } + } + } + } + }, + "output": { + "WING_TEST_RUNNER_FUNCTION_ARNS": { + "value": "[[\"root/Default/Default/test:test\",\"${aws_lambda_function.testtest_Handler_295107CC.arn}\"]]" + } + }, + "provider": { + "aws": [ + {} + ] + }, + "resource": { + "aws_iam_role": { + "testtest_Handler_IamRole_15693C93": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRole", + "uniqueId": "testtest_Handler_IamRole_15693C93" + } + }, + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}" + } + }, + "aws_iam_role_policy": { + "testtest_Handler_IamRolePolicy_AF0279BD": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicy", + "uniqueId": "testtest_Handler_IamRolePolicy_AF0279BD" + } + }, + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"sqs:SendMessage\"],\"Resource\":[\"${aws_sqs_queue.MyClosure_cloudQueue_465FD228.arn}\"],\"Effect\":\"Allow\"}]}", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_iam_role_policy_attachment": { + "testtest_Handler_IamRolePolicyAttachment_ADF4752D": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/IamRolePolicyAttachment", + "uniqueId": "testtest_Handler_IamRolePolicyAttachment_ADF4752D" + } + }, + "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.name}" + } + }, + "aws_lambda_function": { + "testtest_Handler_295107CC": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/Default", + "uniqueId": "testtest_Handler_295107CC" + } + }, + "environment": { + "variables": { + "QUEUE_URL_6ec5b2e4": "${aws_sqs_queue.MyClosure_cloudQueue_465FD228.url}", + "WING_FUNCTION_NAME": "Handler-c8f4f2a1", + "WING_TARGET": "tf-aws" + } + }, + "function_name": "Handler-c8f4f2a1", + "handler": "index.handler", + "publish": true, + "role": "${aws_iam_role.testtest_Handler_IamRole_15693C93.arn}", + "runtime": "nodejs18.x", + "s3_bucket": "${aws_s3_bucket.Code.bucket}", + "s3_key": "${aws_s3_object.testtest_Handler_S3Object_9F4E28A7.key}", + "timeout": 30, + "vpc_config": { + "security_group_ids": [], + "subnet_ids": [] + } + } + }, + "aws_s3_bucket": { + "Code": { + "//": { + "metadata": { + "path": "root/Default/Code", + "uniqueId": "Code" + } + }, + "bucket_prefix": "code-c84a50b1-" + } + }, + "aws_s3_object": { + "testtest_Handler_S3Object_9F4E28A7": { + "//": { + "metadata": { + "path": "root/Default/Default/test:test/Handler/S3Object", + "uniqueId": "testtest_Handler_S3Object_9F4E28A7" + } + }, + "bucket": "${aws_s3_bucket.Code.bucket}", + "key": "", + "source": "" + } + }, + "aws_sqs_queue": { + "MyClosure_cloudQueue_465FD228": { + "//": { + "metadata": { + "path": "root/Default/Default/MyClosure/cloud.Queue/Default", + "uniqueId": "MyClosure_cloudQueue_465FD228" + } + }, + "name": "cloud-Queue-c8cccb9b" + } + } + } +} +``` + +## preflight.js +```js +const $stdlib = require('@winglang/sdk'); +const $outdir = process.env.WING_SYNTH_DIR ?? "."; +const std = $stdlib.std; +const $wing_is_test = process.env.WING_IS_TEST === "true"; +const $AppBase = $stdlib.core.App.for(process.env.WING_TARGET); +const cloud = require('@winglang/sdk').cloud; +class $Root extends $stdlib.std.Resource { + constructor(scope, id) { + super(scope, id); + class MyClosure extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.q = this.node.root.newAbstract("@winglang/sdk.cloud.Queue",this,"cloud.Queue"); + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.MyClosure.js")({ + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const MyClosureClient = ${MyClosure._toInflightType(this).text}; + const client = new MyClosureClient({ + $this_q: ${this._lift(this.q)}, + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + MyClosure._registerBindObject(this.q, host, ["push"]); + } + super._registerBind(host, ops); + } + } + class $Closure1 extends $stdlib.std.Resource { + constructor(scope, id, ) { + super(scope, id); + this.display.hidden = true; + this._addInflightOps("handle", "$inflight_init"); + } + static _toInflightType(context) { + return $stdlib.core.NodeJsCode.fromInline(` + require("./inflight.$Closure1.js")({ + $fn: ${context._lift(fn)}, + }) + `); + } + _toInflight() { + return $stdlib.core.NodeJsCode.fromInline(` + (await (async () => { + const $Closure1Client = ${$Closure1._toInflightType(this).text}; + const client = new $Closure1Client({ + }); + if (client.$inflight_init) { await client.$inflight_init(); } + return client; + })()) + `); + } + _registerBind(host, ops) { + if (ops.includes("handle")) { + $Closure1._registerBindObject(fn, host, ["handle"]); + } + super._registerBind(host, ops); + } + } + const fn = new MyClosure(this,"MyClosure"); + this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:test",new $Closure1(this,"$Closure1")); + } +} +class $App extends $AppBase { + constructor() { + super({ outdir: $outdir, name: "lift_via_closure_explicit", plugins: $plugins, isTestEnvironment: $wing_is_test }); + if ($wing_is_test) { + new $Root(this, "env0"); + const $test_runner = this.testRunner; + const $tests = $test_runner.findTests(); + for (let $i = 1; $i < $tests.length; $i++) { + new $Root(this, "env" + $i); + } + } else { + new $Root(this, "Default"); + } + } +} +new $App().synth(); + +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure_explicit.w_test_sim.md b/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure_explicit.w_test_sim.md new file mode 100644 index 00000000000..a764b89d2ae --- /dev/null +++ b/tools/hangar/__snapshots__/test_corpus/valid/lift_via_closure_explicit.w_test_sim.md @@ -0,0 +1,12 @@ +# [lift_via_closure_explicit.w](../../../../../examples/tests/valid/lift_via_closure_explicit.w) | test | sim + +## stdout.log +```log +pass ─ lift_via_closure_explicit.wsim » root/env0/test:test + + +Tests 1 passed (1) +Test Files 1 passed (1) +Duration +``` + diff --git a/tools/hangar/__snapshots__/test_corpus/valid/nil.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/nil.w_compile_tf-aws.md index 7bc4adf8a5b..cfb058d7d72 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/nil.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/nil.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ foo }) { +module.exports = function({ $foo }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: foo.returnNil(true)? == true")})(((((await foo.returnNil(true))) != null) === true))}; - {((cond) => {if (!cond) throw new Error("assertion failed: foo.returnNil(false)? == false")})(((((await foo.returnNil(false))) != null) === false))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: foo.returnNil(true)? == true")})(((((await $foo.returnNil(true))) != null) === true))}; + {((cond) => {if (!cond) throw new Error("assertion failed: foo.returnNil(false)? == false")})(((((await $foo.returnNil(false))) != null) === false))}; } } return $Closure1; @@ -23,23 +21,21 @@ module.exports = function({ foo }) { ## inflight.$Closure2.js ```js -module.exports = function({ foo }) { +module.exports = function({ $foo }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: foo.getOptionalValue()? == false")})(((((await foo.getOptionalValue())) != null) === false))}; - (await foo.setOptionalValue("hello")); - {((cond) => {if (!cond) throw new Error("assertion failed: foo.getOptionalValue()? == true")})(((((await foo.getOptionalValue())) != null) === true))}; - {((cond) => {if (!cond) throw new Error("assertion failed: foo.getOptionalValue() != nil")})(((await foo.getOptionalValue()) !== undefined))}; - (await foo.setOptionalValue(undefined)); - {((cond) => {if (!cond) throw new Error("assertion failed: foo.getOptionalValue()? == false")})(((((await foo.getOptionalValue())) != null) === false))}; - {((cond) => {if (!cond) throw new Error("assertion failed: foo.getOptionalValue() == nil")})(((await foo.getOptionalValue()) === undefined))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: foo.getOptionalValue()? == false")})(((((await $foo.getOptionalValue())) != null) === false))}; + (await $foo.setOptionalValue("hello")); + {((cond) => {if (!cond) throw new Error("assertion failed: foo.getOptionalValue()? == true")})(((((await $foo.getOptionalValue())) != null) === true))}; + {((cond) => {if (!cond) throw new Error("assertion failed: foo.getOptionalValue() != nil")})(((await $foo.getOptionalValue()) !== undefined))}; + (await $foo.setOptionalValue(undefined)); + {((cond) => {if (!cond) throw new Error("assertion failed: foo.getOptionalValue()? == false")})(((((await $foo.getOptionalValue())) != null) === false))}; + {((cond) => {if (!cond) throw new Error("assertion failed: foo.getOptionalValue() == nil")})(((await $foo.getOptionalValue()) === undefined))}; } } return $Closure2; @@ -53,21 +49,21 @@ module.exports = function({ }) { class Foo { constructor({ }) { } - async $inflight_init() { - this.optionalVar = undefined; - } - async returnNil(t) { + async returnNil(t) { if (t) { return "hello"; } return undefined; } - async setOptionalValue(msg) { + async setOptionalValue(msg) { this.optionalVar = msg; } - async getOptionalValue() { + async getOptionalValue() { return this.optionalVar; } + async $inflight_init() { + this.optionalVar = undefined; + } } return Foo; } @@ -275,12 +271,11 @@ class $Root extends $stdlib.std.Resource { class Foo extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("returnNil", "setOptionalValue", "getOptionalValue", "optionalVar"); + this._addInflightOps("returnNil", "setOptionalValue", "getOptionalValue", "$inflight_init", "optionalVar"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } @@ -297,12 +292,13 @@ class $Root extends $stdlib.std.Resource { } _registerBind(host, ops) { if (ops.includes("$inflight_init")) { + Foo._registerBindObject(this, host, ["optionalVar"]); } if (ops.includes("getOptionalValue")) { - } - if (ops.includes("returnNil")) { + Foo._registerBindObject(this, host, ["optionalVar"]); } if (ops.includes("setOptionalValue")) { + Foo._registerBindObject(this, host, ["optionalVar"]); } super._registerBind(host, ops); } @@ -311,14 +307,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const foo_client = context._lift(foo); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - foo: ${foo_client}, + require("./inflight.$Closure1.js")({ + $foo: ${context._lift(foo)}, }) `); } @@ -334,9 +328,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(foo, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(foo, host, ["returnNil"]); } @@ -347,14 +338,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const foo_client = context._lift(foo); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - foo: ${foo_client}, + require("./inflight.$Closure2.js")({ + $foo: ${context._lift(foo)}, }) `); } @@ -370,9 +359,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(foo, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(foo, host, ["getOptionalValue", "setOptionalValue"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/optionals.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/optionals.w_compile_tf-aws.md index f9ef075a553..90075bf7fb3 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/optionals.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/optionals.w_compile_tf-aws.md @@ -2,19 +2,17 @@ ## inflight.$Closure1.js ```js -module.exports = function({ payloadWithoutOptions, payloadWithBucket }) { +module.exports = function({ $__payloadWithBucket_c_____null_, $__payloadWithoutOptions_b_____null_, $payloadWithBucket_c }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: payloadWithoutOptions.b? == false")})((((payloadWithoutOptions.b) != null) === false))}; - if (((payloadWithBucket.c) != null)) { - (await payloadWithBucket.c?.put?.("x.txt","something")); + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: payloadWithoutOptions.b? == false")})(($__payloadWithoutOptions_b_____null_ === false))}; + if ($__payloadWithBucket_c_____null_) { + (await $payloadWithBucket_c?.put?.("x.txt","something")); } } } @@ -27,12 +25,7 @@ module.exports = function({ payloadWithoutOptions, payloadWithBucket }) { ```js module.exports = function({ }) { class Node { - constructor({ left, right, value }) { - this.left = left; - this.right = right; - this.value = value; - } - async $inflight_init() { + constructor({ }) { } } return Node; @@ -42,12 +35,10 @@ module.exports = function({ }) { ## inflight.Sub.js ```js -module.exports = function({ Super }) { - class Sub extends Super { - constructor({ name }) { - super({name}); - } - async $inflight_init() { +module.exports = function({ $Super }) { + class Sub extends $Super { + constructor({ }) { + super({ }); } } return Sub; @@ -57,12 +48,10 @@ module.exports = function({ Super }) { ## inflight.Sub1.js ```js -module.exports = function({ Super }) { - class Sub1 extends Super { - constructor({ name }) { - super({name}); - } - async $inflight_init() { +module.exports = function({ $Super }) { + class Sub1 extends $Super { + constructor({ }) { + super({ }); } } return Sub1; @@ -74,10 +63,7 @@ module.exports = function({ Super }) { ```js module.exports = function({ }) { class Super { - constructor({ name }) { - this.name = name; - } - async $inflight_init() { + constructor({ }) { } } return Super; @@ -265,101 +251,75 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.name = "Super"; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Super.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Super.js")({ }) `); } _toInflight() { - const name_client = this._lift(this.name); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const SuperClient = ${Super._toInflightType(this).text}; const client = new SuperClient({ - name: ${name_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Super._registerBindObject(this.name, host, []); - } - super._registerBind(host, ops); - } } class Sub extends Super { constructor(scope, id, ) { super(scope, id); this.name = "Sub"; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Sub.js"; - const SuperClient = Super._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Super: ${SuperClient.text}, + require("./inflight.Sub.js")({ + $Super: ${context._lift(Super)}, }) `); } _toInflight() { - const name_client = this._lift(this.name); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const SubClient = ${Sub._toInflightType(this).text}; const client = new SubClient({ - name: ${name_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Sub._registerBindObject(this.name, host, []); - } - super._registerBind(host, ops); - } } class Sub1 extends Super { constructor(scope, id, ) { super(scope, id); this.name = "Sub"; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Sub1.js"; - const SuperClient = Super._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Super: ${SuperClient.text}, + require("./inflight.Sub1.js")({ + $Super: ${context._lift(Super)}, }) `); } _toInflight() { - const name_client = this._lift(this.name); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const Sub1Client = ${Sub1._toInflightType(this).text}; const client = new Sub1Client({ - name: ${name_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Sub1._registerBindObject(this.name, host, []); - } - super._registerBind(host, ops); - } } class Node extends $stdlib.std.Resource { constructor(scope, id, value, left, right) { @@ -367,54 +327,38 @@ class $Root extends $stdlib.std.Resource { this.value = value; this.left = left; this.right = right; + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Node.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Node.js")({ }) `); } _toInflight() { - const left_client = this._lift(this.left); - const right_client = this._lift(this.right); - const value_client = this._lift(this.value); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const NodeClient = ${Node._toInflightType(this).text}; const client = new NodeClient({ - left: ${left_client}, - right: ${right_client}, - value: ${value_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Node._registerBindObject(this.left, host, []); - Node._registerBindObject(this.right, host, []); - Node._registerBindObject(this.value, host, []); - } - super._registerBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const payloadWithoutOptions_client = context._lift(payloadWithoutOptions); - const payloadWithBucket_client = context._lift(payloadWithBucket); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - payloadWithoutOptions: ${payloadWithoutOptions_client}, - payloadWithBucket: ${payloadWithBucket_client}, + require("./inflight.$Closure1.js")({ + $__payloadWithBucket_c_____null_: ${context._lift(((payloadWithBucket.c) != null))}, + $__payloadWithoutOptions_b_____null_: ${context._lift(((payloadWithoutOptions.b) != null))}, + $payloadWithBucket_c: ${context._lift(payloadWithBucket.c)}, }) `); } @@ -430,13 +374,10 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(payloadWithBucket, host, []); - $Closure1._registerBindObject(payloadWithoutOptions, host, []); - } if (ops.includes("handle")) { + $Closure1._registerBindObject(((payloadWithBucket.c) != null), host, []); + $Closure1._registerBindObject(((payloadWithoutOptions.b) != null), host, []); $Closure1._registerBindObject(payloadWithBucket.c, host, ["put"]); - $Closure1._registerBindObject(payloadWithoutOptions.b, host, []); } super._registerBind(host, ops); } @@ -472,7 +413,7 @@ class $Root extends $stdlib.std.Resource { {((cond) => {if (!cond) throw new Error("assertion failed: true")})(true)}; } } - const tryParseName = (fullName) => { + const tryParseName = ((fullName) => { const parts = (fullName.split(" ")); if ((parts.length < 1)) { return undefined; @@ -481,8 +422,7 @@ class $Root extends $stdlib.std.Resource { "first": (parts.at(0)), "last": (parts.at(1)),} ; - } - ; + }); { const $IF_LET_VALUE = (tryParseName("Good Name")); if ($IF_LET_VALUE != undefined) { @@ -544,7 +484,7 @@ class $Root extends $stdlib.std.Resource { } } } - const fun = (a) => { + const fun = ((a) => { { const $IF_LET_VALUE = a; if ($IF_LET_VALUE != undefined) { @@ -555,8 +495,7 @@ class $Root extends $stdlib.std.Resource { return "default"; } } - } - ; + }); {((cond) => {if (!cond) throw new Error("assertion failed: fun(\"hello\") == \"hello\"")})(((fun("hello")) === "hello"))}; {((cond) => {if (!cond) throw new Error("assertion failed: fun(nil) == \"default\"")})(((fun(undefined)) === "default"))}; const tree = new Node(this,"eight",8,new Node(this,"three",3,new Node(this,"one",1,undefined,undefined),new Node(this,"six",6,undefined,undefined)),new Node(this,"ten",10,undefined,new Node(this,"fourteen",14,new Node(this,"thirteen",13,undefined,undefined),undefined))); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/primitive_methods.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/primitive_methods.w_compile_tf-aws.md index 36ca977726b..c86af1acc4f 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/primitive_methods.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/primitive_methods.w_compile_tf-aws.md @@ -44,9 +44,8 @@ class $Root extends $stdlib.std.Resource { super(scope, id); const dur = (std.Duration.fromSeconds(60)); const dur2 = (std.Duration.fromSeconds(600)); - const f = (d) => { - } - ; + const f = ((d) => { + }); const stringy = String.raw({ raw: ["", ":", ""] }, dur.minutes, dur.seconds); {console.log(stringy)}; if ((stringy.includes("60") && (((stringy.split(":")).at(0)) === "60"))) { diff --git a/tools/hangar/__snapshots__/test_corpus/valid/print.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/print.w_compile_tf-aws.md index fdacec9ce25..3b96181e38c 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/print.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/print.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {console.log("inflight log 1.1")}; {console.log("inflight log 1.2")}; } @@ -30,9 +28,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {console.log("inflight log 2.1")}; {console.log("inflight log 2.2")}; } @@ -244,12 +240,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -264,24 +259,16 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure2 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure2.js")({ }) `); } @@ -296,13 +283,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } {console.log("preflight log")}; this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:log1",new $Closure1(this,"$Closure1")); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/reassignment.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/reassignment.w_compile_tf-aws.md index 55f94267114..37e0984420e 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/reassignment.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/reassignment.w_compile_tf-aws.md @@ -4,11 +4,7 @@ ```js module.exports = function({ }) { class R { - constructor({ f, f1 }) { - this.f = f; - this.f1 = f1; - } - async $inflight_init() { + constructor({ }) { } } return R; @@ -65,39 +61,28 @@ class $Root extends $stdlib.std.Resource { this.f = 1; this.f1 = 0; } + this._addInflightOps("$inflight_init"); } - inc() { + inc() { this.f = (this.f + 1); } static _toInflightType(context) { - const self_client_path = "././inflight.R.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.R.js")({ }) `); } _toInflight() { - const f_client = this._lift(this.f); - const f1_client = this._lift(this.f1); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const RClient = ${R._toInflightType(this).text}; const client = new RClient({ - f: ${f_client}, - f1: ${f1_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - R._registerBindObject(this.f, host, []); - R._registerBindObject(this.f1, host, []); - } - super._registerBind(host, ops); - } } let x = 5; {((cond) => {if (!cond) throw new Error("assertion failed: x == 5")})((x === 5))}; @@ -106,11 +91,10 @@ class $Root extends $stdlib.std.Resource { const r = new R(this,"R"); (r.inc()); {((cond) => {if (!cond) throw new Error("assertion failed: r.f == 2")})((r.f === 2))}; - const f = (arg) => { + const f = ((arg) => { arg = 0; return arg; - } - ; + }); const y = 1; {((cond) => {if (!cond) throw new Error("assertion failed: f(y) == 0")})(((f(y)) === 0))}; {((cond) => {if (!cond) throw new Error("assertion failed: y == 1")})((y === 1))}; diff --git a/tools/hangar/__snapshots__/test_corpus/valid/redis.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/redis.w_compile_tf-aws.md index 4778ad03b02..0a3e7bbaf55 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/redis.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/redis.w_compile_tf-aws.md @@ -2,22 +2,20 @@ ## inflight.$Closure1.js ```js -module.exports = function({ r, r2 }) { +module.exports = function({ $r, $r2 }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const connection = (await r.rawClient()); + async handle() { + const connection = (await $r.rawClient()); (await connection.set("wing","does redis")); const value = (await connection.get("wing")); {((cond) => {if (!cond) throw new Error("assertion failed: value == \"does redis\"")})((value === "does redis"))}; - (await r2.set("wing","does redis again")); - const value2 = (await r2.get("wing")); + (await $r2.set("wing","does redis again")); + const value2 = (await $r2.get("wing")); {((cond) => {if (!cond) throw new Error("assertion failed: value2 == \"does redis again\"")})((value2 === "does redis again"))}; } } @@ -486,16 +484,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const r_client = context._lift(r); - const r2_client = context._lift(r2); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - r: ${r_client}, - r2: ${r2_client}, + require("./inflight.$Closure1.js")({ + $r: ${context._lift(r)}, + $r2: ${context._lift(r2)}, }) `); } @@ -511,10 +506,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(r, host, []); - $Closure1._registerBindObject(r2, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(r, host, ["rawClient"]); $Closure1._registerBindObject(r2, host, ["get", "set"]); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/resource.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/resource.w_compile_tf-aws.md index 8ff475260f8..9bda4043e39 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/resource.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/resource.w_compile_tf-aws.md @@ -2,21 +2,20 @@ ## inflight.$Closure1.js ```js -module.exports = function({ res, bucket }) { +module.exports = function({ $bucket, $res, $res_foo }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const s = (await res.myMethod()); - {((cond) => {if (!cond) throw new Error("assertion failed: s == \"counter is: 101\"")})((s === "counter is: 101"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: bucket.list().length == 1")})(((await bucket.list()).length === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: res.foo.inflightField == 123")})((res.foo.inflightField === 123))}; - (await res.testTypeAccess()); + async handle() { + const s = (await $res.myMethod()); + {console.log(s)}; + {((cond) => {if (!cond) throw new Error("assertion failed: s == \"counter is: 201\"")})((s === "counter is: 201"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: bucket.list().length == 1")})(((await $bucket.list()).length === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: res.foo.inflightField == 123")})(($res_foo.inflightField === 123))}; + (await $res.testTypeAccess()); } } return $Closure1; @@ -26,17 +25,15 @@ module.exports = function({ res, bucket }) { ## inflight.$Closure2.js ```js -module.exports = function({ __parent_this_2 }) { +module.exports = function({ $__parent_this_2_b }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await __parent_this_2.b.put("foo1.txt","bar")); + async handle() { + (await $__parent_this_2_b.put("foo1.txt","bar")); } } return $Closure2; @@ -46,17 +43,15 @@ module.exports = function({ __parent_this_2 }) { ## inflight.$Closure3.js ```js -module.exports = function({ __parent_this_3 }) { +module.exports = function({ $__parent_this_3_b }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await __parent_this_3.b.put("foo2.txt","bar")); + async handle() { + (await $__parent_this_3_b.put("foo2.txt","bar")); } } return $Closure3; @@ -66,17 +61,15 @@ module.exports = function({ __parent_this_3 }) { ## inflight.$Closure4.js ```js -module.exports = function({ __parent_this_4 }) { +module.exports = function({ $__parent_this_4_q }) { class $Closure4 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await __parent_this_4.q.push("foo")); + async handle() { + (await $__parent_this_4_q.push("foo")); } } return $Closure4; @@ -86,18 +79,16 @@ module.exports = function({ __parent_this_4 }) { ## inflight.$Closure5.js ```js -module.exports = function({ bigOlPublisher }) { +module.exports = function({ $bigOlPublisher }) { class $Closure5 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await bigOlPublisher.publish("foo")); - const count = (await bigOlPublisher.getObjectCount()); + async handle() { + (await $bigOlPublisher.publish("foo")); + const count = (await $bigOlPublisher.getObjectCount()); } } return $Closure5; @@ -107,30 +98,27 @@ module.exports = function({ bigOlPublisher }) { ## inflight.Bar.js ```js -module.exports = function({ Foo, MyEnum }) { +module.exports = function({ $Foo, $MyEnum }) { class Bar { - constructor({ b, e, foo, name }) { - this.b = b; - this.e = e; - this.foo = foo; - this.name = name; - } - async $inflight_init() { + constructor({ $this_b, $this_e, $this_foo }) { + this.$this_b = $this_b; + this.$this_e = $this_e; + this.$this_foo = $this_foo; } - static async barStatic() { + static async barStatic() { return "bar static"; } - async myMethod() { - (await this.foo.fooInc()); - const s = (await Foo.fooStatic()); - (await this.b.put("foo",String.raw({ raw: ["counter is: ", ""] }, (await this.foo.fooGet())))); - return (await this.b.get("foo")); + async myMethod() { + (await this.$this_foo.fooInc()); + const s = (await $Foo.fooStatic()); + (await this.$this_b.put("foo",String.raw({ raw: ["counter is: ", ""] }, (await this.$this_foo.fooGet())))); + return (await this.$this_b.get("foo")); } - async testTypeAccess() { + async testTypeAccess() { if (true) { {((cond) => {if (!cond) throw new Error("assertion failed: Bar.barStatic() == \"bar static\"")})(((await Bar.barStatic()) === "bar static"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: Foo.fooStatic() == \"foo static\"")})(((await Foo.fooStatic()) === "foo static"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.e == MyEnum.B")})((this.e === MyEnum.B))}; + {((cond) => {if (!cond) throw new Error("assertion failed: Foo.fooStatic() == \"foo static\"")})(((await $Foo.fooStatic()) === "foo static"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.e == MyEnum.B")})((this.$this_e === $MyEnum.B))}; } } } @@ -143,21 +131,19 @@ module.exports = function({ Foo, MyEnum }) { ```js module.exports = function({ }) { class BigPublisher { - constructor({ b, b2, q, t }) { - this.b = b; - this.b2 = b2; - this.q = q; - this.t = t; - } - async $inflight_init() { + constructor({ $this_b, $this_b2, $this_q, $this_t }) { + this.$this_b = $this_b; + this.$this_b2 = $this_b2; + this.$this_q = $this_q; + this.$this_t = $this_t; } - async publish(s) { - (await this.t.publish(s)); - (await this.q.push(s)); - (await this.b2.put("foo",s)); + async publish(s) { + (await this.$this_t.publish(s)); + (await this.$this_q.push(s)); + (await this.$this_b2.put("foo",s)); } - async getObjectCount() { - return (await this.b.list()).length; + async getObjectCount() { + return (await this.$this_b.list()).length; } } return BigPublisher; @@ -171,8 +157,6 @@ module.exports = function({ }) { class Dummy { constructor({ }) { } - async $inflight_init() { - } } return Dummy; } @@ -183,23 +167,23 @@ module.exports = function({ }) { ```js module.exports = function({ }) { class Foo { - constructor({ c }) { - this.c = c; - } - async $inflight_init() { - this.inflightField = 123; - (await this.c.inc(110)); - (await this.c.dec(10)); + constructor({ $this_c }) { + this.$this_c = $this_c; } - async fooInc() { - (await this.c.inc()); + async fooInc() { + (await this.$this_c.inc()); } - async fooGet() { - return (await this.c.peek()); + async fooGet() { + return (await this.$this_c.peek()); } - static async fooStatic() { + static async fooStatic() { return "foo static"; } + async $inflight_init() { + this.inflightField = 123; + (await this.$this_c.inc(110)); + (await this.$this_c.dec(10)); + } } return Foo; } @@ -212,8 +196,6 @@ module.exports = function({ }) { class ScopeAndIdTestClass { constructor({ }) { } - async $inflight_init() { - } } return ScopeAndIdTestClass; } @@ -324,7 +306,7 @@ module.exports = function({ }) { "uniqueId": "BigPublisher_b2_b2-on_create-OnMessage-a6a70fca_IamRolePolicy_46BA1064" } }, - "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[],\"Resource\":[\"${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.arn}\",\"${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.arn}/*\"],\"Effect\":\"Allow\"},{\"Action\":[],\"Resource\":[\"${aws_s3_bucket.BigPublisher_b2_702AC841.arn}\",\"${aws_s3_bucket.BigPublisher_b2_702AC841.arn}/*\"],\"Effect\":\"Allow\"},{\"Action\":[\"sqs:SendMessage\"],\"Resource\":[\"${aws_sqs_queue.BigPublisher_cloudQueue_2EE8871A.arn}\"],\"Effect\":\"Allow\"}]}", + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"sqs:SendMessage\"],\"Resource\":[\"${aws_sqs_queue.BigPublisher_cloudQueue_2EE8871A.arn}\"],\"Effect\":\"Allow\"}]}", "role": "${aws_iam_role.BigPublisher_b2_b2-on_create-OnMessage-a6a70fca_IamRole_ADCAC8AB.name}" }, "BigPublisher_cloudQueue-SetConsumer-c50bc9ef_IamRolePolicy_6AF2C97F": { @@ -334,7 +316,7 @@ module.exports = function({ }) { "uniqueId": "BigPublisher_cloudQueue-SetConsumer-c50bc9ef_IamRolePolicy_6AF2C97F" } }, - "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"sqs:ReceiveMessage\",\"sqs:ChangeMessageVisibility\",\"sqs:GetQueueUrl\",\"sqs:DeleteMessage\",\"sqs:GetQueueAttributes\"],\"Resource\":[\"${aws_sqs_queue.BigPublisher_cloudQueue_2EE8871A.arn}\"],\"Effect\":\"Allow\"},{\"Action\":[\"s3:PutObject*\",\"s3:Abort*\"],\"Resource\":[\"${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.arn}\",\"${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.arn}/*\"],\"Effect\":\"Allow\"},{\"Action\":[],\"Resource\":[\"${aws_s3_bucket.BigPublisher_b2_702AC841.arn}\",\"${aws_s3_bucket.BigPublisher_b2_702AC841.arn}/*\"],\"Effect\":\"Allow\"}]}", + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"sqs:ReceiveMessage\",\"sqs:ChangeMessageVisibility\",\"sqs:GetQueueUrl\",\"sqs:DeleteMessage\",\"sqs:GetQueueAttributes\"],\"Resource\":[\"${aws_sqs_queue.BigPublisher_cloudQueue_2EE8871A.arn}\"],\"Effect\":\"Allow\"},{\"Action\":[\"s3:PutObject*\",\"s3:Abort*\"],\"Resource\":[\"${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.arn}\",\"${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.arn}/*\"],\"Effect\":\"Allow\"}]}", "role": "${aws_iam_role.BigPublisher_cloudQueue-SetConsumer-c50bc9ef_IamRole_7FC6BA51.name}" }, "BigPublisher_cloudTopic-OnMessage-113c9059_IamRolePolicy_51FA866C": { @@ -344,7 +326,7 @@ module.exports = function({ }) { "uniqueId": "BigPublisher_cloudTopic-OnMessage-113c9059_IamRolePolicy_51FA866C" } }, - "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"s3:PutObject*\",\"s3:Abort*\"],\"Resource\":[\"${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.arn}\",\"${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.arn}/*\"],\"Effect\":\"Allow\"},{\"Action\":[],\"Resource\":[\"${aws_s3_bucket.BigPublisher_b2_702AC841.arn}\",\"${aws_s3_bucket.BigPublisher_b2_702AC841.arn}/*\"],\"Effect\":\"Allow\"}]}", + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"s3:PutObject*\",\"s3:Abort*\"],\"Resource\":[\"${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.arn}\",\"${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.arn}/*\"],\"Effect\":\"Allow\"}]}", "role": "${aws_iam_role.BigPublisher_cloudTopic-OnMessage-113c9059_IamRole_1067F50A.name}" }, "testdependencycycles_Handler_IamRolePolicy_A8D5A9DF": { @@ -443,10 +425,7 @@ module.exports = function({ }) { }, "environment": { "variables": { - "BUCKET_NAME_584271ad": "${aws_s3_bucket.BigPublisher_b2_702AC841.bucket}", - "BUCKET_NAME_7ef741f5": "${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.bucket}", "QUEUE_URL_b0ba884c": "${aws_sqs_queue.BigPublisher_cloudQueue_2EE8871A.url}", - "TOPIC_ARN_eb0072ec": "${aws_sns_topic.BigPublisher_cloudTopic_61DC7B63.arn}", "WING_FUNCTION_NAME": "b2-on_create-OnMessage-a6a70fca-c87e0778", "WING_TARGET": "tf-aws" } @@ -473,10 +452,7 @@ module.exports = function({ }) { }, "environment": { "variables": { - "BUCKET_NAME_584271ad": "${aws_s3_bucket.BigPublisher_b2_702AC841.bucket}", "BUCKET_NAME_7ef741f5": "${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.bucket}", - "QUEUE_URL_b0ba884c": "${aws_sqs_queue.BigPublisher_cloudQueue_2EE8871A.url}", - "TOPIC_ARN_eb0072ec": "${aws_sns_topic.BigPublisher_cloudTopic_61DC7B63.arn}", "WING_FUNCTION_NAME": "cloud-Queue-SetConsumer-c50bc9ef-c889d16f", "WING_TARGET": "tf-aws" } @@ -503,10 +479,7 @@ module.exports = function({ }) { }, "environment": { "variables": { - "BUCKET_NAME_584271ad": "${aws_s3_bucket.BigPublisher_b2_702AC841.bucket}", "BUCKET_NAME_7ef741f5": "${aws_s3_bucket.BigPublisher_cloudBucket_ABF95118.bucket}", - "QUEUE_URL_b0ba884c": "${aws_sqs_queue.BigPublisher_cloudQueue_2EE8871A.url}", - "TOPIC_ARN_eb0072ec": "${aws_sns_topic.BigPublisher_cloudTopic_61DC7B63.arn}", "WING_FUNCTION_NAME": "cloud-Topic-OnMessage-113c9059-c81d1d09", "WING_TARGET": "tf-aws" } @@ -907,22 +880,20 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.c = this.node.root.newAbstract("@winglang/sdk.cloud.Counter",this,"cloud.Counter"); - this._addInflightOps("fooInc", "fooGet", "fooStatic", "inflightField"); + this._addInflightOps("fooInc", "fooGet", "fooStatic", "$inflight_init", "inflightField"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } _toInflight() { - const c_client = this._lift(this.c); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const FooClient = ${Foo._toInflightType(this).text}; const client = new FooClient({ - c: ${c_client}, + $this_c: ${this._lift(this.c)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -932,6 +903,7 @@ class $Root extends $stdlib.std.Resource { _registerBind(host, ops) { if (ops.includes("$inflight_init")) { Foo._registerBindObject(this.c, host, ["dec", "inc"]); + Foo._registerBindObject(this, host, ["inflightField"]); } if (ops.includes("fooGet")) { Foo._registerBindObject(this.c, host, ["peek"]); @@ -941,11 +913,6 @@ class $Root extends $stdlib.std.Resource { } super._registerBind(host, ops); } - static _registerTypeBind(host, ops) { - if (ops.includes("fooStatic")) { - } - super._registerTypeBind(host, ops); - } } class Bar extends $stdlib.std.Resource { constructor(scope, id, name, b, e) { @@ -954,39 +921,24 @@ class $Root extends $stdlib.std.Resource { this.b = b; this.foo = new Foo(this,"Foo"); this.e = e; - this._addInflightOps("barStatic", "myMethod", "testTypeAccess"); + this._addInflightOps("barStatic", "myMethod", "testTypeAccess", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Bar.js"; - const FooClient = Foo._toInflightType(context); - const MyEnumClient = $stdlib.core.NodeJsCode.fromInline(` - Object.freeze((function (tmp) { - tmp[tmp["A"] = 0] = "A"; - tmp[tmp["B"] = 1] = "B"; - tmp[tmp["C"] = 2] = "C"; - return tmp; - })({})) - `); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Foo: ${FooClient.text}, - MyEnum: ${MyEnumClient.text}, + require("./inflight.Bar.js")({ + $Foo: ${context._lift(Foo)}, + $MyEnum: ${context._lift(MyEnum)}, }) `); } _toInflight() { - const b_client = this._lift(this.b); - const e_client = this._lift(this.e); - const foo_client = this._lift(this.foo); - const name_client = this._lift(this.name); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const BarClient = ${Bar._toInflightType(this).text}; const client = new BarClient({ - b: ${b_client}, - e: ${e_client}, - foo: ${foo_client}, - name: ${name_client}, + $this_b: ${this._lift(this.b)}, + $this_e: ${this._lift(this.e)}, + $this_foo: ${this._lift(this.foo)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -994,44 +946,30 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Bar._registerBindObject(this.b, host, []); - Bar._registerBindObject(this.e, host, []); - Bar._registerBindObject(this.foo, host, []); - Bar._registerBindObject(this.name, host, []); - } if (ops.includes("myMethod")) { Bar._registerBindObject(Foo, host, ["fooStatic"]); Bar._registerBindObject(this.b, host, ["get", "put"]); Bar._registerBindObject(this.foo, host, ["fooGet", "fooInc"]); } if (ops.includes("testTypeAccess")) { - Bar._registerBindObject(Bar, host, ["barStatic"]); Bar._registerBindObject(Foo, host, ["fooStatic"]); Bar._registerBindObject(this.e, host, []); } super._registerBind(host, ops); } - static _registerTypeBind(host, ops) { - if (ops.includes("barStatic")) { - } - super._registerTypeBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const res_client = context._lift(res); - const bucket_client = context._lift(bucket); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - res: ${res_client}, - bucket: ${bucket_client}, + require("./inflight.$Closure1.js")({ + $bucket: ${context._lift(bucket)}, + $res: ${context._lift(res)}, + $res_foo: ${context._lift(res.foo)}, }) `); } @@ -1047,10 +985,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(bucket, host, []); - $Closure1._registerBindObject(res, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(bucket, host, ["list"]); $Closure1._registerBindObject(res, host, ["myMethod", "testTypeAccess"]); @@ -1071,14 +1005,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const __parent_this_2_client = context._lift(__parent_this_2); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - __parent_this_2: ${__parent_this_2_client}, + require("./inflight.$Closure2.js")({ + $__parent_this_2_b: ${context._lift(__parent_this_2.b)}, }) `); } @@ -1094,9 +1026,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(__parent_this_2, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(__parent_this_2.b, host, ["put"]); } @@ -1109,14 +1038,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const __parent_this_3_client = context._lift(__parent_this_3); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - __parent_this_3: ${__parent_this_3_client}, + require("./inflight.$Closure3.js")({ + $__parent_this_3_b: ${context._lift(__parent_this_3.b)}, }) `); } @@ -1132,9 +1059,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(__parent_this_3, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(__parent_this_3.b, host, ["put"]); } @@ -1147,14 +1071,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; - const __parent_this_4_client = context._lift(__parent_this_4); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - __parent_this_4: ${__parent_this_4_client}, + require("./inflight.$Closure4.js")({ + $__parent_this_4_q: ${context._lift(__parent_this_4.q)}, }) `); } @@ -1170,9 +1092,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure4._registerBindObject(__parent_this_4, host, []); - } if (ops.includes("handle")) { $Closure4._registerBindObject(__parent_this_4.q, host, ["push"]); } @@ -1180,28 +1099,23 @@ class $Root extends $stdlib.std.Resource { } } (this.b2.onCreate(new $Closure4(this,"$Closure4"))); - this._addInflightOps("publish", "getObjectCount"); + this._addInflightOps("publish", "getObjectCount", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.BigPublisher.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.BigPublisher.js")({ }) `); } _toInflight() { - const b_client = this._lift(this.b); - const b2_client = this._lift(this.b2); - const q_client = this._lift(this.q); - const t_client = this._lift(this.t); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const BigPublisherClient = ${BigPublisher._toInflightType(this).text}; const client = new BigPublisherClient({ - b: ${b_client}, - b2: ${b2_client}, - q: ${q_client}, - t: ${t_client}, + $this_b: ${this._lift(this.b)}, + $this_b2: ${this._lift(this.b2)}, + $this_q: ${this._lift(this.q)}, + $this_t: ${this._lift(this.t)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -1209,12 +1123,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - BigPublisher._registerBindObject(this.b, host, []); - BigPublisher._registerBindObject(this.b2, host, []); - BigPublisher._registerBindObject(this.q, host, []); - BigPublisher._registerBindObject(this.t, host, []); - } if (ops.includes("getObjectCount")) { BigPublisher._registerBindObject(this.b, host, ["list"]); } @@ -1230,14 +1138,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure5.js"; - const bigOlPublisher_client = context._lift(bigOlPublisher); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - bigOlPublisher: ${bigOlPublisher_client}, + require("./inflight.$Closure5.js")({ + $bigOlPublisher: ${context._lift(bigOlPublisher)}, }) `); } @@ -1253,9 +1159,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure5._registerBindObject(bigOlPublisher, host, []); - } if (ops.includes("handle")) { $Closure5._registerBindObject(bigOlPublisher, host, ["getObjectCount", "publish"]); } @@ -1265,11 +1168,11 @@ class $Root extends $stdlib.std.Resource { class Dummy extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Dummy.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Dummy.js")({ }) `); } @@ -1284,11 +1187,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } class ScopeAndIdTestClass extends $stdlib.std.Resource { constructor(scope, id, ) { @@ -1302,11 +1200,11 @@ class $Root extends $stdlib.std.Resource { const expected_path = String.raw({ raw: ["/ScopeAndIdTestClass/tc", ""] }, i); {((cond) => {if (!cond) throw new Error("assertion failed: x.node.path.endsWith(expected_path)")})(x.node.path.endsWith(expected_path))}; } + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.ScopeAndIdTestClass.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.ScopeAndIdTestClass.js")({ }) `); } @@ -1321,11 +1219,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } const MyEnum = Object.freeze((function (tmp) { diff --git a/tools/hangar/__snapshots__/test_corpus/valid/resource.w_test_sim.md b/tools/hangar/__snapshots__/test_corpus/valid/resource.w_test_sim.md index 34b66842c8c..20d1ab53078 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/resource.w_test_sim.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/resource.w_test_sim.md @@ -2,7 +2,8 @@ ## stdout.log ```log -pass ─ resource.wsim » root/env0/test:test +pass ┌ resource.wsim » root/env0/test:test + └ counter is: 201 pass ─ resource.wsim » root/env1/test:dependency cycles diff --git a/tools/hangar/__snapshots__/test_corpus/valid/resource_as_inflight_literal.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/resource_as_inflight_literal.w_compile_tf-aws.md index 9276d0730a0..4351183355a 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/resource_as_inflight_literal.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/resource_as_inflight_literal.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ fn }) { +module.exports = function({ $fn }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: fn.invoke(\"test\") == \"hello world!\"")})(((await fn.invoke("test")) === "hello world!"))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: fn.invoke(\"test\") == \"hello world!\"")})(((await $fn.invoke("test")) === "hello world!"))}; } } return $Closure1; @@ -29,9 +27,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(message) { + async handle(message) { return "hello world!"; } } @@ -242,12 +238,11 @@ class $Root extends $stdlib.std.Resource { class Foo extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } @@ -262,26 +257,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const fn_client = context._lift(fn); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - fn: ${fn_client}, + require("./inflight.$Closure1.js")({ + $fn: ${context._lift(fn)}, }) `); } @@ -297,9 +283,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(fn, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(fn, host, ["invoke"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/resource_call_static.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/resource_call_static.w_compile_tf-aws.md index d4454108a17..f4795ca2521 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/resource_call_static.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/resource_call_static.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ Another }) { +module.exports = function({ $Another }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: Another.myStaticMethod() == 0")})(((await Another.myStaticMethod()) === 0))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: Another.myStaticMethod() == 0")})(((await $Another.myStaticMethod()) === 0))}; } } return $Closure1; @@ -22,14 +20,12 @@ module.exports = function({ Another }) { ## inflight.Another.js ```js -module.exports = function({ globalCounter }) { +module.exports = function({ $globalCounter }) { class Another { constructor({ }) { } - async $inflight_init() { - } - static async myStaticMethod() { - return (await globalCounter.peek()); + static async myStaticMethod() { + return (await $globalCounter.peek()); } } return Another; @@ -192,14 +188,12 @@ class $Root extends $stdlib.std.Resource { class Another extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("myStaticMethod"); + this._addInflightOps("myStaticMethod", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Another.js"; - const globalCounter_client = context._lift(globalCounter); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - globalCounter: ${globalCounter_client}, + require("./inflight.Another.js")({ + $globalCounter: ${context._lift(globalCounter)}, }) `); } @@ -214,12 +208,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Another._registerBindObject(globalCounter, host, []); - } - super._registerBind(host, ops); - } static _registerTypeBind(host, ops) { if (ops.includes("myStaticMethod")) { Another._registerBindObject(globalCounter, host, ["peek"]); @@ -231,14 +219,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const AnotherClient = Another._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Another: ${AnotherClient.text}, + require("./inflight.$Closure1.js")({ + $Another: ${context._lift(Another)}, }) `); } @@ -254,8 +240,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } if (ops.includes("handle")) { $Closure1._registerBindObject(Another, host, ["myStaticMethod"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/resource_captures.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/resource_captures.w_compile_tf-aws.md index cdff46d71f2..bd46403c672 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/resource_captures.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/resource_captures.w_compile_tf-aws.md @@ -2,27 +2,25 @@ ## inflight.$Closure1.js ```js -module.exports = function({ r }) { +module.exports = function({ $r }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await r.testNoCapture()); - (await r.testCaptureCollectionsOfData()); - (await r.testCapturePrimitives()); - (await r.testCaptureOptional()); - (await r.testCaptureResource()); - (await r.testNestedInflightField()); - (await r.testNestedResource()); - (await r.testExpressionRecursive()); - (await r.testExternal()); - (await r.testUserDefinedResource()); - (await r.testInflightField()); + async handle() { + (await $r.testNoCapture()); + (await $r.testCaptureCollectionsOfData()); + (await $r.testCapturePrimitives()); + (await $r.testCaptureOptional()); + (await $r.testCaptureResource()); + (await $r.testNestedInflightField()); + (await $r.testNestedResource()); + (await $r.testExpressionRecursive()); + (await $r.testExternal()); + (await $r.testUserDefinedResource()); + (await $r.testInflightField()); } } return $Closure1; @@ -34,16 +32,12 @@ module.exports = function({ r }) { ```js module.exports = function({ }) { class Another { - constructor({ first, myField }) { - this.first = first; - this.myField = myField; - } - async $inflight_init() { + constructor({ }) { } - async meaningOfLife() { + async meaningOfLife() { return 42; } - async anotherFunc() { + async anotherFunc() { return "42"; } } @@ -56,10 +50,7 @@ module.exports = function({ }) { ```js module.exports = function({ }) { class First { - constructor({ myResource }) { - this.myResource = myResource; - } - async $inflight_init() { + constructor({ }) { } } return First; @@ -71,75 +62,81 @@ module.exports = function({ }) { ```js module.exports = function({ }) { class MyResource { - constructor({ another, arrayOfStr, extBucket, extNum, mapOfNum, myBool, myNum, myOptStr, myQueue, myResource, myStr, setOfStr, unusedResource }) { - this.another = another; - this.arrayOfStr = arrayOfStr; - this.extBucket = extBucket; - this.extNum = extNum; - this.mapOfNum = mapOfNum; - this.myBool = myBool; - this.myNum = myNum; - this.myOptStr = myOptStr; - this.myQueue = myQueue; - this.myResource = myResource; - this.myStr = myStr; - this.setOfStr = setOfStr; - this.unusedResource = unusedResource; - } - async $inflight_init() { - this.inflightField = 123; + constructor({ $___this_setOfStr_has__s3____, $_this_arrayOfStr_at_0__, $_this_arrayOfStr_at_1__, $_this_mapOfNum___k1__, $_this_mapOfNum___k2__, $_this_myOptStr_______, $_this_setOfStr_has__s1___, $_this_setOfStr_has__s2___, $this_another, $this_another_first_myResource, $this_another_myField, $this_arrayOfStr_length, $this_extBucket, $this_extNum, $this_myBool, $this_myNum, $this_myQueue, $this_myResource, $this_myStr }) { + this.$___this_setOfStr_has__s3____ = $___this_setOfStr_has__s3____; + this.$_this_arrayOfStr_at_0__ = $_this_arrayOfStr_at_0__; + this.$_this_arrayOfStr_at_1__ = $_this_arrayOfStr_at_1__; + this.$_this_mapOfNum___k1__ = $_this_mapOfNum___k1__; + this.$_this_mapOfNum___k2__ = $_this_mapOfNum___k2__; + this.$_this_myOptStr_______ = $_this_myOptStr_______; + this.$_this_setOfStr_has__s1___ = $_this_setOfStr_has__s1___; + this.$_this_setOfStr_has__s2___ = $_this_setOfStr_has__s2___; + this.$this_another = $this_another; + this.$this_another_first_myResource = $this_another_first_myResource; + this.$this_another_myField = $this_another_myField; + this.$this_arrayOfStr_length = $this_arrayOfStr_length; + this.$this_extBucket = $this_extBucket; + this.$this_extNum = $this_extNum; + this.$this_myBool = $this_myBool; + this.$this_myNum = $this_myNum; + this.$this_myQueue = $this_myQueue; + this.$this_myResource = $this_myResource; + this.$this_myStr = $this_myStr; } - async testNoCapture() { + async testNoCapture() { const arr = Object.freeze([1, 2, 3]); {((cond) => {if (!cond) throw new Error("assertion failed: arr.length == 3")})((arr.length === 3))}; {console.log(String.raw({ raw: ["array.len=", ""] }, arr.length))}; } - async testCaptureCollectionsOfData() { - {((cond) => {if (!cond) throw new Error("assertion failed: this.arrayOfStr.length == 2")})((this.arrayOfStr.length === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.arrayOfStr.at(0) == \"s1\"")})(((await this.arrayOfStr.at(0)) === "s1"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.arrayOfStr.at(1) == \"s2\"")})(((await this.arrayOfStr.at(1)) === "s2"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.mapOfNum.get(\"k1\") == 11")})(((this.mapOfNum)["k1"] === 11))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.mapOfNum.get(\"k2\") == 22")})(((this.mapOfNum)["k2"] === 22))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.setOfStr.has(\"s1\")")})((await this.setOfStr.has("s1")))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.setOfStr.has(\"s2\")")})((await this.setOfStr.has("s2")))}; - {((cond) => {if (!cond) throw new Error("assertion failed: !this.setOfStr.has(\"s3\")")})((!(await this.setOfStr.has("s3"))))}; + async testCaptureCollectionsOfData() { + {((cond) => {if (!cond) throw new Error("assertion failed: this.arrayOfStr.length == 2")})((this.$this_arrayOfStr_length === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.arrayOfStr.at(0) == \"s1\"")})((this.$_this_arrayOfStr_at_0__ === "s1"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.arrayOfStr.at(1) == \"s2\"")})((this.$_this_arrayOfStr_at_1__ === "s2"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.mapOfNum.get(\"k1\") == 11")})((this.$_this_mapOfNum___k1__ === 11))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.mapOfNum.get(\"k2\") == 22")})((this.$_this_mapOfNum___k2__ === 22))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.setOfStr.has(\"s1\")")})(this.$_this_setOfStr_has__s1___)}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.setOfStr.has(\"s2\")")})(this.$_this_setOfStr_has__s2___)}; + {((cond) => {if (!cond) throw new Error("assertion failed: !this.setOfStr.has(\"s3\")")})(this.$___this_setOfStr_has__s3____)}; } - async testCapturePrimitives() { - {((cond) => {if (!cond) throw new Error("assertion failed: this.myStr == \"myString\"")})((this.myStr === "myString"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.myNum == 42")})((this.myNum === 42))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.myBool == true")})((this.myBool === true))}; + async testCapturePrimitives() { + {((cond) => {if (!cond) throw new Error("assertion failed: this.myStr == \"myString\"")})((this.$this_myStr === "myString"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.myNum == 42")})((this.$this_myNum === 42))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.myBool == true")})((this.$this_myBool === true))}; } - async testCaptureOptional() { - {((cond) => {if (!cond) throw new Error("assertion failed: this.myOptStr ?? \"\" == \"myOptString\"")})(((this.myOptStr ?? "") === "myOptString"))}; + async testCaptureOptional() { + {((cond) => {if (!cond) throw new Error("assertion failed: this.myOptStr ?? \"\" == \"myOptString\"")})((this.$_this_myOptStr_______ === "myOptString"))}; } - async testCaptureResource() { - (await this.myResource.put("f1.txt","f1")); - {((cond) => {if (!cond) throw new Error("assertion failed: this.myResource.get(\"f1.txt\") == \"f1\"")})(((await this.myResource.get("f1.txt")) === "f1"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.myResource.list().length == 1")})(((await this.myResource.list()).length === 1))}; + async testCaptureResource() { + (await this.$this_myResource.put("f1.txt","f1")); + {((cond) => {if (!cond) throw new Error("assertion failed: this.myResource.get(\"f1.txt\") == \"f1\"")})(((await this.$this_myResource.get("f1.txt")) === "f1"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.myResource.list().length == 1")})(((await this.$this_myResource.list()).length === 1))}; } - async testNestedInflightField() { - {((cond) => {if (!cond) throw new Error("assertion failed: this.another.myField == \"hello!\"")})((this.another.myField === "hello!"))}; - {console.log(String.raw({ raw: ["field=", ""] }, this.another.myField))}; + async testNestedInflightField() { + {((cond) => {if (!cond) throw new Error("assertion failed: this.another.myField == \"hello!\"")})((this.$this_another_myField === "hello!"))}; + {console.log(String.raw({ raw: ["field=", ""] }, this.$this_another_myField))}; } - async testNestedResource() { - {((cond) => {if (!cond) throw new Error("assertion failed: this.another.first.myResource.list().length == 0")})(((await this.another.first.myResource.list()).length === 0))}; - (await this.another.first.myResource.put("hello",this.myStr)); - {console.log(String.raw({ raw: ["this.another.first.myResource:", ""] }, (await this.another.first.myResource.get("hello"))))}; + async testNestedResource() { + {((cond) => {if (!cond) throw new Error("assertion failed: this.another.first.myResource.list().length == 0")})(((await this.$this_another_first_myResource.list()).length === 0))}; + (await this.$this_another_first_myResource.put("hello",this.$this_myStr)); + {console.log(String.raw({ raw: ["this.another.first.myResource:", ""] }, (await this.$this_another_first_myResource.get("hello"))))}; } - async testExpressionRecursive() { - (await this.myQueue.push(this.myStr)); + async testExpressionRecursive() { + (await this.$this_myQueue.push(this.$this_myStr)); } - async testExternal() { - {((cond) => {if (!cond) throw new Error("assertion failed: this.extBucket.list().length == 0")})(((await this.extBucket.list()).length === 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.extNum == 12")})((this.extNum === 12))}; + async testExternal() { + {((cond) => {if (!cond) throw new Error("assertion failed: this.extBucket.list().length == 0")})(((await this.$this_extBucket.list()).length === 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.extNum == 12")})((this.$this_extNum === 12))}; } - async testUserDefinedResource() { - {((cond) => {if (!cond) throw new Error("assertion failed: this.another.meaningOfLife() == 42")})(((await this.another.meaningOfLife()) === 42))}; - {((cond) => {if (!cond) throw new Error("assertion failed: this.another.anotherFunc() == \"42\"")})(((await this.another.anotherFunc()) === "42"))}; + async testUserDefinedResource() { + {((cond) => {if (!cond) throw new Error("assertion failed: this.another.meaningOfLife() == 42")})(((await this.$this_another.meaningOfLife()) === 42))}; + {((cond) => {if (!cond) throw new Error("assertion failed: this.another.anotherFunc() == \"42\"")})(((await this.$this_another.anotherFunc()) === "42"))}; } - async testInflightField() { + async testInflightField() { {((cond) => {if (!cond) throw new Error("assertion failed: this.inflightField == 123")})((this.inflightField === 123))}; } + async $inflight_init() { + this.inflightField = 123; + } } return MyResource; } @@ -243,7 +240,6 @@ module.exports = function({ }) { "BUCKET_NAME_51ee81c0": "${aws_s3_bucket.MyResource_cloudBucket_B5E6C951.bucket}", "BUCKET_NAME_830bf023": "${aws_s3_bucket.MyResource_Another_First_cloudBucket_5C44A510.bucket}", "BUCKET_NAME_d755b447": "${aws_s3_bucket.cloudBucket.bucket}", - "DYNAMODB_TABLE_NAME_5afed199": "${aws_dynamodb_table.MyResource_cloudCounter_0782991D.name}", "QUEUE_URL_ea9f63d6": "${aws_sqs_queue.MyResource_cloudQueue_E7A2C0F4.url}", "WING_FUNCTION_NAME": "Handler-c8f4f2a1", "WING_TARGET": "tf-aws" @@ -438,74 +434,50 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.myResource = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.First.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.First.js")({ }) `); } _toInflight() { - const myResource_client = this._lift(this.myResource); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const FirstClient = ${First._toInflightType(this).text}; const client = new FirstClient({ - myResource: ${myResource_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - First._registerBindObject(this.myResource, host, []); - } - super._registerBind(host, ops); - } } class Another extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.myField = "hello!"; this.first = new First(this,"First"); - this._addInflightOps("meaningOfLife", "anotherFunc"); + this._addInflightOps("meaningOfLife", "anotherFunc", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Another.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Another.js")({ }) `); } _toInflight() { - const first_client = this._lift(this.first); - const myField_client = this._lift(this.myField); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const AnotherClient = ${Another._toInflightType(this).text}; const client = new AnotherClient({ - first: ${first_client}, - myField: ${myField_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Another._registerBindObject(this.first, host, []); - Another._registerBindObject(this.myField, host, []); - } - if (ops.includes("anotherFunc")) { - } - if (ops.includes("meaningOfLife")) { - } - super._registerBind(host, ops); - } } class MyResource extends $stdlib.std.Resource { constructor(scope, id, externalBucket, externalNum) { @@ -523,49 +495,41 @@ class $Root extends $stdlib.std.Resource { this.extBucket = externalBucket; this.extNum = externalNum; this.unusedResource = this.node.root.newAbstract("@winglang/sdk.cloud.Counter",this,"cloud.Counter"); - this._addInflightOps("testNoCapture", "testCaptureCollectionsOfData", "testCapturePrimitives", "testCaptureOptional", "testCaptureResource", "testNestedInflightField", "testNestedResource", "testExpressionRecursive", "testExternal", "testUserDefinedResource", "testInflightField", "inflightField"); + this._addInflightOps("testNoCapture", "testCaptureCollectionsOfData", "testCapturePrimitives", "testCaptureOptional", "testCaptureResource", "testNestedInflightField", "testNestedResource", "testExpressionRecursive", "testExternal", "testUserDefinedResource", "testInflightField", "$inflight_init", "inflightField"); } - helloPreflight() { + helloPreflight() { return this.another; } static _toInflightType(context) { - const self_client_path = "././inflight.MyResource.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.MyResource.js")({ }) `); } _toInflight() { - const another_client = this._lift(this.another); - const arrayOfStr_client = this._lift(this.arrayOfStr); - const extBucket_client = this._lift(this.extBucket); - const extNum_client = this._lift(this.extNum); - const mapOfNum_client = this._lift(this.mapOfNum); - const myBool_client = this._lift(this.myBool); - const myNum_client = this._lift(this.myNum); - const myOptStr_client = this._lift(this.myOptStr); - const myQueue_client = this._lift(this.myQueue); - const myResource_client = this._lift(this.myResource); - const myStr_client = this._lift(this.myStr); - const setOfStr_client = this._lift(this.setOfStr); - const unusedResource_client = this._lift(this.unusedResource); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const MyResourceClient = ${MyResource._toInflightType(this).text}; const client = new MyResourceClient({ - another: ${another_client}, - arrayOfStr: ${arrayOfStr_client}, - extBucket: ${extBucket_client}, - extNum: ${extNum_client}, - mapOfNum: ${mapOfNum_client}, - myBool: ${myBool_client}, - myNum: ${myNum_client}, - myOptStr: ${myOptStr_client}, - myQueue: ${myQueue_client}, - myResource: ${myResource_client}, - myStr: ${myStr_client}, - setOfStr: ${setOfStr_client}, - unusedResource: ${unusedResource_client}, + $___this_setOfStr_has__s3____: ${this._lift((!(this.setOfStr.has("s3"))))}, + $_this_arrayOfStr_at_0__: ${this._lift((this.arrayOfStr.at(0)))}, + $_this_arrayOfStr_at_1__: ${this._lift((this.arrayOfStr.at(1)))}, + $_this_mapOfNum___k1__: ${this._lift((this.mapOfNum)["k1"])}, + $_this_mapOfNum___k2__: ${this._lift((this.mapOfNum)["k2"])}, + $_this_myOptStr_______: ${this._lift((this.myOptStr ?? ""))}, + $_this_setOfStr_has__s1___: ${this._lift((this.setOfStr.has("s1")))}, + $_this_setOfStr_has__s2___: ${this._lift((this.setOfStr.has("s2")))}, + $this_another: ${this._lift(this.another)}, + $this_another_first_myResource: ${this._lift(this.another.first.myResource)}, + $this_another_myField: ${this._lift(this.another.myField)}, + $this_arrayOfStr_length: ${this._lift(this.arrayOfStr.length)}, + $this_extBucket: ${this._lift(this.extBucket)}, + $this_extNum: ${this._lift(this.extNum)}, + $this_myBool: ${this._lift(this.myBool)}, + $this_myNum: ${this._lift(this.myNum)}, + $this_myQueue: ${this._lift(this.myQueue)}, + $this_myResource: ${this._lift(this.myResource)}, + $this_myStr: ${this._lift(this.myStr)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -574,27 +538,20 @@ class $Root extends $stdlib.std.Resource { } _registerBind(host, ops) { if (ops.includes("$inflight_init")) { - MyResource._registerBindObject(this.another, host, []); - MyResource._registerBindObject(this.arrayOfStr, host, []); - MyResource._registerBindObject(this.extBucket, host, []); - MyResource._registerBindObject(this.extNum, host, []); - MyResource._registerBindObject(this.mapOfNum, host, []); - MyResource._registerBindObject(this.myBool, host, []); - MyResource._registerBindObject(this.myNum, host, []); - MyResource._registerBindObject(this.myOptStr, host, []); - MyResource._registerBindObject(this.myQueue, host, []); - MyResource._registerBindObject(this.myResource, host, []); - MyResource._registerBindObject(this.myStr, host, []); - MyResource._registerBindObject(this.setOfStr, host, []); - MyResource._registerBindObject(this.unusedResource, host, []); + MyResource._registerBindObject(this, host, ["inflightField"]); } if (ops.includes("testCaptureCollectionsOfData")) { - MyResource._registerBindObject(this.arrayOfStr, host, ["at", "length"]); - MyResource._registerBindObject(this.mapOfNum, host, ["get"]); - MyResource._registerBindObject(this.setOfStr, host, ["has"]); + MyResource._registerBindObject((!(this.setOfStr.has("s3"))), host, []); + MyResource._registerBindObject((this.arrayOfStr.at(0)), host, []); + MyResource._registerBindObject((this.arrayOfStr.at(1)), host, []); + MyResource._registerBindObject((this.mapOfNum)["k1"], host, []); + MyResource._registerBindObject((this.mapOfNum)["k2"], host, []); + MyResource._registerBindObject((this.setOfStr.has("s1")), host, []); + MyResource._registerBindObject((this.setOfStr.has("s2")), host, []); + MyResource._registerBindObject(this.arrayOfStr.length, host, []); } if (ops.includes("testCaptureOptional")) { - MyResource._registerBindObject(this.myOptStr, host, []); + MyResource._registerBindObject((this.myOptStr ?? ""), host, []); } if (ops.includes("testCapturePrimitives")) { MyResource._registerBindObject(this.myBool, host, []); @@ -613,6 +570,7 @@ class $Root extends $stdlib.std.Resource { MyResource._registerBindObject(this.extNum, host, []); } if (ops.includes("testInflightField")) { + MyResource._registerBindObject(this, host, ["inflightField"]); } if (ops.includes("testNestedInflightField")) { MyResource._registerBindObject(this.another.myField, host, []); @@ -621,8 +579,6 @@ class $Root extends $stdlib.std.Resource { MyResource._registerBindObject(this.another.first.myResource, host, ["get", "list", "put"]); MyResource._registerBindObject(this.myStr, host, []); } - if (ops.includes("testNoCapture")) { - } if (ops.includes("testUserDefinedResource")) { MyResource._registerBindObject(this.another, host, ["anotherFunc", "meaningOfLife"]); } @@ -633,14 +589,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const r_client = context._lift(r); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - r: ${r_client}, + require("./inflight.$Closure1.js")({ + $r: ${context._lift(r)}, }) `); } @@ -656,9 +610,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(r, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(r, host, ["testCaptureCollectionsOfData", "testCaptureOptional", "testCapturePrimitives", "testCaptureResource", "testExpressionRecursive", "testExternal", "testInflightField", "testNestedInflightField", "testNestedResource", "testNoCapture", "testUserDefinedResource"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/resource_captures_globals.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/resource_captures_globals.w_compile_tf-aws.md index f7b5b9375ff..6e00b7ee6bc 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/resource_captures_globals.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/resource_captures_globals.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ res }) { +module.exports = function({ $res }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await res.myPut()); + async handle() { + (await $res.myPut()); } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ res }) { ## inflight.$Closure2.js ```js -module.exports = function({ Another }) { +module.exports = function({ $Another }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: Another.myStaticMethod() == 0")})(((await Another.myStaticMethod()) === 0))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: Another.myStaticMethod() == 0")})(((await $Another.myStaticMethod()) === 0))}; } } return $Closure2; @@ -42,21 +38,19 @@ module.exports = function({ Another }) { ## inflight.Another.js ```js -module.exports = function({ globalCounter }) { +module.exports = function({ $globalCounter }) { class Another { - constructor({ first, myField }) { - this.first = first; - this.myField = myField; + constructor({ }) { } - async $inflight_init() { - {((cond) => {if (!cond) throw new Error("assertion failed: globalCounter.peek() == 0")})(((await globalCounter.peek()) === 0))}; + async myMethod() { + (await $globalCounter.inc()); + return (await $globalCounter.peek()); } - async myMethod() { - (await globalCounter.inc()); - return (await globalCounter.peek()); + static async myStaticMethod() { + return (await $globalCounter.peek()); } - static async myStaticMethod() { - return (await globalCounter.peek()); + async $inflight_init() { + {((cond) => {if (!cond) throw new Error("assertion failed: globalCounter.peek() == 0")})(((await $globalCounter.peek()) === 0))}; } } return Another; @@ -68,10 +62,7 @@ module.exports = function({ globalCounter }) { ```js module.exports = function({ }) { class First { - constructor({ myResource }) { - this.myResource = myResource; - } - async $inflight_init() { + constructor({ }) { } } return First; @@ -81,27 +72,24 @@ module.exports = function({ }) { ## inflight.MyResource.js ```js -module.exports = function({ globalBucket, globalStr, globalBool, globalNum, globalArrayOfStr, globalMapOfNum, globalSetOfStr, globalAnother, Another }) { +module.exports = function({ $Another, $_globalArrayOfStr_at_0__, $_globalMapOfNum___a__, $_globalSetOfStr_has__a___, $globalAnother, $globalAnother_first_myResource, $globalAnother_myField, $globalBool, $globalBucket, $globalNum, $globalStr }) { class MyResource { - constructor({ localCounter, localTopic }) { - this.localCounter = localCounter; - this.localTopic = localTopic; - } - async $inflight_init() { + constructor({ $this_localTopic }) { + this.$this_localTopic = $this_localTopic; } - async myPut() { - (await this.localTopic.publish("hello")); - (await globalBucket.put("key","value")); - {((cond) => {if (!cond) throw new Error("assertion failed: globalStr == \"hello\"")})((globalStr === "hello"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: globalBool == true")})((globalBool === true))}; - {((cond) => {if (!cond) throw new Error("assertion failed: globalNum == 42")})((globalNum === 42))}; - {((cond) => {if (!cond) throw new Error("assertion failed: globalArrayOfStr.at(0) == \"hello\"")})(((await globalArrayOfStr.at(0)) === "hello"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: globalMapOfNum.get(\"a\") == -5")})(((globalMapOfNum)["a"] === (-5)))}; - {((cond) => {if (!cond) throw new Error("assertion failed: globalSetOfStr.has(\"a\")")})((await globalSetOfStr.has("a")))}; - {((cond) => {if (!cond) throw new Error("assertion failed: globalAnother.myField == \"hello!\"")})((globalAnother.myField === "hello!"))}; - (await globalAnother.first.myResource.put("key","value")); - {((cond) => {if (!cond) throw new Error("assertion failed: globalAnother.myMethod() > 0")})(((await globalAnother.myMethod()) > 0))}; - {((cond) => {if (!cond) throw new Error("assertion failed: Another.myStaticMethod() > 0")})(((await Another.myStaticMethod()) > 0))}; + async myPut() { + (await this.$this_localTopic.publish("hello")); + (await $globalBucket.put("key","value")); + {((cond) => {if (!cond) throw new Error("assertion failed: globalStr == \"hello\"")})(($globalStr === "hello"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: globalBool == true")})(($globalBool === true))}; + {((cond) => {if (!cond) throw new Error("assertion failed: globalNum == 42")})(($globalNum === 42))}; + {((cond) => {if (!cond) throw new Error("assertion failed: globalArrayOfStr.at(0) == \"hello\"")})(($_globalArrayOfStr_at_0__ === "hello"))}; + {((cond) => {if (!cond) throw new Error("assertion failed: globalMapOfNum.get(\"a\") == -5")})(($_globalMapOfNum___a__ === (-5)))}; + {((cond) => {if (!cond) throw new Error("assertion failed: globalSetOfStr.has(\"a\")")})($_globalSetOfStr_has__a___)}; + {((cond) => {if (!cond) throw new Error("assertion failed: globalAnother.myField == \"hello!\"")})(($globalAnother_myField === "hello!"))}; + (await $globalAnother_first_myResource.put("key","value")); + {((cond) => {if (!cond) throw new Error("assertion failed: globalAnother.myMethod() > 0")})(((await $globalAnother.myMethod()) > 0))}; + {((cond) => {if (!cond) throw new Error("assertion failed: Another.myStaticMethod() > 0")})(((await $Another.myStaticMethod()) > 0))}; } } return MyResource; @@ -111,18 +99,16 @@ module.exports = function({ globalBucket, globalStr, globalBool, globalNum, glob ## inflight.R.js ```js -module.exports = function({ globalCounter, $parentThis }) { +module.exports = function({ $_parentThis_localCounter, $globalCounter }) { class R { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await globalCounter.inc()); - (await $parentThis.localCounter.inc()); + async handle() { + (await $globalCounter.inc()); + (await $_parentThis_localCounter.inc()); } } return R; @@ -233,7 +219,7 @@ module.exports = function({ globalCounter, $parentThis }) { "uniqueId": "MyResource_cloudTopic-OnMessage-f10eb240_IamRolePolicy_3BEB9061" } }, - "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[],\"Resource\":[\"${aws_s3_bucket.cloudBucket.arn}\",\"${aws_s3_bucket.cloudBucket.arn}/*\"],\"Effect\":\"Allow\"},{\"Action\":[\"dynamodb:UpdateItem\"],\"Resource\":[\"${aws_dynamodb_table.cloudCounter.arn}\"],\"Effect\":\"Allow\"},{\"Action\":[\"dynamodb:GetItem\"],\"Resource\":[\"${aws_dynamodb_table.cloudCounter.arn}\"],\"Effect\":\"Allow\"},{\"Action\":[],\"Resource\":[\"${aws_s3_bucket.Another_First_cloudBucket_DB822B7C.arn}\",\"${aws_s3_bucket.Another_First_cloudBucket_DB822B7C.arn}/*\"],\"Effect\":\"Allow\"},{\"Action\":[\"dynamodb:UpdateItem\"],\"Resource\":[\"${aws_dynamodb_table.MyResource_cloudCounter_0782991D.arn}\"],\"Effect\":\"Allow\"}]}", + "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"dynamodb:UpdateItem\"],\"Resource\":[\"${aws_dynamodb_table.cloudCounter.arn}\"],\"Effect\":\"Allow\"},{\"Action\":[\"dynamodb:UpdateItem\"],\"Resource\":[\"${aws_dynamodb_table.MyResource_cloudCounter_0782991D.arn}\"],\"Effect\":\"Allow\"}]}", "role": "${aws_iam_role.MyResource_cloudTopic-OnMessage-f10eb240_IamRole_C06EFF5D.name}" }, "testaccesscloudresourcethroughstaticmethodsonly_Handler_IamRolePolicy_A6861688": { @@ -299,11 +285,8 @@ module.exports = function({ globalCounter, $parentThis }) { }, "environment": { "variables": { - "BUCKET_NAME_ae5b06c6": "${aws_s3_bucket.Another_First_cloudBucket_DB822B7C.bucket}", - "BUCKET_NAME_d755b447": "${aws_s3_bucket.cloudBucket.bucket}", "DYNAMODB_TABLE_NAME_49baa65c": "${aws_dynamodb_table.cloudCounter.name}", "DYNAMODB_TABLE_NAME_5afed199": "${aws_dynamodb_table.MyResource_cloudCounter_0782991D.name}", - "TOPIC_ARN_53de52bf": "${aws_sns_topic.MyResource_cloudTopic_1F3310C3.arn}", "WING_FUNCTION_NAME": "cloud-Topic-OnMessage-f10eb240-c8df2c86", "WING_TARGET": "tf-aws" } @@ -360,7 +343,6 @@ module.exports = function({ globalCounter, $parentThis }) { "BUCKET_NAME_ae5b06c6": "${aws_s3_bucket.Another_First_cloudBucket_DB822B7C.bucket}", "BUCKET_NAME_d755b447": "${aws_s3_bucket.cloudBucket.bucket}", "DYNAMODB_TABLE_NAME_49baa65c": "${aws_dynamodb_table.cloudCounter.name}", - "DYNAMODB_TABLE_NAME_5afed199": "${aws_dynamodb_table.MyResource_cloudCounter_0782991D.name}", "TOPIC_ARN_53de52bf": "${aws_sns_topic.MyResource_cloudTopic_1F3310C3.arn}", "WING_FUNCTION_NAME": "Handler-c8f4f2a1", "WING_TARGET": "tf-aws" @@ -565,59 +547,45 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.myResource = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"cloud.Bucket"); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.First.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.First.js")({ }) `); } _toInflight() { - const myResource_client = this._lift(this.myResource); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const FirstClient = ${First._toInflightType(this).text}; const client = new FirstClient({ - myResource: ${myResource_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - First._registerBindObject(this.myResource, host, []); - } - super._registerBind(host, ops); - } } class Another extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.myField = "hello!"; this.first = new First(this,"First"); - this._addInflightOps("myMethod", "myStaticMethod"); + this._addInflightOps("myMethod", "myStaticMethod", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Another.js"; - const globalCounter_client = context._lift(globalCounter); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - globalCounter: ${globalCounter_client}, + require("./inflight.Another.js")({ + $globalCounter: ${context._lift(globalCounter)}, }) `); } _toInflight() { - const first_client = this._lift(this.first); - const myField_client = this._lift(this.myField); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const AnotherClient = ${Another._toInflightType(this).text}; const client = new AnotherClient({ - first: ${first_client}, - myField: ${myField_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -627,8 +595,6 @@ class $Root extends $stdlib.std.Resource { _registerBind(host, ops) { if (ops.includes("$inflight_init")) { Another._registerBindObject(globalCounter, host, ["peek"]); - Another._registerBindObject(this.first, host, []); - Another._registerBindObject(this.myField, host, []); } if (ops.includes("myMethod")) { Another._registerBindObject(globalCounter, host, ["inc", "peek"]); @@ -651,16 +617,13 @@ class $Root extends $stdlib.std.Resource { class R extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.R.js"; - const globalCounter_client = context._lift(globalCounter); - const $parentThis_client = context._lift($parentThis); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - globalCounter: ${globalCounter_client}, - $parentThis: ${$parentThis_client}, + require("./inflight.R.js")({ + $_parentThis_localCounter: ${context._lift($parentThis.localCounter)}, + $globalCounter: ${context._lift(globalCounter)}, }) `); } @@ -676,10 +639,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - R._registerBindObject($parentThis, host, []); - R._registerBindObject(globalCounter, host, []); - } if (ops.includes("handle")) { R._registerBindObject($parentThis.localCounter, host, ["inc"]); R._registerBindObject(globalCounter, host, ["inc"]); @@ -688,42 +647,31 @@ class $Root extends $stdlib.std.Resource { } } (this.localTopic.onMessage(new R(this,"R"))); - this._addInflightOps("myPut"); + this._addInflightOps("myPut", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.MyResource.js"; - const globalBucket_client = context._lift(globalBucket); - const globalStr_client = context._lift(globalStr); - const globalBool_client = context._lift(globalBool); - const globalNum_client = context._lift(globalNum); - const globalArrayOfStr_client = context._lift(globalArrayOfStr); - const globalMapOfNum_client = context._lift(globalMapOfNum); - const globalSetOfStr_client = context._lift(globalSetOfStr); - const globalAnother_client = context._lift(globalAnother); - const AnotherClient = Another._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - globalBucket: ${globalBucket_client}, - globalStr: ${globalStr_client}, - globalBool: ${globalBool_client}, - globalNum: ${globalNum_client}, - globalArrayOfStr: ${globalArrayOfStr_client}, - globalMapOfNum: ${globalMapOfNum_client}, - globalSetOfStr: ${globalSetOfStr_client}, - globalAnother: ${globalAnother_client}, - Another: ${AnotherClient.text}, + require("./inflight.MyResource.js")({ + $Another: ${context._lift(Another)}, + $_globalArrayOfStr_at_0__: ${context._lift((globalArrayOfStr.at(0)))}, + $_globalMapOfNum___a__: ${context._lift((globalMapOfNum)["a"])}, + $_globalSetOfStr_has__a___: ${context._lift((globalSetOfStr.has("a")))}, + $globalAnother: ${context._lift(globalAnother)}, + $globalAnother_first_myResource: ${context._lift(globalAnother.first.myResource)}, + $globalAnother_myField: ${context._lift(globalAnother.myField)}, + $globalBool: ${context._lift(globalBool)}, + $globalBucket: ${context._lift(globalBucket)}, + $globalNum: ${context._lift(globalNum)}, + $globalStr: ${context._lift(globalStr)}, }) `); } _toInflight() { - const localCounter_client = this._lift(this.localCounter); - const localTopic_client = this._lift(this.localTopic); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const MyResourceClient = ${MyResource._toInflightType(this).text}; const client = new MyResourceClient({ - localCounter: ${localCounter_client}, - localTopic: ${localTopic_client}, + $this_localTopic: ${this._lift(this.localTopic)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -731,29 +679,17 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - MyResource._registerBindObject(globalAnother, host, []); - MyResource._registerBindObject(globalArrayOfStr, host, []); - MyResource._registerBindObject(globalBool, host, []); - MyResource._registerBindObject(globalBucket, host, []); - MyResource._registerBindObject(globalMapOfNum, host, []); - MyResource._registerBindObject(globalNum, host, []); - MyResource._registerBindObject(globalSetOfStr, host, []); - MyResource._registerBindObject(globalStr, host, []); - MyResource._registerBindObject(this.localCounter, host, []); - MyResource._registerBindObject(this.localTopic, host, []); - } if (ops.includes("myPut")) { MyResource._registerBindObject(Another, host, ["myStaticMethod"]); + MyResource._registerBindObject((globalArrayOfStr.at(0)), host, []); + MyResource._registerBindObject((globalMapOfNum)["a"], host, []); + MyResource._registerBindObject((globalSetOfStr.has("a")), host, []); MyResource._registerBindObject(globalAnother, host, ["myMethod"]); MyResource._registerBindObject(globalAnother.first.myResource, host, ["put"]); MyResource._registerBindObject(globalAnother.myField, host, []); - MyResource._registerBindObject(globalArrayOfStr, host, ["at"]); MyResource._registerBindObject(globalBool, host, []); MyResource._registerBindObject(globalBucket, host, ["put"]); - MyResource._registerBindObject(globalMapOfNum, host, ["get"]); MyResource._registerBindObject(globalNum, host, []); - MyResource._registerBindObject(globalSetOfStr, host, ["has"]); MyResource._registerBindObject(globalStr, host, []); MyResource._registerBindObject(this.localTopic, host, ["publish"]); } @@ -764,14 +700,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const res_client = context._lift(res); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - res: ${res_client}, + require("./inflight.$Closure1.js")({ + $res: ${context._lift(res)}, }) `); } @@ -787,9 +721,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(res, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(res, host, ["myPut"]); } @@ -800,14 +731,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const AnotherClient = Another._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - Another: ${AnotherClient.text}, + require("./inflight.$Closure2.js")({ + $Another: ${context._lift(Another)}, }) `); } @@ -823,8 +752,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } if (ops.includes("handle")) { $Closure2._registerBindObject(Another, host, ["myStaticMethod"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/shadowing.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/shadowing.w_compile_tf-aws.md index d8a647c139e..c63d7d88ddc 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/shadowing.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/shadowing.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ bar }) { +module.exports = function({ $bar }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const result = []; - (await result.push(bar)); + (await result.push($bar)); if (true) { const bar = "world"; (await result.push(bar)); @@ -30,17 +28,15 @@ module.exports = function({ bar }) { ## inflight.$Closure2.js ```js -module.exports = function({ fn }) { +module.exports = function({ $fn }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const result = (await fn()); + async handle() { + const result = (await $fn()); {((cond) => {if (!cond) throw new Error("assertion failed: result.length == 3")})((result.length === 3))}; {((cond) => {if (!cond) throw new Error("assertion failed: result.at(0) == \"hola!\"")})(((await result.at(0)) === "hola!"))}; {((cond) => {if (!cond) throw new Error("assertion failed: result.at(1) == \"world\"")})(((await result.at(1)) === "world"))}; @@ -188,14 +184,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const bar_client = context._lift(bar); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - bar: ${bar_client}, + require("./inflight.$Closure1.js")({ + $bar: ${context._lift(bar)}, }) `); } @@ -211,9 +205,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(bar, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(bar, host, []); } @@ -224,14 +215,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const fn_client = context._lift(fn); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - fn: ${fn_client}, + require("./inflight.$Closure2.js")({ + $fn: ${context._lift(fn)}, }) `); } @@ -247,9 +236,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(fn, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(fn, host, ["handle"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/statements_if.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/statements_if.w_compile_tf-aws.md index de65cfc1a0f..f4d97cc7ff8 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/statements_if.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/statements_if.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { if (true) { const x = 2; if ((true && ((x + 2) === 4))) { @@ -175,12 +173,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -195,13 +192,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } if (true) { const x = 2; diff --git a/tools/hangar/__snapshots__/test_corpus/valid/static_members.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/static_members.w_compile_tf-aws.md index 0943fe1ea0b..89b23e5ce31 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/static_members.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/static_members.w_compile_tf-aws.md @@ -9,10 +9,15 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - const InflightClass = require("./inflight.InflightClass.js")({}); + async handle() { + class InflightClass { + async inflightMethod() { + return "Inflight method"; + } + static async staticInflightMethod() { + return "Static inflight method"; + } + } const inflightClass = new InflightClass(); {((cond) => {if (!cond) throw new Error("assertion failed: inflightClass.inflightMethod() == \"Inflight method\"")})(((await inflightClass.inflightMethod()) === "Inflight method"))}; {((cond) => {if (!cond) throw new Error("assertion failed: InflightClass.staticInflightMethod() == \"Static inflight method\"")})(((await InflightClass.staticInflightMethod()) === "Static inflight method"))}; @@ -27,12 +32,9 @@ module.exports = function({ }) { ```js module.exports = function({ }) { class Foo { - constructor({ instanceField }) { - this.instanceField = instanceField; - } - async $inflight_init() { + constructor({ }) { } - static async get123() { + static async get123() { return 123; } } @@ -41,24 +43,6 @@ module.exports = function({ }) { ``` -## inflight.InflightClass.js -```js -module.exports = function({ }) { - class InflightClass { - constructor() { - } - async inflightMethod() { - return "Inflight method"; - } - static async staticInflightMethod() { - return "Static inflight method"; - } - } - return InflightClass; -} - -``` - ## main.tf.json ```json { @@ -195,53 +179,38 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.instanceField = 100; - this._addInflightOps("get123"); + this._addInflightOps("get123", "$inflight_init"); } - static m() { + static m() { return 99; } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } _toInflight() { - const instanceField_client = this._lift(this.instanceField); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const FooClient = ${Foo._toInflightType(this).text}; const client = new FooClient({ - instanceField: ${instanceField_client}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Foo._registerBindObject(this.instanceField, host, []); - } - super._registerBind(host, ops); - } - static _registerTypeBind(host, ops) { - if (ops.includes("get123")) { - } - super._registerTypeBind(host, ops); - } } class $Closure1 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -256,13 +225,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } const foo = new Foo(this,"Foo"); {((cond) => {if (!cond) throw new Error("assertion failed: foo.instanceField == 100")})((foo.instanceField === 100))}; diff --git a/tools/hangar/__snapshots__/test_corpus/valid/std_string.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/std_string.w_compile_tf-aws.md index cfeedfce1bf..12ce86b959b 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/std_string.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/std_string.w_compile_tf-aws.md @@ -2,19 +2,17 @@ ## inflight.$Closure1.js ```js -module.exports = function({ s1, s2 }) { +module.exports = function({ $__s1_split_______at_1__, $_s1_concat_s2__, $s1_indexOf__s__ }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {console.log(String.raw({ raw: ["index of \"s\" in s1 is ", ""] }, s1.indexOf("s")))}; - {console.log((await (await s1.split(" ")).at(1)))}; - {console.log((await s1.concat(s2)))}; + async handle() { + {console.log(String.raw({ raw: ["index of \"s\" in s1 is ", ""] }, $s1_indexOf__s__))}; + {console.log($__s1_split_______at_1__)}; + {console.log($_s1_concat_s2__)}; } } return $Closure1; @@ -157,16 +155,14 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const s1_client = context._lift(s1); - const s2_client = context._lift(s2); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - s1: ${s1_client}, - s2: ${s2_client}, + require("./inflight.$Closure1.js")({ + $__s1_split_______at_1__: ${context._lift(((s1.split(" ")).at(1)))}, + $_s1_concat_s2__: ${context._lift((s1.concat(s2)))}, + $s1_indexOf__s__: ${context._lift(s1.indexOf("s"))}, }) `); } @@ -182,13 +178,10 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(s1, host, []); - $Closure1._registerBindObject(s2, host, []); - } if (ops.includes("handle")) { - $Closure1._registerBindObject(s1, host, []); - $Closure1._registerBindObject(s2, host, []); + $Closure1._registerBindObject(((s1.split(" ")).at(1)), host, []); + $Closure1._registerBindObject((s1.concat(s2)), host, []); + $Closure1._registerBindObject(s1.indexOf("s"), host, []); } super._registerBind(host, ops); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/structs.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/structs.w_compile_tf-aws.md index 245cbdaa579..8eb3d64323d 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/structs.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/structs.w_compile_tf-aws.md @@ -4,13 +4,11 @@ ```js module.exports = function({ }) { class Foo { - constructor({ data }) { - this.data = data; + constructor({ $this_data_field0 }) { + this.$this_data_field0 = $this_data_field0; } - async $inflight_init() { - } - async getStuff() { - return this.data.field0; + async getStuff() { + return this.$this_data_field0; } } return Foo; @@ -64,22 +62,20 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, b) { super(scope, id); this.data = b; - this._addInflightOps("getStuff"); + this._addInflightOps("getStuff", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.Foo.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.Foo.js")({ }) `); } _toInflight() { - const data_client = this._lift(this.data); return $stdlib.core.NodeJsCode.fromInline(` (await (async () => { const FooClient = ${Foo._toInflightType(this).text}; const client = new FooClient({ - data: ${data_client}, + $this_data_field0: ${this._lift(this.data.field0)}, }); if (client.$inflight_init) { await client.$inflight_init(); } return client; @@ -87,9 +83,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - Foo._registerBindObject(this.data, host, []); - } if (ops.includes("getStuff")) { Foo._registerBindObject(this.data.field0, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/symbol_shadow.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/symbol_shadow.w_compile_tf-aws.md index f0477bbdfc2..c8b040ba2f2 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/symbol_shadow.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/symbol_shadow.w_compile_tf-aws.md @@ -2,17 +2,15 @@ ## inflight.$Closure1.js ```js -module.exports = function({ s }) { +module.exports = function({ $s }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: s == \"inner\"")})((s === "inner"))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: s == \"inner\"")})(($s === "inner"))}; } } return $Closure1; @@ -22,17 +20,15 @@ module.exports = function({ s }) { ## inflight.$Closure2.js ```js -module.exports = function({ s }) { +module.exports = function({ $s }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: s == \"inResource\"")})((s === "inResource"))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: s == \"inResource\"")})(($s === "inResource"))}; } } return $Closure2; @@ -42,17 +38,15 @@ module.exports = function({ s }) { ## inflight.$Closure3.js ```js -module.exports = function({ s }) { +module.exports = function({ $s }) { class $Closure3 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: s == \"top\"")})((s === "top"))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: s == \"top\"")})(($s === "top"))}; } } return $Closure3; @@ -69,9 +63,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { const s = "insideInflight"; {((cond) => {if (!cond) throw new Error("assertion failed: s == \"insideInflight\"")})((s === "insideInflight"))}; } @@ -87,8 +79,6 @@ module.exports = function({ }) { class A { constructor({ }) { } - async $inflight_init() { - } } return A; } @@ -435,14 +425,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const s_client = context._lift(s); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - s: ${s_client}, + require("./inflight.$Closure2.js")({ + $s: ${context._lift(s)}, }) `); } @@ -458,9 +446,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(s, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(s, host, []); } @@ -468,11 +453,11 @@ class $Root extends $stdlib.std.Resource { } } this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:inflight in resource should capture the right scoped var",new $Closure2(this,"$Closure2")); + this._addInflightOps("$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.A.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.A.js")({ }) `); } @@ -487,24 +472,17 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - super._registerBind(host, ops); - } } class $Closure3 extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; - const s_client = context._lift(s); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - s: ${s_client}, + require("./inflight.$Closure3.js")({ + $s: ${context._lift(s)}, }) `); } @@ -520,9 +498,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure3._registerBindObject(s, host, []); - } if (ops.includes("handle")) { $Closure3._registerBindObject(s, host, []); } @@ -533,12 +508,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure4.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure4.js")({ }) `); } @@ -553,13 +527,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } const s = "top"; if (true) { @@ -569,14 +536,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const s_client = context._lift(s); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - s: ${s_client}, + require("./inflight.$Closure1.js")({ + $s: ${context._lift(s)}, }) `); } @@ -592,9 +557,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(s, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(s, host, []); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/test_bucket.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/test_bucket.w_compile_tf-aws.md index c7000802875..6a1f14812f5 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/test_bucket.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/test_bucket.w_compile_tf-aws.md @@ -2,19 +2,17 @@ ## inflight.$Closure1.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - {((cond) => {if (!cond) throw new Error("assertion failed: b.list().length == 0")})(((await b.list()).length === 0))}; - (await b.put("hello.txt","world")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.list().length == 1")})(((await b.list()).length === 1))}; + async handle() { + {((cond) => {if (!cond) throw new Error("assertion failed: b.list().length == 0")})(((await $b.list()).length === 0))}; + (await $b.put("hello.txt","world")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.list().length == 1")})(((await $b.list()).length === 1))}; } } return $Closure1; @@ -24,18 +22,16 @@ module.exports = function({ b }) { ## inflight.$Closure2.js ```js -module.exports = function({ b }) { +module.exports = function({ $b }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { - (await b.put("hello.txt","world")); - {((cond) => {if (!cond) throw new Error("assertion failed: b.get(\"hello.txt\") == \"world\"")})(((await b.get("hello.txt")) === "world"))}; + async handle() { + (await $b.put("hello.txt","world")); + {((cond) => {if (!cond) throw new Error("assertion failed: b.get(\"hello.txt\") == \"world\"")})(((await $b.get("hello.txt")) === "world"))}; } } return $Closure2; @@ -290,14 +286,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure1.js")({ + $b: ${context._lift(b)}, }) `); } @@ -313,9 +307,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(b, host, ["list", "put"]); } @@ -326,14 +317,12 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const b_client = context._lift(b); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - b: ${b_client}, + require("./inflight.$Closure2.js")({ + $b: ${context._lift(b)}, }) `); } @@ -349,9 +338,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(b, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(b, host, ["get", "put"]); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/test_without_bring.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/test_without_bring.w_compile_tf-aws.md index afae1b2c9a2..82177b73b6d 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/test_without_bring.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/test_without_bring.w_compile_tf-aws.md @@ -9,9 +9,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle() { + async handle() { {((cond) => {if (!cond) throw new Error("assertion failed: true")})(true)}; } } @@ -155,12 +153,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -175,13 +172,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:hello test",new $Closure1(this,"$Closure1")); } diff --git a/tools/hangar/__snapshots__/test_corpus/valid/try_catch.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/try_catch.w_compile_tf-aws.md index 2e0c090cc12..6f606b5290f 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/try_catch.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/try_catch.w_compile_tf-aws.md @@ -86,31 +86,28 @@ class $Root extends $stdlib.std.Resource { x = "finally with no catch and no exception"; } {((cond) => {if (!cond) throw new Error("assertion failed: x == \"finally with no catch and no exception\"")})((x === "finally with no catch and no exception"))}; - {((cond) => {if (!cond) throw new Error("assertion failed: (():num => { try {} finally {return 1;}})() == 1")})(((( () => { + {((cond) => {if (!cond) throw new Error("assertion failed: (():num => { try {} finally {return 1;}})() == 1")})((((() => { try { } finally { return 1; } - } - )()) === 1))}; - {((cond) => {if (!cond) throw new Error("assertion failed: (():num => { try {throw(\"\");} catch {return 2;}})() == 2")})(((( () => { + })()) === 1))}; + {((cond) => {if (!cond) throw new Error("assertion failed: (():num => { try {throw(\"\");} catch {return 2;}})() == 2")})((((() => { try { {((msg) => {throw new Error(msg)})("")}; } catch { return 2; } - } - )()) === 2))}; - {((cond) => {if (!cond) throw new Error("assertion failed: (():num => { try {return 3;} finally {}})() == 3")})(((( () => { + })()) === 2))}; + {((cond) => {if (!cond) throw new Error("assertion failed: (():num => { try {return 3;} finally {}})() == 3")})((((() => { try { return 3; } finally { } - } - )()) === 3))}; + })()) === 3))}; } } class $App extends $AppBase { diff --git a/tools/hangar/__snapshots__/test_corpus/valid/website_with_api.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/website_with_api.w_compile_tf-aws.md index a27c28e737b..df4400a1224 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/website_with_api.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/website_with_api.w_compile_tf-aws.md @@ -2,18 +2,16 @@ ## inflight.$Closure1.js ```js -module.exports = function({ usersTable, std_Json }) { +module.exports = function({ $std_Json, $usersTable }) { class $Closure1 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { + async handle(req) { return { - "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([Object.freeze({"users":(await usersTable.list())})]), + "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([Object.freeze({"users":(await $usersTable.list())})]), "status": 200,} ; } @@ -25,16 +23,14 @@ module.exports = function({ usersTable, std_Json }) { ## inflight.$Closure2.js ```js -module.exports = function({ usersTable, std_Json }) { +module.exports = function({ $std_Json, $usersTable }) { class $Closure2 { constructor({ }) { const $obj = (...args) => this.handle(...args); Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { + async handle(req) { const body = (JSON.parse((req.body ?? ((args) => { return JSON.stringify(args[0], null, args[1]) })([Object.freeze({"name":"","age":"","id":""})])))); if (((((body)["name"] === "") || ((body)["age"] === "")) || ((body)["id"] === ""))) { return { @@ -42,7 +38,7 @@ module.exports = function({ usersTable, std_Json }) { "status": 400,} ; } - (await usersTable.insert(((args) => { return JSON.stringify(args[0], null, args[1]) })([(body)["id"]]),body)); + (await $usersTable.insert(((args) => { return JSON.stringify(args[0], null, args[1]) })([(body)["id"]]),body)); return { "body": ((args) => { return JSON.stringify(args[0], null, args[1]) })([Object.freeze({"user":(body)["id"]})]), "status": 201,} @@ -63,9 +59,7 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(req) { + async handle(req) { return { "headers": Object.freeze({"Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"OPTIONS,POST,GET"}), "status": 204,} @@ -614,16 +608,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; - const usersTable_client = context._lift(usersTable); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - usersTable: ${usersTable_client}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure1.js")({ + $std_Json: ${context._lift(std.Json)}, + $usersTable: ${context._lift(usersTable)}, }) `); } @@ -639,9 +630,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure1._registerBindObject(usersTable, host, []); - } if (ops.includes("handle")) { $Closure1._registerBindObject(usersTable, host, ["list"]); } @@ -652,16 +640,13 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure2.js"; - const usersTable_client = context._lift(usersTable); - const std_JsonClient = std.Json._toInflightType(context); return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ - usersTable: ${usersTable_client}, - std_Json: ${std_JsonClient.text}, + require("./inflight.$Closure2.js")({ + $std_Json: ${context._lift(std.Json)}, + $usersTable: ${context._lift(usersTable)}, }) `); } @@ -677,9 +662,6 @@ class $Root extends $stdlib.std.Resource { `); } _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - $Closure2._registerBindObject(usersTable, host, []); - } if (ops.includes("handle")) { $Closure2._registerBindObject(usersTable, host, ["insert"]); } @@ -690,12 +672,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure3.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure3.js")({ }) `); } @@ -710,13 +691,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } const api = this.node.root.newAbstract("@winglang/sdk.cloud.Api",this,"cloud.Api"); const website = this.node.root.newAbstract("@winglang/sdk.cloud.Website",this,"cloud.Website",{ path: "./website_with_api" }); diff --git a/tools/hangar/__snapshots__/test_corpus/valid/while_loop_await.w_compile_tf-aws.md b/tools/hangar/__snapshots__/test_corpus/valid/while_loop_await.w_compile_tf-aws.md index 943ab4e5a57..3a526606365 100644 --- a/tools/hangar/__snapshots__/test_corpus/valid/while_loop_await.w_compile_tf-aws.md +++ b/tools/hangar/__snapshots__/test_corpus/valid/while_loop_await.w_compile_tf-aws.md @@ -9,11 +9,9 @@ module.exports = function({ }) { Object.setPrototypeOf($obj, this); return $obj; } - async $inflight_init() { - } - async handle(body) { + async handle(body) { const i = 0; - const iterator = async (j) => { + const iterator = async (j) => { return (j + 1); } ; @@ -187,12 +185,11 @@ class $Root extends $stdlib.std.Resource { constructor(scope, id, ) { super(scope, id); this.display.hidden = true; - this._addInflightOps("handle"); + this._addInflightOps("handle", "$inflight_init"); } static _toInflightType(context) { - const self_client_path = "././inflight.$Closure1.js"; return $stdlib.core.NodeJsCode.fromInline(` - require("${self_client_path}")({ + require("./inflight.$Closure1.js")({ }) `); } @@ -207,13 +204,6 @@ class $Root extends $stdlib.std.Resource { })()) `); } - _registerBind(host, ops) { - if (ops.includes("$inflight_init")) { - } - if (ops.includes("handle")) { - } - super._registerBind(host, ops); - } } const queue = this.node.root.newAbstract("@winglang/sdk.cloud.Queue",this,"cloud.Queue"); const handler = new $Closure1(this,"$Closure1"); diff --git a/tools/hangar/__snapshots__/tree_json.ts.snap b/tools/hangar/__snapshots__/tree_json.ts.snap index e661901417b..5f5f924dc2c 100644 --- a/tools/hangar/__snapshots__/tree_json.ts.snap +++ b/tools/hangar/__snapshots__/tree_json.ts.snap @@ -97,7 +97,7 @@ exports[`tree.json for an app with many resources 1`] = ` { "direction": "inbound", "implicit": false, - "relationship": "dec", + "relationship": "peek", "resource": "root/Default/Default/test:test/Handler", }, { @@ -106,12 +106,6 @@ exports[`tree.json for an app with many resources 1`] = ` "relationship": "inc", "resource": "root/Default/Default/test:test/Handler", }, - { - "direction": "inbound", - "implicit": false, - "relationship": "peek", - "resource": "root/Default/Default/test:test/Handler", - }, ], }, "children": { @@ -1108,18 +1102,6 @@ exports[`tree.json for an app with many resources 1`] = ` "Handler": { "attributes": { "wing:resource:connections": [ - { - "direction": "outbound", - "implicit": false, - "relationship": "dec", - "resource": "root/Default/Default/Bar/Foo/cloud.Counter", - }, - { - "direction": "outbound", - "implicit": false, - "relationship": "inc", - "resource": "root/Default/Default/Bar/Foo/cloud.Counter", - }, { "direction": "outbound", "implicit": false, @@ -1144,6 +1126,12 @@ exports[`tree.json for an app with many resources 1`] = ` "relationship": "peek", "resource": "root/Default/Default/Bar/Foo/cloud.Counter", }, + { + "direction": "outbound", + "implicit": false, + "relationship": "inc", + "resource": "root/Default/Default/Bar/Foo/cloud.Counter", + }, { "direction": "outbound", "implicit": false,