file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
crates/swc_ecma_transforms/tests/__swc_snapshots__/tests/es2015_function_name.rs/let_complex.js
JavaScript
var TestClass = { name: "John Doe", testMethodFailure () { return new Promise(async function(resolve) { console.log(this); setTimeout(resolve, 1000); }); } };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/decorators.rs
Rust
#![cfg(all( feature = "swc_ecma_transforms_compat", feature = "swc_ecma_transforms_module", feature = "swc_ecma_transforms_optimization", feature = "swc_ecma_transforms_proposal", ))] use std::{fs, path::PathBuf}; use swc_common::Mark; use swc_ecma_ast::Pass; use swc_ecma_parser::{EsSyntax, Syntax, TsSyntax}; use swc_ecma_transforms_base::resolver; use swc_ecma_transforms_compat::{ class_fields_use_set::class_fields_use_set, es2015::{classes, function_name}, es2022::class_properties, }; use swc_ecma_transforms_module::common_js; use swc_ecma_transforms_proposal::{decorators, decorators::Config}; use swc_ecma_transforms_testing::{test, test_exec, test_fixture, Tester}; use swc_ecma_transforms_typescript::{strip, typescript}; fn ts() -> Syntax { Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }) } fn syntax(decorators_before_export: bool) -> Syntax { Syntax::Es(EsSyntax { decorators_before_export, decorators: true, ..Default::default() }) } fn tr(_: &Tester) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(Default::default()), class_fields_use_set(true), class_properties(Default::default(), unresolved_mark), ) } fn ts_transform(t: &Tester) -> impl Pass { simple_strip( t, Config { legacy: true, ..Default::default() }, ) } fn simple_strip(_: &Tester, config: Config) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( decorators(config), resolver(unresolved_mark, top_level_mark, false), typescript( typescript::Config { no_empty_export: true, ..Default::default() }, unresolved_mark, top_level_mark, ), class_fields_use_set(true), class_properties( class_properties::Config { set_public_fields: true, ..Default::default() }, unresolved_mark, ), ) } /// Folder for `transformation_*` tests fn transformation(t: &Tester) -> impl Pass { simple_strip(t, Default::default()) } // transformation_declaration test!( module, syntax(false), |t| transformation(t), transformation_declaration, r#" @dec() class A {} "# ); // transformation_initialize_after_super_multiple test!( module, syntax(false), |t| transformation(t), transformation_initialize_after_super_multiple, r#" @dec class B extends A { constructor() { const foo = () => { super(); }; if (a) { super(); } else { foo(); } while (0) { super(); } super(); } } "# ); // transformation_export_default_anonymous test!( syntax(false), |t| transformation(t), transformation_export_default_anonymous, r#" export default @dec() class {} "# ); // transformation_initialize_after_super_statement test!( module, syntax(false), |t| transformation(t), transformation_initialize_after_super_statement, r#" @dec class B extends A { constructor() { super(); } } "# ); // element_descriptors_created_own_method_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_created_own_method_exec, r#" function pushElement(e) { return function (c) { c.elements.push(e); return c }; } function method() {} @pushElement({ kind: "method", placement: "own", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, value: method, } }) class A {} expect(A).not.toHaveProperty("foo"); expect(A.prototype).not.toHaveProperty("foo"); expect(Object.getOwnPropertyDescriptor(new A(), "foo")).toEqual({ enumerable: true, configurable: true, writable: true, value: method, }); "# ); // finishers_return_class_exec test_exec!( syntax(false), |t| tr(t), finishers_return_class_exec, r#" class C {} function decorator(el) { return Object.assign(el, { finisher() { return C; }, }); } class A { @decorator foo() {} } expect(A).toBe(C); "# ); // misc_method_name_not_shadow test!( module, syntax(false), |t| tr(t), misc_method_name_not_shadow, r#" var method = 1; @decorator class Foo { method() { return method; } } "# ); // element_descriptors_original_class_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_original_class_exec, r#" var el = null; @(_ => el = _) class A {} expect(el).toEqual(Object.defineProperty({ kind: "class", elements: [] }, Symbol.toStringTag, { value: "Descriptor" })); @(_ => el = _) class B { foo = 2; static bar() {} get baz() {} set baz(x) {} } expect(el.elements).toHaveLength(3); "# ); // duplicated_keys_create_existing_element_with_extras_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_create_existing_element_with_extras_exec, r#" function decorate(el) { el.extras = [{ kind: "method", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, value: function() {}, } }]; return el; } expect(() => { class A { @decorate bar() {} foo() {} } }).toThrow(TypeError); "# ); // finishers_no_in_extras_exec test_exec!( syntax(false), |t| tr(t), finishers_no_in_extras_exec, r#" class C {} function decorator(el) { return Object.assign(el, { extras: [ Object.assign({}, el, { key: "bar", finisher() { return C; } }) ] }); } expect(() => { class A { @decorator foo() {} } }).toThrow(); "# ); // duplicated_keys_computed_keys_same_value test!( module, syntax(false), |t| tr(t), duplicated_keys_computed_keys_same_value, r#" @(_ => desc = _) class Foo { [getKeyI()]() { return 1; } [getKeyJ()]() { return 2; } } "# ); // transformation_only_decorated test!( syntax(false), |t| transformation(t), transformation_only_decorated, r#" class B { foo = 2; bar() {} } "# ); // ordering_finishers_exec test_exec!( syntax(false), |t| tr(t), ordering_finishers_exec, r#" var log = []; function push(x) { log.push(x); return x; } function logFinisher(x) { return function (el) { return Object.assign(el, { finisher() { push(x); } }); }; } @logFinisher(9) @logFinisher(8) class A { @logFinisher(1) @logFinisher(0) foo; @logFinisher(3) @logFinisher(2) static bar() {} @logFinisher(5) @logFinisher(4) static baz; @logFinisher(7) @logFinisher(6) asd() {} } var numsFrom0to9 = Array.from({ length: 10 }, (_, i) => i); expect(log).toEqual(numsFrom0to9); "# ); // transformation_initializer_after_super_bug_8808 test!( module, syntax(false), |t| transformation(t), transformation_initiailzer_after_super_bug_8808, r#" @decorator(parameter) class Sub extends Super { constructor() { super().method(); } } "# ); // duplicated_keys_original_method_overwritten_no_decorators_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_original_method_overwritten_no_decorators_exec, r#" var el; @(_ => el = _) class A { method() { return 1; } method() { return 2; } } expect(el.elements).toHaveLength(1); expect(A.prototype.method()).toBe(2); "# ); // transformation_arguments test!( module, syntax(false), |t| transformation(t), transformation_arguments, r#" @dec(a, b, ...c) class A { @dec(a, b, ...c) method() {} } "# ); // duplicated_keys_original_method_overwritten_both_decorated_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_original_method_overwritten_both_decorated_exec, r#" expect(() => { class A { @(el => el) method() { return 1; } @(el => el) method() { return 2; } } }).toThrow(ReferenceError); "# ); // ordering_field_initializers_after_methods_exec test_exec!( // Babel 7.3.0 fails ignore, syntax(false), |t| tr(t), ordering_field_initializers_after_methods_exec, r#" var counter = 0; @(x => x) class A { foo = (() => { counter++; expect(typeof this.method).toBe("function"); expect(this.foo).toBeUndefined(); expect(this.bar).toBeUndefined(); return "foo"; })(); method() {} bar = (() => { counter++; expect(typeof this.method).toBe("function"); expect(this.foo).toBe("foo"); expect(this.bar).toBeUndefined(); })(); } expect(counter).toBe(0); new A(); expect(counter).toBe(2); "# ); // misc_to_primitive_exec test_exec!( syntax(false), |t| tr(t), misc_to_primitive_exec, r#" let calls = 0; const baz = { [Symbol.toPrimitive]() { calls++; return "baz"; } } function dec() {} @dec class A { [baz]() {} } expect(calls).toBe(1); "# ); // ordering // transformation_initialize_after_super_expression test!( module, syntax(false), |t| transformation(t), transformation_initialize_after_super_expression, r#" @dec class B extends A { constructor() { (0, super()); } } "# ); // element_descriptors_not_reused_field_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_not_reused_field_exec, r#" var dec1, dec2; class A { @(_ => dec1 = _) @(_ => dec2 = _) field = {} } expect(dec1).toEqual(dec2); expect(dec1).not.toBe(dec2); expect(dec1.descriptor).toEqual(dec2.descriptor); expect(dec1.descriptor).not.toBe(dec2.descriptor); expect(dec1.initializer).toBe(dec2.initializer); "# ); // transformation_export_default_named test!( syntax(false), |t| transformation(t), transformation_export_default_named, r#" export default @dec() class Foo {} "# ); // element_descriptors_original_own_field_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_original_own_field_exec, r#" var el = null; var val = {}; class A { @(_ => el = _) foo = val; } expect(el).toEqual(Object.defineProperty({ kind: "field", key: "foo", placement: "own", descriptor: { enumerable: true, configurable: true, writable: true, }, initializer: expect.any(Function), }, Symbol.toStringTag, { value: "Descriptor" })); expect(el.initializer()).toBe(val); "# ); // transformation // ordering_decorators_exec test_exec!( syntax(false), |t| tr(t), ordering_decorators_exec, r#" var log = []; function push(x) { log.push(x); return x; } function logDecoratorRun(a, b) { push(a); return function (el) { push(b); return el; }; } @logDecoratorRun(0, 23) @logDecoratorRun(1, 22) class A { @logDecoratorRun(2, 15) @logDecoratorRun(3, 14) [push(4)] = "4"; @logDecoratorRun(5, 17) @logDecoratorRun(6, 16) static [push(7)]() {} @logDecoratorRun(8, 19) @logDecoratorRun(9, 18) static [push(10)] = "10"; @logDecoratorRun(11, 21) @logDecoratorRun(12, 20) [push(13)]() {} } var numsFrom0to23 = Array.from({ length: 24 }, (_, i) => i); expect(log).toEqual(numsFrom0to23); "# ); // transformation_async_generator_method // element_descriptors_default_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_default_exec, r#" function decorate(el) { el.descriptor.value = 2; } var Foo; expect(() => { Foo = @(() => void 0) class Foo { @decorate bar() {} } }).not.toThrow(); expect(Foo.prototype.bar).toBe(2); "# ); // element_descriptors_original_prototype_method_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_original_prototype_method_exec, r#" var el = null; class A { @(_ => el = _) foo() {} } expect(el).toEqual(Object.defineProperty({ kind: "method", key: "foo", placement: "prototype", descriptor: { enumerable: false, configurable: true, writable: true, value: A.prototype.foo, }, }, Symbol.toStringTag, { value: "Descriptor" })); "# ); // misc_method_name_exec test_exec!( syntax(false), |t| tr(t), misc_method_name_exec, r#" function decorator() {} @decorator class Foo { method() {} } expect(Foo.prototype.method.name).toBe("method"); "# ); // transformation_strict_directive test!( ignore, syntax(false), |t| transformation(t), transformation_strict_directive, r#" (() => { @dec class Foo { method() {} } }); (() => { @dec class Foo { method() {} } }); "# ); // element_descriptors_created_static_method_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_created_static_method_exec, r#" function pushElement(e) { return function (c) { c.elements.push(e); return c }; } function method() {} @pushElement({ kind: "method", placement: "static", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, value: method, } }) class A {} expect(A.prototype).not.toHaveProperty("foo"); expect(new A()).not.toHaveProperty("foo"); expect(Object.getOwnPropertyDescriptor(A, "foo")).toEqual({ enumerable: true, configurable: true, writable: true, value: method, }); "# ); // misc_method_name_not_shadow_exec test_exec!( syntax(false), |t| tr(t), misc_method_name_not_shadow_exec, r#" function decorator() {} var method = 1; @decorator class Foo { method() { return method; } } expect(new Foo().method()).toBe(1); expect(Foo.prototype.method.name).toBe("method"); "# ); // transformation_class_decorators_yield_await // duplicated_keys_original_method_overwritten_second_decorated_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_original_method_overwritten_second_decorated_exec, r#" expect(() => { class A { @(el => el) method() { return 1; } method() { return 2; } } }).toThrow(ReferenceError); "# ); // duplicated_keys_get_set_both_decorated_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_get_set_both_decorated_exec, r#" function dec(el) { return el } expect(() => { class A { @dec get foo() {} @dec set foo(x) {} } }).toThrow(ReferenceError); "# ); // duplicated_keys_original_method_overwritten_first_decorated_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_original_method_overwritten_first_decorated_exec, r#" expect(() => { class A { method() { return 1; } @(el => el) method() { return 2; } } }).toThrow(ReferenceError); "# ); // element_descriptors_created_prototype_field_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_created_prototype_field_exec, r#" function pushElement(e) { return function (c) { c.elements.push(e); return c }; } var value = {}; @pushElement({ kind: "field", placement: "prototype", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, }, initializer() { return value; } }) class A {} expect(A).not.toHaveProperty("foo"); expect(Object.getOwnPropertyDescriptor(A.prototype, "foo")).toEqual({ enumerable: true, configurable: true, writable: true, value: value, }); "# ); // transformation_extends test!( module, syntax(false), |t| transformation(t), transformation_extends, r#" @dec class A extends B {} "# ); // finishers // transformation_extends_await test!( module, syntax(false), |t| transformation(t), transformation_extends_await, r#" async function g() { @dec class A extends (await B) {} } "# ); // transformation_extends_yield test!( module, syntax(false), |t| transformation(t), transformation_extends_yield, r#" function* g() { @dec class A extends (yield B) {} } "# ); // element_descriptors_created_static_field_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_created_static_field_exec, r#" function pushElement(e) { return function (c) { c.elements.push(e); return c }; } var value = {}; @pushElement({ kind: "field", placement: "static", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, }, initializer() { return value; } }) class A {} expect(A.prototype).not.toHaveProperty("foo"); expect(new A()).not.toHaveProperty("foo"); expect(Object.getOwnPropertyDescriptor(A, "foo")).toEqual({ enumerable: true, configurable: true, writable: true, value: value, }); "# ); // element_descriptors_created_own_field_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_created_own_field_exec, r#" function pushElement(e) { return function (c) { c.elements.push(e); return c }; } var value = {}; @pushElement({ kind: "field", placement: "own", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, }, initializer() { return value; } }) class A {} expect(A).not.toHaveProperty("foo"); expect(A.prototype).not.toHaveProperty("foo"); expect(Object.getOwnPropertyDescriptor(new A(), "foo")).toEqual({ enumerable: true, configurable: true, writable: true, value: value, }); "# ); // element_descriptors_not_reused_method_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_not_reused_method_exec, r#" var dec1, dec2; class A { @(_ => dec1 = _) @(_ => dec2 = _) fn() {} } expect(dec1).toEqual(dec2); expect(dec1).not.toBe(dec2); expect(dec1.descriptor).toEqual(dec2.descriptor); expect(dec1.descriptor).not.toBe(dec2.descriptor); expect(dec1.descriptor.value).toBe(dec2.descriptor.value); "# ); // element_descriptors_not_reused_class_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_not_reused_class_exec, r#" var dec1, dec2; @(_ => dec1 = _) @(_ => dec2 = _) class A {} expect(dec1).toEqual(dec2); expect(dec1).not.toBe(dec2); "# ); // duplicated_keys_computed_keys_same_ast_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_computed_keys_same_ast_exec, r#" var i = 0; function getKey() { return (i++).toString(); } var desc; @(_ => desc = _) class Foo { [getKey()]() { return 1; } [getKey()]() { return 2; } } expect(desc.elements).toHaveLength(2); expect(desc.elements[0].key).toBe("0"); expect(desc.elements[0].descriptor.value()).toBe(1); expect(desc.elements[1].key).toBe("1"); expect(desc.elements[1].descriptor.value()).toBe(2); expect(i).toBe(2); "# ); // transformation_initialize_after_super_bug_8931 test!( module, syntax(false), |t| transformation(t), transformation_initialize_after_super_bug_8931, r#" @dec class B extends A { constructor() { super(); []; } } "# ); // duplicated_keys // ordering_static_field_initializers_after_methods_exec test_exec!( // Babel 7.3.0 fails ignore, syntax(false), |t| tr(t), ordering_static_field_initializers_after_methods_exec, r#" var counter = 0; @(x => x) class A { static foo = (() => { counter++; expect(typeof this.method).toBe("function"); expect(this.foo).toBeUndefined(); expect(this.bar).toBeUndefined(); return "foo"; })(); static method() {} static bar = (() => { counter++; expect(typeof this.method).toBe("function"); expect(this.foo).toBe("foo"); expect(this.bar).toBeUndefined(); })(); } expect(counter).toBe(2); "# ); // element_descriptors_original_static_method_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_original_static_method_exec, r#" var el = null; class A { @(_ => el = _) static foo() {} } expect(el).toEqual(Object.defineProperty({ kind: "method", key: "foo", placement: "static", descriptor: { enumerable: false, configurable: true, writable: true, value: A.foo, }, }, Symbol.toStringTag, { value: "Descriptor" })); "# ); // duplicated_keys_extras_duplicated_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_extras_duplicated_exec, r#" function decorate(el) { el.extras = [{ kind: "method", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, value: function() {}, } }, { kind: "method", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, value: function() {}, } }]; return el; } expect(() => { class A { @decorate method() {} } }).toThrow(TypeError); "# ); // duplicated_keys_extras_same_as_return_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_extras_same_as_return_exec, r#" function decorate(el) { return { kind: "method", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, value: function() {}, }, extras: [{ kind: "method", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, value: function() {}, } }] }; } expect(() => { class A { @decorate method() {} } }).toThrow(TypeError); "# ); // finishers_class_as_parameter_exec test_exec!( syntax(false), |t| tr(t), finishers_class_as_parameter_exec, r#" var C; function decorator(el) { return Object.assign(el, { finisher(Class) { C = Class; }, }); } class A { @decorator foo() {} } expect(C).toBe(A); "# ); // duplicated_keys_moved_and_created_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_moved_and_created_exec, r#" var value1, value2 = {}; function makeStatic(el) { el.placement = "static"; return el; } function defineBar(el) { el.extras = [{ key: "bar", kind: "method", placement: "prototype", descriptor: { value: value2, }, }]; return el; } function storeValue(el) { value1 = el.descriptor.value; return el; } class Foo { @defineBar @makeStatic @storeValue bar() {} } expect(Foo.bar).toBe(value1); expect(Foo.prototype.bar).toBe(value2); "# ); // transformation_expression test!( module, syntax(false), |t| transformation(t), transformation_expression, r#" (@dec() class {}); "# ); // duplicated_keys_original_method_prototype_and_static_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_original_method_prototype_and_static_exec, r#" var el; @(_ => el = _) class A { method() { return 1; } static method() { return 2; } } expect(el.elements).toHaveLength(2); expect(A.prototype.method()).toBe(1); expect(A.method()).toBe(2); "# ); // element_descriptors // duplicated_keys_computed_keys_same_ast test!( module, syntax(false), |t| tr(t), duplicated_keys_computed_keys_same_ast, r#" @(_ => desc = _) class Foo { [getKey()]() { return 1; } [getKey()]() { return 2; } } "# ); // element_descriptors_created_prototype_method_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_created_prototype_method_exec, r#" function pushElement(e) { return function (c) { c.elements.push(e); return c }; } function method() {} @pushElement({ kind: "method", placement: "prototype", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, value: method, } }) class A {} expect(A).not.toHaveProperty("foo"); expect(Object.getOwnPropertyDescriptor(A.prototype, "foo")).toEqual({ enumerable: true, configurable: true, writable: true, value: method, }); "# ); // duplicated_keys_create_existing_element_from_method_decorator_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_create_existing_element_from_method_decorator_exec, r#" function decorate() { return { kind: "method", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, value: function() {}, } }; } expect(() => { class A { @decorate bar() {} foo() {} } }).toThrow(TypeError); "# ); // element_descriptors_original_static_field_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_original_static_field_exec, r#" var el = null; var val = { foo: 2 }; class A { @(_ => el = _) static foo = val; } expect(el).toEqual(Object.defineProperty({ kind: "field", key: "foo", placement: "static", descriptor: { enumerable: true, configurable: true, writable: true, }, initializer: expect.any(Function), }, Symbol.toStringTag, { value: "Descriptor" })); expect(el.initializer()).toBe(val); "# ); // duplicated_keys_coalesce_get_set_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_coalesce_get_set_exec, r#" var el, el1; @(_ => el = _) class A { @(_ => el1 = _) get foo() { return 1; } set foo(x) { return 2; } } expect(el.elements).toHaveLength(1); expect(el1).toEqual(expect.objectContaining({ descriptor: expect.objectContaining({ get: expect.any(Function), set: expect.any(Function) }) })); var desc = Object.getOwnPropertyDescriptor(A.prototype, "foo"); expect(desc.get()).toBe(1); expect(desc.set()).toBe(2); "# ); // misc // transformation_extends_exec test_exec!( syntax(false), |t| tr(t), transformation_extends_exec, r#" class B {} @(_ => _) class A extends B {} expect(new A).toBeInstanceOf(A); expect(new A).toBeInstanceOf(B); "# ); // duplicated_keys_create_existing_element_from_class_decorator_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_create_existing_element_from_class_decorator_exec, r#" function pushElement(e) { return function (c) { c.elements.push(e); return c }; } expect(() => { @pushElement({ kind: "method", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, value: function() {}, } }) class A { foo() {} } }).toThrow(TypeError); "# ); // duplicated_keys_computed_keys_same_value_exec test_exec!( syntax(false), |t| tr(t), duplicated_keys_computed_keys_same_value_exec, r#" var i = 0; var j = 0; function getKeyI() { return (i++).toString(); } function getKeyJ() { return (j++).toString(); } var desc; @(_ => desc = _) class Foo { [getKeyI()]() { return 1; } [getKeyJ()]() { return 2; } } expect(desc.elements).toHaveLength(1); expect(desc.elements[0].key).toBe("0"); expect(desc.elements[0].descriptor.value()).toBe(2); expect(i).toBe(1); expect(j).toBe(1); "# ); // element_descriptors_original_own_field_without_initializer_exec test_exec!( syntax(false), |t| tr(t), element_descriptors_original_own_field_without_initiailzer_exec, r#" var el = null; class A { @(_ => el = _) foo; } expect(el).toEqual(Object.defineProperty({ kind: "field", key: "foo", placement: "own", descriptor: { enumerable: true, configurable: true, writable: true, }, initializer: undefined, }, Symbol.toStringTag, { value: "Descriptor" })); "# ); // legacy_class_constructors_return_new_constructor test_exec!( syntax(true), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_constructors_return_new_constructor_exec, r#" function dec(cls){ return class Child extends cls { child(){} }; } @dec class Parent { parent(){} } expect(typeof Parent.prototype.parent).toBe("function"); expect(typeof Parent.prototype.child).toBe("function"); "# ); // legacy_class_prototype_methods_numeric_props test_exec!( syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_prototype_methods_numeric_props_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(name).toBe(4); expect(typeof descriptor).toBe("object"); } class Example { @dec 4() {}; } "# ); // legacy_class_static_properties_mutate_descriptor test_exec!( // I tested using typescript playground and node js ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_static_properties_mutate_descriptor_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let initializer = descriptor.initializer; Object.assign(descriptor, { enumerable: name.indexOf("enum") !== -1, configurable: name.indexOf("conf") !== -1, writable: name.indexOf("write") !== -1, initializer: function(...args){ return '__' + initializer.apply(this, args) + '__'; }, }); } class Example { @dec static enumconfwrite = 1; @dec static enumconf = 2; @dec static enumwrite = 3; @dec static enum = 4; @dec static confwrite = 5; @dec static conf = 6; @dec static write = 7; @dec static _ = 8; } const inst = new Example(); expect(Example).toHaveProperty("decoratedProps"); expect(Example.decoratedProps).toEqual([ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const descs = Object.getOwnPropertyDescriptors(Example); expect(descs.enumconfwrite.enumerable).toBeTruthy(); expect(descs.enumconfwrite.writable).toBeTruthy(); expect(descs.enumconfwrite.configurable).toBeTruthy(); expect(Example.enumconfwrite).toBe("__1__"); expect(descs.enumconf.enumerable).toBeTruthy(); expect(descs.enumconf.writable).toBe(false); expect(descs.enumconf.configurable).toBeTruthy(); expect(Example.enumconf).toBe("__2__"); expect(descs.enumwrite.enumerable).toBeTruthy(); expect(descs.enumwrite.writable).toBeTruthy(); expect(descs.enumwrite.configurable).toBe(false); expect(Example.enumwrite).toBe("__3__"); expect(descs.enum.enumerable).toBeTruthy(); expect(descs.enum.writable).toBe(false); expect(descs.enum.configurable).toBe(false); expect(Example.enum).toBe("__4__"); expect(descs.confwrite.enumerable).toBe(false); expect(descs.confwrite.writable).toBeTruthy(); expect(descs.confwrite.configurable).toBeTruthy(); expect(Example.confwrite).toBe("__5__"); expect(descs.conf.enumerable).toBe(false); expect(descs.conf.writable).toBe(false); expect(descs.conf.configurable).toBeTruthy(); expect(Example.conf).toBe("__6__"); expect(descs.write.enumerable).toBe(false); expect(descs.write.writable).toBeTruthy(); expect(descs.write.configurable).toBe(false); expect(Example.write).toBe("__7__"); expect(descs._.enumerable).toBe(false); expect(descs._.writable).toBe(false); expect(descs._.configurable).toBe(false); expect(Example._).toBe("__8__"); "# ); // legacy_class_static_methods_string_props test_exec!( syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_static_methods_string_props_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(name).toBe("str"); expect(typeof descriptor).toBe("object"); } class Example { @dec static "str"() {}; } "# ); // legacy_class_prototype_properties_string_literal_properties test_exec!( ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_prototype_properties_string_literal_properties_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); return descriptor; } class Example { @dec "a-prop"; } let inst = new Example(); expect(Example.prototype).toHaveProperty("decoratedProps"); expect(inst.decoratedProps).toEqual([ "a-prop" ]); expect(inst).toHaveProperty("a-prop"); expect(inst["a-prop"]).toBeUndefined(); // const descs = Object.getOwnPropertyDescriptors(inst); // expect(descs["a-prop"].enumerable).toBeTruthy(); // expect(descs["a-prop"].writable).toBeTruthy(); // expect(descs["a-prop"].configurable).toBeTruthy(); "# ); // legacy_class_prototype_methods_mutate_descriptor test_exec!( // I tested on typescript playground ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_prototype_methods_mutate_descriptor_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let value = descriptor.value; Object.assign(descriptor, { enumerable: name.indexOf("enum") !== -1, configurable: name.indexOf("conf") !== -1, writable: name.indexOf("write") !== -1, value: function(...args) { return "__" + value.apply(this, args) + "__"; }, }); } class Example { @dec enumconfwrite(){ return 1; } @dec enumconf(){ return 2; } @dec enumwrite(){ return 3; } @dec enum(){ return 4; } @dec confwrite(){ return 5; } @dec conf(){ return 6; } @dec write(){ return 7; } @dec _(){ return 8; } } expect(Example.prototype).toHaveProperty('decoratedProps'); expect(Example.prototype.decoratedProps).toEqual([ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const inst = new Example(); const descs = Object.getOwnPropertyDescriptors(Example.prototype); expect(descs.enumconfwrite.enumerable).toBeTruthy(); expect(descs.enumconfwrite.writable).toBeTruthy(); expect(descs.enumconfwrite.configurable).toBeTruthy(); expect(inst.enumconfwrite()).toBe("__1__"); expect(descs.enumconf.enumerable).toBeTruthy(); expect(descs.enumconf.writable).toBe(false); expect(descs.enumconf.configurable).toBeTruthy(); expect(inst.enumconf()).toBe("__2__"); expect(descs.enumwrite.enumerable).toBeTruthy(); expect(descs.enumwrite.writable).toBeTruthy(); expect(descs.enumwrite.configurable).toBe(false); expect(inst.enumwrite()).toBe("__3__"); expect(descs.enum.enumerable).toBeTruthy(); expect(descs.enum.writable).toBe(false); expect(descs.enum.configurable).toBe(false); expect(inst.enum()).toBe("__4__"); expect(descs.confwrite.enumerable).toBe(false); expect(descs.confwrite.writable).toBeTruthy(); expect(descs.confwrite.configurable).toBeTruthy(); expect(inst.confwrite()).toBe("__5__"); expect(descs.conf.enumerable).toBe(false); expect(descs.conf.writable).toBe(false); expect(descs.conf.configurable).toBeTruthy(); expect(inst.conf()).toBe("__6__"); expect(descs.write.enumerable).toBe(false); expect(descs.write.writable).toBeTruthy(); expect(descs.write.configurable).toBe(false); expect(inst.write()).toBe("__7__"); expect(descs._.enumerable).toBe(false); expect(descs._.writable).toBe(false); expect(descs._.configurable).toBe(false); expect(inst._()).toBe("__8__"); "# ); // legacy_object_properties_numeric_props test_exec!( // Legacy decorator for object literals ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_object_properties_numeric_props_exec, r#" function dec(target, name, descriptor){ expect(target).toBeTruthy(); expect(name).toBe(4); expect(typeof descriptor).toBe("object"); } const inst = { @dec 4: 1 }; "# ); // legacy_class_prototype_properties_return_descriptor test_exec!( ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_prototype_properties_return_descriptor_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let initializer = descriptor.initializer; return { enumerable: name.indexOf('enum') !== -1, configurable: name.indexOf('conf') !== -1, writable: name.indexOf('write') !== -1, initializer: function(...args){ return '__' + initializer.apply(this, args) + '__'; }, }; } class Example { @dec enumconfwrite = 1; @dec enumconf = 2; @dec enumwrite = 3; @dec enum = 4; @dec confwrite = 5; @dec conf = 6; @dec write = 7; @dec _ = 8; } const inst = new Example(); expect(Example.prototype).toHaveProperty("decoratedProps"); expect(inst.decoratedProps).toEqual([ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const descs = Object.getOwnPropertyDescriptors(inst); expect(descs.enumconfwrite.enumerable).toBeTruthy(); expect(descs.enumconfwrite.writable).toBeTruthy(); expect(descs.enumconfwrite.configurable).toBeTruthy(); expect(inst.enumconfwrite).toBe("__1__"); expect(descs.enumconf.enumerable).toBeTruthy(); expect(descs.enumconf.writable).toBe(false); expect(descs.enumconf.configurable).toBeTruthy(); expect(inst.enumconf).toBe("__2__"); expect(descs.enumwrite.enumerable).toBeTruthy(); expect(descs.enumwrite.writable).toBeTruthy(); expect(descs.enumwrite.configurable).toBe(false); expect(inst.enumwrite).toBe("__3__"); expect(descs.enum.enumerable).toBeTruthy(); expect(descs.enum.writable).toBe(false); expect(descs.enum.configurable).toBe(false); expect(inst.enum).toBe("__4__"); expect(descs.confwrite.enumerable).toBe(false); expect(descs.confwrite.writable).toBeTruthy(); expect(descs.confwrite.configurable).toBeTruthy(); expect(inst.confwrite).toBe("__5__"); expect(descs.conf.enumerable).toBe(false); expect(descs.conf.writable).toBe(false); expect(descs.conf.configurable).toBeTruthy(); expect(inst.conf).toBe("__6__"); expect(descs.write.enumerable).toBe(false); expect(descs.write.writable).toBeTruthy(); expect(descs.write.configurable).toBe(false); expect(inst.write).toBe("__7__"); expect(descs._.enumerable).toBe(false); expect(descs._.writable).toBe(false); expect(descs._.configurable).toBe(false); expect(inst._).toBe("__8__"); "# ); // legacy_object_properties_string_props test_exec!( // Legacy decorator for object literals ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_object_properties_string_props_exec, r#" function dec(target, name, descriptor){ expect(target).toBeTruthy(); expect(name).toBe("str"); expect(typeof descriptor).toBe("object"); } const inst = { @dec "str": 1 }; "# ); // legacy_object_properties_return_descriptor test_exec!( // Legacy decorator for object literals ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_object_properties_return_descriptor_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let initializer = descriptor.initializer; return { enumerable: name.indexOf('enum') !== -1, configurable: name.indexOf('conf') !== -1, writable: name.indexOf('write') !== -1, initializer: function(...args){ return '__' + initializer.apply(this, args) + '__'; }, }; } const inst = { @dec enumconfwrite: 1, @dec enumconf: 2, @dec enumwrite: 3, @dec enum: 4, @dec confwrite: 5, @dec conf: 6, @dec write: 7, @dec _: 8, }; expect(inst).toHaveProperty("decoratedProps"); expect(inst.decoratedProps).toEqual([ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const descs = Object.getOwnPropertyDescriptors(inst); expect(descs.enumconfwrite.enumerable).toBeTruthy(); expect(descs.enumconfwrite.writable).toBeTruthy(); expect(descs.enumconfwrite.configurable).toBeTruthy(); expect(inst.enumconfwrite).toBe("__1__"); expect(descs.enumconf.enumerable).toBeTruthy(); expect(descs.enumconf.writable).toBe(false); expect(descs.enumconf.configurable).toBeTruthy(); expect(inst.enumconf).toBe("__2__"); expect(descs.enumwrite.enumerable).toBeTruthy(); expect(descs.enumwrite.writable).toBeTruthy(); expect(descs.enumwrite.configurable).toBe(false); expect(inst.enumwrite).toBe("__3__"); expect(descs.enum.enumerable).toBeTruthy(); expect(descs.enum.writable).toBe(false); expect(descs.enum.configurable).toBe(false); expect(inst.enum).toBe("__4__"); expect(descs.confwrite.enumerable).toBe(false); expect(descs.confwrite.writable).toBeTruthy(); expect(descs.confwrite.configurable).toBeTruthy(); expect(inst.confwrite).toBe("__5__"); expect(descs.conf.enumerable).toBe(false); expect(descs.conf.writable).toBe(false); expect(descs.conf.configurable).toBeTruthy(); expect(inst.conf).toBe("__6__"); expect(descs.write.enumerable).toBe(false); expect(descs.write.writable).toBeTruthy(); expect(descs.write.configurable).toBe(false); expect(inst.write).toBe("__7__"); expect(descs._.enumerable).toBe(false); expect(descs._.writable).toBe(false); expect(descs._.configurable).toBe(false); expect(inst._).toBe("__8__"); "# ); // legacy_class_prototype_methods_string_props test_exec!( syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_prototype_methods_string_props_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(name).toBe("str"); expect(typeof descriptor).toBe("object"); } class Example { @dec "str"() {}; } "# ); // legacy_class_prototype_methods_return_descriptor test_exec!( syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_prototype_methods_return_descriptor_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let value = descriptor.value; return { enumerable: name.indexOf('enum') !== -1, configurable: name.indexOf('conf') !== -1, writable: name.indexOf('write') !== -1, value: function(...args){ return '__' + value.apply(this, args) + '__'; }, }; } class Example { @dec enumconfwrite() { return 1; } @dec enumconf() { return 2; } @dec enumwrite() { return 3; } @dec enum() { return 4; } @dec confwrite() { return 5; } @dec conf() { return 6; } @dec write() { return 7; } @dec _() { return 8; } } expect(Example.prototype).toHaveProperty('decoratedProps'); expect(Example.prototype.decoratedProps).toEqual([ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const inst = new Example(); const descs = Object.getOwnPropertyDescriptors(Example.prototype); expect(descs.enumconfwrite.enumerable).toBeTruthy(); expect(descs.enumconfwrite.writable).toBeTruthy(); expect(descs.enumconfwrite.configurable).toBeTruthy(); expect(inst.enumconfwrite()).toBe("__1__"); expect(descs.enumconf.enumerable).toBeTruthy(); expect(descs.enumconf.writable).toBe(false); expect(descs.enumconf.configurable).toBeTruthy(); expect(inst.enumconf()).toBe("__2__"); expect(descs.enumwrite.enumerable).toBeTruthy(); expect(descs.enumwrite.writable).toBeTruthy(); expect(descs.enumwrite.configurable).toBe(false); expect(inst.enumwrite()).toBe("__3__"); expect(descs.enum.enumerable).toBeTruthy(); expect(descs.enum.writable).toBe(false); expect(descs.enum.configurable).toBe(false); expect(inst.enum()).toBe("__4__"); expect(descs.confwrite.enumerable).toBe(false); expect(descs.confwrite.writable).toBeTruthy(); expect(descs.confwrite.configurable).toBeTruthy(); expect(inst.confwrite()).toBe("__5__"); expect(descs.conf.enumerable).toBe(false); expect(descs.conf.writable).toBe(false); expect(descs.conf.configurable).toBeTruthy(); expect(inst.conf()).toBe("__6__"); expect(descs.write.enumerable).toBe(false); expect(descs.write.writable).toBeTruthy(); expect(descs.write.configurable).toBe(false); expect(inst.write()).toBe("__7__"); expect(descs._.enumerable).toBe(false); expect(descs._.writable).toBe(false); expect(descs._.configurable).toBe(false); expect(inst._()).toBe("__8__"); "# ); // legacy_object_ordering_reverse_order test_exec!( // Legacy decorator for object literals ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_object_ordering_reverse_order_exec, r#" const calls = []; function dec(id){ return function(){ calls.push(id); }; } const obj = { @dec(2) @dec(1) method1(){}, @dec(4) @dec(3) prop1: 1, @dec(6) @dec(5) method2(){}, @dec(8) @dec(7) prop2: 2, } expect(calls).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); "# ); // legacy_object_methods_numeric_props test_exec!( // Legacy decorator for object literals ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_object_methods_numeric_props_exec, r#" function dec(target, name, descriptor){ expect(target).toBeTruthy(); expect(name).toBe(4); expect(typeof descriptor).toBe("object"); } const inst = { @dec 4(){ } }; "# ); // legacy_class_static_properties_return_descriptor test_exec!( // I tested using typescript playground and node js ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_static_properties_return_descriptor_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let initializer = descriptor.initializer; return { enumerable: name.indexOf('enum') !== -1, configurable: name.indexOf('conf') !== -1, writable: name.indexOf('write') !== -1, initializer: function(...args){ return '__' + initializer.apply(this, args) + '__'; }, }; } class Example { @dec static enumconfwrite = 1; @dec static enumconf = 2; @dec static enumwrite = 3; @dec static enum = 4; @dec static confwrite = 5; @dec static conf = 6; @dec static write = 7; @dec static _ = 8; } const inst = new Example(); expect(Example).toHaveProperty("decoratedProps"); expect(Example.decoratedProps).toEqual([ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const descs = Object.getOwnPropertyDescriptors(Example); expect(descs.enumconfwrite.enumerable).toBeTruthy(); expect(descs.enumconfwrite.writable).toBeTruthy(); expect(descs.enumconfwrite.configurable).toBeTruthy(); expect(Example.enumconfwrite).toBe("__1__"); expect(descs.enumconf.enumerable).toBeTruthy(); expect(descs.enumconf.writable).toBe(false); expect(descs.enumconf.configurable).toBeTruthy(); expect(Example.enumconf).toBe("__2__"); expect(descs.enumwrite.enumerable).toBeTruthy(); expect(descs.enumwrite.writable).toBeTruthy(); expect(descs.enumwrite.configurable).toBe(false); expect(Example.enumwrite).toBe("__3__"); expect(descs.enum.enumerable).toBeTruthy(); expect(descs.enum.writable).toBe(false); expect(descs.enum.configurable).toBe(false); expect(Example.enum).toBe("__4__"); expect(descs.confwrite.enumerable).toBe(false); expect(descs.confwrite.writable).toBeTruthy(); expect(descs.confwrite.configurable).toBeTruthy(); expect(Example.confwrite).toBe("__5__"); expect(descs.conf.enumerable).toBe(false); expect(descs.conf.writable).toBe(false); expect(descs.conf.configurable); expect(Example.conf).toBe("__6__"); expect(descs.write.enumerable).toBe(false); expect(descs.write.writable).toBeTruthy(); expect(descs.write.configurable).toBe(false); expect(Example.write).toBe("__7__"); expect(descs._.enumerable).toBe(false); expect(descs._.writable).toBe(false); expect(descs._.configurable).toBe(false); expect(Example._).toBe("__8__"); "# ); // legacy_class_export_default test_exec!( // We wrap exec tests in a function like it('should work', function(){ // // .. code // }), but it prevents swc_ecma_parser from parsing the code // below correctly. ignore, syntax(true), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_export_default_exec, r#" const calls = []; function foo(target) { calls.push(target.name); } @foo export default class Foo { bar() { class Baz {} } } expect(calls).toEqual(["Foo"]); "# ); // legacy_class_ordering_reverse_order test_exec!( syntax(true), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_ordering_reverse_order_exec, r#" const calls = []; function dec(id){ return function(){ calls.push(id); }; } @dec(10) @dec(9) class Example2 { @dec(2) @dec(1) method1() {}; @dec(4) @dec(3) prop1 = 1; @dec(6) @dec(5) method2() {}; @dec(8) @dec(7) prop2 = 2; } expect(calls).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); "# ); // legacy_object_methods_mutate_descriptor test_exec!( // Legacy decorator for object literals ignore, syntax(true), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_object_methods_mutate_descriptor_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let value = descriptor.value; Object.assign(descriptor, { enumerable: name.indexOf("enum") !== -1, configurable: name.indexOf("conf") !== -1, writable: name.indexOf("write") !== -1, value: function(...args) { return "__" + value.apply(this, args) + "__"; }, }); } const inst = { @dec enumconfwrite(){ return 1; }, @dec enumconf(){ return 2; }, @dec enumwrite(){ return 3; }, @dec enum(){ return 4; }, @dec confwrite(){ return 5; }, @dec conf(){ return 6; }, @dec write(){ return 7; }, @dec _(){ return 8; }, } expect(inst).toHaveProperty('decoratedProps'); expect(inst.decoratedProps).toEqual([ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const descs = Object.getOwnPropertyDescriptors(inst); expect(descs.enumconfwrite.enumerable).toBeTruthy(); expect(descs.enumconfwrite.writable).toBeTruthy(); expect(descs.enumconfwrite.configurable).toBeTruthy(); expect(inst.enumconfwrite()).toBe("__1__"); expect(descs.enumconf.enumerable).toBeTruthy(); expect(descs.enumconf.writable).toBe(false); expect(descs.enumconf.configurable).toBeTruthy(); expect(inst.enumconf()).toBe("__2__"); expect(descs.enumwrite.enumerable).toBeTruthy(); expect(descs.enumwrite.writable).toBeTruthy(); expect(descs.enumwrite.configurable).toBe(false); expect(inst.enumwrite()).toBe("__3__"); expect(descs.enum.enumerable).toBeTruthy(); expect(descs.enum.writable).toBe(false); expect(descs.enum.configurable).toBe(false); expect(inst.enum()).toBe("__4__"); expect(descs.confwrite.enumerable).toBe(false); expect(descs.confwrite.writable).toBeTruthy(); expect(descs.confwrite.configurable); expect(inst.confwrite()).toBe("__5__"); expect(descs.conf.enumerable).toBe(false); expect(descs.conf.writable).toBe(false); expect(descs.conf.configurable).toBeTruthy(); expect(inst.conf()).toBe("__6__"); expect(descs.write.enumerable).toBe(false); expect(descs.write.writable).toBeTruthy(); expect(descs.write.configurable).toBe(false); expect(inst.write()).toBe("__7__"); expect(descs._.enumerable).toBe(false); expect(descs._.writable).toBe(false); expect(descs._.configurable).toBe(false); expect(inst._()).toBe("__8__"); "# ); // legacy_class_static_methods_return_descriptor test_exec!( syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_static_methods_return_descriptor_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let value = descriptor.value; return { enumerable: name.indexOf('enum') !== -1, configurable: name.indexOf('conf') !== -1, writable: name.indexOf('write') !== -1, value: function(...args){ return '__' + value.apply(this, args) + '__'; }, }; } class Example { @dec static enumconfwrite() { return 1; } @dec static enumconf() { return 2; } @dec static enumwrite() { return 3; } @dec static enum() { return 4; } @dec static confwrite() { return 5; } @dec static conf() { return 6; } @dec static write() { return 7; } @dec static _() { return 8; } } expect(Example).toHaveProperty("decoratedProps"); expect(Example.decoratedProps).toEqual([ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const descs = Object.getOwnPropertyDescriptors(Example); expect(descs.enumconfwrite.enumerable).toBeTruthy(); expect(descs.enumconfwrite.writable).toBeTruthy(); expect(descs.enumconfwrite.configurable).toBeTruthy(); expect(Example.enumconfwrite()).toBe("__1__"); expect(descs.enumconf.enumerable).toBeTruthy(); expect(descs.enumconf.writable).toBe(false); expect(descs.enumconf.configurable).toBeTruthy(); expect(Example.enumconf()).toBe("__2__"); expect(descs.enumwrite.enumerable).toBeTruthy(); expect(descs.enumwrite.writable).toBeTruthy(); expect(descs.enumwrite.configurable).toBe(false); expect(Example.enumwrite()).toBe("__3__"); expect(descs.enum.enumerable).toBeTruthy(); expect(descs.enum.writable).toBe(false); expect(descs.enum.configurable).toBe(false); expect(Example.enum()).toBe("__4__"); expect(descs.confwrite.enumerable).toBe(false); expect(descs.confwrite.writable).toBeTruthy(); expect(descs.confwrite.configurable); expect(Example.confwrite()).toBe("__5__"); expect(descs.conf.enumerable).toBe(false); expect(descs.conf.writable).toBe(false); expect(descs.conf.configurable).toBeTruthy(); expect(Example.conf()).toBe("__6__"); expect(descs.write.enumerable).toBe(false); expect(descs.write.writable).toBeTruthy(); expect(descs.write.configurable).toBe(false); expect(Example.write()).toBe("__7__"); expect(descs._.enumerable).toBe(false); expect(descs._.writable).toBe(false); expect(descs._.configurable).toBe(false); expect(Example._()).toBe("__8__"); "# ); // legacy_object_methods_return_descriptor test_exec!( // Legacy decorator for object literals ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_object_methods_return_descriptor_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let value = descriptor.value; return { enumerable: name.indexOf('enum') !== -1, configurable: name.indexOf('conf') !== -1, writable: name.indexOf('write') !== -1, value: function(...args){ return '__' + value.apply(this, args) + '__'; }, }; } const inst = { @dec enumconfwrite(){ return 1; }, @dec enumconf(){ return 2; }, @dec enumwrite(){ return 3; }, @dec enum(){ return 4; }, @dec confwrite(){ return 5; }, @dec conf(){ return 6; }, @dec write(){ return 7; }, @dec _(){ return 8; }, } expect(inst).toHaveProperty('decoratedProps'); expect(inst.decoratedProps).toEqual([ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const descs = Object.getOwnPropertyDescriptors(inst); expect(descs.enumconfwrite.enumerable).toBeTruthy(); expect(descs.enumconfwrite.writable).toBeTruthy(); expect(descs.enumconfwrite.configurable).toBeTruthy(); expect(inst.enumconfwrite()).toBe("__1__"); expect(descs.enumconf.enumerable).toBeTruthy(); expect(descs.enumconf.writable).toBe(false); expect(descs.enumconf.configurable).toBeTruthy(); expect(inst.enumconf()).toBe("__2__"); expect(descs.enumwrite.enumerable).toBeTruthy(); expect(descs.enumwrite.writable).toBeTruthy(); expect(descs.enumwrite.configurable).toBe(false); expect(inst.enumwrite()).toBe("__3__"); expect(descs.enum.enumerable).toBeTruthy(); expect(descs.enum.writable).toBe(false); expect(descs.enum.configurable).toBe(false); expect(inst.enum()).toBe("__4__"); expect(descs.confwrite.enumerable).toBe(false); expect(descs.confwrite.writable).toBeTruthy(); expect(descs.confwrite.configurable).toBeTruthy(); expect(inst.confwrite()).toBe("__5__"); expect(descs.conf.enumerable).toBe(false); expect(descs.conf.writable).toBe(false); expect(descs.conf.configurable).toBeTruthy(); expect(inst.conf()).toBe("__6__"); expect(descs.write.enumerable).toBe(false); expect(descs.write.writable).toBeTruthy(); expect(descs.write.configurable).toBe(false); expect(inst.write()).toBe("__7__"); expect(descs._.enumerable).toBe(false); expect(descs._.writable).toBe(false); expect(descs._.configurable).toBe(false); expect(inst._()).toBe("__8__"); "# ); // legacy_object_methods_string_props test_exec!( // Legacy decorator for object literals ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_object_methods_string_props_exec, r#" function dec(target, name, descriptor){ expect(target).toBeTruthy(); expect(name).toBe("str"); expect(typeof descriptor).toBe("object"); } const inst = { @dec "str"(){ } }; "# ); // legacy_class_prototype_properties_child_classes_properties test_exec!( ignore, syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_prototype_properties_child_classes_properties_exec, r#" function dec(target, name, descriptor){ expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let initializer = descriptor.initializer; descriptor.initializer = function(...args){ return "__" + initializer.apply(this, args) + "__"; }; } class Base { @dec prop2 = 4; } class Example extends Base { @dec prop = 3; } let inst = new Example(); expect(inst.prop).toBe("__3__"); expect(inst.prop2).toBe("__4__"); "# ); // legacy_class_static_methods_mutate_descriptor test_exec!( syntax(false), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), ) }, legacy_class_static_methods_mutate_descriptor_exec, r#" function dec(target, name, descriptor) { expect(target).toBeTruthy(); expect(typeof name).toBe("string"); expect(typeof descriptor).toBe("object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let value = descriptor.value; Object.assign(descriptor, { enumerable: name.indexOf("enum") !== -1, configurable: name.indexOf("conf") !== -1, writable: name.indexOf("write") !== -1, value: function(...args) { return "__" + value.apply(this, args) + "__"; }, }); } class Example { @dec static enumconfwrite(){ return 1; } @dec static enumconf(){ return 2; } @dec static enumwrite(){ return 3; } @dec static enum(){ return 4; } @dec static confwrite(){ return 5; } @dec static conf(){ return 6; } @dec static write(){ return 7; } @dec static _(){ return 8; } } expect(Example).toHaveProperty("decoratedProps"); expect(Example.decoratedProps).toEqual([ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const descs = Object.getOwnPropertyDescriptors(Example); expect(descs.enumconfwrite.enumerable).toBeTruthy(); expect(descs.enumconfwrite.writable).toBeTruthy(); expect(descs.enumconfwrite.configurable).toBeTruthy(); expect(Example.enumconfwrite()).toBe("__1__"); expect(descs.enumconf.enumerable).toBeTruthy(); expect(descs.enumconf.writable).toBe(false); expect(descs.enumconf.configurable).toBeTruthy(); expect(Example.enumconf()).toBe("__2__"); expect(descs.enumwrite.enumerable).toBeTruthy(); expect(descs.enumwrite.writable).toBeTruthy(); expect(descs.enumwrite.configurable).toBe(false); expect(Example.enumwrite()).toBe("__3__"); expect(descs.enum.enumerable).toBeTruthy(); expect(descs.enum.writable).toBe(false); expect(descs.enum.configurable).toBe(false); expect(Example.enum()).toBe("__4__"); expect(descs.confwrite.enumerable).toBe(false); expect(descs.confwrite.writable).toBeTruthy(); expect(descs.confwrite.configurable).toBeTruthy(); expect(Example.confwrite()).toBe("__5__"); expect(descs.conf.enumerable).toBe(false); expect(descs.conf.writable).toBe(false); expect(descs.conf.configurable).toBeTruthy(); expect(Example.conf()).toBe("__6__"); expect(descs.write.enumerable).toBe(false); expect(descs.write.writable).toBeTruthy(); expect(descs.write.configurable).toBe(false); expect(Example.write()).toBe("__7__"); expect(descs._.enumerable).toBe(false); expect(descs._.writable).toBe(false); expect(descs._.configurable).toBe(false); expect(Example._()).toBe("__8__"); "# ); // legacy_regression_8512 test_exec!( syntax(false), |_| decorators(Config { legacy: true, ..Default::default() }), legacy_regression_8512_exec, r#" function dec(Class, key, desc) { return desc; } class Foo { @dec get bar() {} } "# ); test_exec!( ts(), |t| ts_transform(t), issue_862_3, "var log: number[] = []; function push(x: number) { log.push(x); return x; } function saveOrder(x: number) { return function (el: any) { log.push(x); return el; }; } @saveOrder(1) class Product { @saveOrder(0) public id!: string; } var nums = Array.from({ length: 2 }, (_, i) => i); expect(log).toEqual(nums)" ); test_exec!( ts(), |t| ts_transform(t), issue_863_2, "const logs: number[] = []; function foo() { return function (target: any, member: any, ix: any) { logs.push(0); }; } function bar() { return function (target: any, member: any, ix: any) { logs.push(1); }; } class ProductController { findById( @foo() @bar() id: number ) { // ... } } expect(logs).toEqual([1, 0]) const c = new ProductController(); c.findById(100); " ); // decorators_legacy_interop_local_define_property test!( // See: https://github.com/swc-project/swc/issues/421 ignore, Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), classes(Default::default()), ) }, decorators_legacy_interop_local_define_property, r#" function dec() {} // Create a local function binding so babel has to change the name of the helper function _define_property() {} class A { @dec a; @dec b = 123; c = 456; } "# ); fn issue_395_syntax() -> ::swc_ecma_parser::Syntax { ::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsSyntax { decorators: true, ..Default::default() }) } test!( issue_395_syntax(), |_| ( decorators(Default::default()), common_js( Default::default(), Mark::fresh(Mark::root()), common_js::Config { strict: false, strict_mode: true, no_interop: true, ..Default::default() }, Default::default(), ), ), issue_395_1, " import Test from './moduleA.js' @Test('0.0.1') class Demo { constructor() { this.author = 'alan' } } " ); test!( issue_395_syntax(), |_| ( decorators(Default::default()), common_js::common_js( Default::default(), Mark::fresh(Mark::root()), common_js::Config { strict: false, strict_mode: true, no_interop: true, ..Default::default() }, Default::default(), ), ), issue_395_2, " const Test = (version) => { return (target) => { target.version = version } } export default Test " ); // function_name_function_assignment test!( ignore, Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), classes(Default::default()), function_name(), ) }, function_name_function_assignment, r#" var foo; foo = function() { }; var baz; baz = function() { baz(); }; baz = 12; bar = function() { bar(); }; "# ); // function_name_shorthand_property test!( // not important ignore, Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), classes(Default::default()), function_name(), ) }, function_name_shorthand_property, r#" var Utils = { get: function() {} }; var { get } = Utils; var bar = { get: function(arg) { get(arg, "baz"); } }; var f = function ({ foo = "bar" }) { var obj = { // same name as parameter foo: function () { foo; } }; }; "# ); // function_name_object test!( ignore, Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), function_name(), classes(Default::default()), decorators(decorators::Config { legacy: true, ..Default::default() }), ) }, function_name_object, r#" var obj = { f: function () { (function f() { console.log(f); })(); }, h: function () { console.log(h); }, m: function () { doSmth(); } }; "# ); // function_name_export test!( // not important ignore, Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), function_name(), classes(Default::default()), decorators(decorators::Config { legacy: true, ..Default::default() }), ) }, function_name_export, r#" export var foo = "yes", foob = "no"; export function whatever() {} export default function wowzers() {} var bar = { foo: function () { foo; }, whatever: function () { whatever; }, wowzers: function () { wowzers; } }; "# ); // function_name_global test!( // Cost of development is too high. ignore, Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), function_name(), classes(Default::default()), ) }, function_name_global, r#" var test = { setInterval: function(fn, ms) { setInterval(fn, ms); } }; "# ); // function_name_modules test!( Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), classes(Default::default()), function_name(), common_js( Default::default(), Mark::fresh(Mark::root()), Default::default(), Default::default(), ), ) }, function_name_modules, r#" import events from "events"; class Template { events() { return events; } } console.log(new Template().events()); "# ); // function_name_eval test!( Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), function_name(), classes(Default::default()), decorators(decorators::Config { legacy: true, ..Default::default() }), ) }, function_name_eval, r#" var a = { eval: function () { return eval; } }; "# ); test!( module, ts(), |_| decorators(Default::default()), issue_846_1, " class SomeClass { @dec someMethod() {} } class OtherClass extends SomeClass { @dec anotherMethod() { super.someMethod() } } " ); test_exec!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |t| simple_strip( t, Config { legacy: true, emit_metadata: true, use_define_for_class_fields: false, } ), issue_1362_1, " const { IsString } = require('class-validator'); class CreateUserDto { @IsString() id!: string; } " ); #[testing::fixture("tests/fixture/decorator/**/exec.ts")] fn fixture_exec(input: PathBuf) { let code = fs::read_to_string(input).expect("failed to read file"); swc_ecma_transforms_testing::exec_tr( "decorator", Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_t| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(Config { legacy: true, emit_metadata: true, use_define_for_class_fields: false, }), strip(unresolved_mark, top_level_mark), class_fields_use_set(true), ) }, &code, ); } #[testing::fixture("tests/fixture/legacy-only/**/input.ts")] fn legacy_only(input: PathBuf) { let output = input.with_file_name("output.ts"); test_fixture( ts(), &|_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(Config { legacy: true, emit_metadata: false, use_define_for_class_fields: false, }), ) }, &input, &output, Default::default(), ); } #[testing::fixture("tests/fixture/legacy-metadata/**/input.ts")] fn legacy_metadata(input: PathBuf) { let output = input.with_file_name("output.ts"); test_fixture( ts(), &|_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(Config { legacy: true, emit_metadata: true, use_define_for_class_fields: false, }), ) }, &input, &output, Default::default(), ); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/deno.rs
Rust
#![cfg(all( feature = "swc_ecma_transforms_proposal", feature = "swc_ecma_transforms_typescript", ))] use std::path::PathBuf; use swc_common::Mark; use swc_ecma_parser::Syntax; use swc_ecma_transforms::{fixer, helpers::inject_helpers, hygiene, resolver}; use swc_ecma_transforms_proposal::{ decorator_2022_03::decorator_2022_03, explicit_resource_management::explicit_resource_management, }; use swc_ecma_transforms_testing::test_fixture; use swc_ecma_transforms_typescript::typescript; #[testing::fixture("tests/fixture/deno/**/input.ts")] fn stack_overflow(input: PathBuf) { run_test(input); } fn run_test(input: PathBuf) { let output = input.with_file_name("output.js"); test_fixture( Syntax::Typescript(Default::default()), &|_tester| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorator_2022_03(), explicit_resource_management(), inject_helpers(top_level_mark), typescript( typescript::Config { verbatim_module_syntax: false, native_class_properties: false, import_not_used_as_values: typescript::ImportsNotUsedAsValues::Remove, no_empty_export: true, import_export_assign_config: typescript::TsImportExportAssignConfig::Preserve, ts_enum_is_mutable: true, }, unresolved_mark, top_level_mark, ), fixer(None), hygiene(), ) }, &input, &output, Default::default(), ) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/es2015_function_name.rs
Rust
#![cfg(all( feature = "swc_ecma_transforms_compat", feature = "swc_ecma_transforms_module", feature = "swc_ecma_transforms_optimization", feature = "swc_ecma_transforms_proposal", ))] use swc_common::Mark; use swc_ecma_ast::Pass; use swc_ecma_parser::Syntax; use swc_ecma_transforms_base::resolver; use swc_ecma_transforms_compat::{ es2015::{arrow, block_scoping, classes, function_name, shorthand}, es2022::class_properties, }; use swc_ecma_transforms_module::common_js::common_js; use swc_ecma_transforms_proposal::decorators; use swc_ecma_transforms_testing::test; fn syntax() -> Syntax { Default::default() } fn tr() -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), function_name(), block_scoping(unresolved_mark), ) } //macro_rules! identical { // ($name:ident, $src:literal) => { // test!(syntax(), |_| tr(), $name, $src, $src); // }; //} test!( syntax(), |_| tr(), basic, r#"var number = function (x) { return x; };"# ); test!( syntax(), |_| tr(), assign, r#"number = function (x) { return x; };"# ); test!( syntax(), |_| tr(), let_complex, r#" let TestClass = { name: "John Doe", testMethodFailure() { return new Promise(async function(resolve) { console.log(this); setTimeout(resolve, 1000); }); } }; "# ); test!( syntax(), |_| tr(), class_simple, r#" var Foo = function() { var Foo = function () { _class_call_check(this, Foo); }; _define_property(Foo, 'num', 0); return Foo; }(); expect(Foo.num).toBe(0); expect(Foo.num = 1).toBe(1); expect(Foo.name).toBe('Foo'); "# ); test!( syntax(), |_| tr(), issue_288_01, "var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; } || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); };" ); //identical!( // issue_288_02, // "function components_Link_extends() { // components_Link_extends = Object.assign || function (target) { for (var // i = 1; i < \ arguments.length; i++) { var source = arguments[i]; for (var // key in source) { if \ (Object.prototype.hasOwnProperty.call(source, key)) // { target[key] = source[key]; } } } \ return target; }; // return components_Link_extends.apply(this, arguments); }" //); // issues_5004 test!( syntax(), |_| function_name(), issues_5004, r#" export const x = ({x}) => x; export const y = function () {}; "# ); //// function_name_export_default_arrow_renaming_module_system //test!(syntax(),|_| tr("{ // "plugins": [ // function_name(), // shorthand(), // arrow(), // "transform-modules-systemjs" // ] //} //"), function_name_export_default_arrow_renaming_module_system, r#" //export default (a) => { // return { a() { return a } }; //} // //"# r#" //System.register([], function (_export, _context) { // "use strict"; // // return { // setters: [], // execute: function () { // _export("default", function (_a) { // return { // a: function a() { // return _a; // } // }; // }); // } // }; //}); // //"#); //// function_name_export_default_arrow_renaming_2 //test!(syntax(),|_| tr("{ // "presets": ["env"] //} //"), function_name_export_default_arrow_renaming_2, r#" //export default () => ({ // x: ({x}) => {} //}) // //"# r#" //"use strict"; // //Object.defineProperty(exports, "__esModule", { // value: true //}); //exports["default"] = void 0; // //var _default = function _default() { // return { // x: function x(_ref) { // var _x = _ref.x; // } // }; //}; // //exports["default"] = _default; // //"#); // function_name_with_arrow_functions_transform test!( ignore, syntax(), |_| (arrow(Mark::new()), function_name()), function_name_with_arrow_functions_transform, r#" const x = () => x; const y = x => x(); const z = { z: () => y(x) }.z; "# ); // function_name_modules_3 test!( syntax(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), function_name(), classes(Default::default()), decorators(decorators::Config { legacy: true, ..Default::default() }), common_js( Default::default(), unresolved_mark, Default::default(), Default::default(), ), ) }, function_name_modules_3, r#" import {getForm} from "./store" export default class Login extends React.Component { getForm() { return getForm().toJS() } } "# ); // function_name_basic test!( syntax(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), classes(Default::default()), function_name(), ) }, function_name_basic, r#" var g = function () { doSmth(); }; "# ); // function_name_export_default_arrow_renaming test!( ignore, syntax(), |_| { let unresolved_mark = Mark::new(); ( arrow(unresolved_mark), shorthand(), function_name(), common_js( Default::default(), unresolved_mark, Default::default(), Default::default(), ), ) }, function_name_export_default_arrow_renaming, r#" export default (a) => { return { a() { return a } }; } "# ); // issues_7199 test!( // Not important ignore, syntax(), |_| function_name(), issues_7199, r#" const x = { [null]: function () {}, [/regex/gi]: function () {}, [`y`]: function () {}, [`abc${y}def`]: function () {}, [0]: function () {}, [false]: function () {}, }; "# ); //// function_name_export_default_arrow_renaming_3 //test!(syntax(),|_| tr("{ // "presets": ["env", "react"] //} //"), function_name_export_default_arrow_renaming_3, r#" //export default ({ onClick }) => ( // <div onClick={() => onClick()} /> //) // // //"# r#" //"use strict"; // //Object.defineProperty(exports, "__esModule", { // value: true //}); //exports["default"] = void 0; // //var _default = function _default(_ref) { // var _onClick = _ref.onClick; // return React.createElement("div", { // onClick: function onClick() { // return _onClick(); // } // }); //}; // //exports["default"] = _default; // //"#); //// function_name_export_default_arrow_renaming_es3 //test!(syntax(),|_| tr("{ // "presets": ["env"], // "plugins": [ // "transform-member-expression-literals", // "transform-property-literals" // ] //} //"), function_name_export_default_arrow_renaming_es3, r#" //export default (a) => { // return { a() { return a } }; //} // //"# r#" //"use strict"; // //Object.defineProperty(exports, "__esModule", { // value: true //}); //exports["default"] = void 0; // //var _default = function _default(_a) { // return { // a: function a() { // return _a; // } // }; //}; // //exports["default"] = _default; // //"#); // function_name_self_reference test!( // not important ignore, syntax(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), function_name(), classes(Default::default()), ) }, function_name_self_reference, r#" var f = function () { console.log(f, g); }; f = null; "# ); // function_name_with_arrow_functions_transform_spec test!( ignore, syntax(), |_| (arrow(Mark::new()), function_name()), function_name_with_arrow_functions_transform_spec, r#" // These are actually handled by transform-arrow-functions const x = () => x; const y = x => x(); const z = { z: () => y(x) }.z; "# ); // function_name_method_definition test!( syntax(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), classes(Default::default()), function_name(), ) }, function_name_method_definition, r#" ({ x() {} }); "# ); // function_name_export_default_arrow_renaming_module_es6 test!( ignore, syntax(), |_| (arrow(Mark::new()), shorthand(), function_name()), function_name_export_default_arrow_renaming_module_es6, r#" export default (a) => { return { a() { return a } }; } "# ); // function_name_assignment test!( // not important ignore, syntax(), |_| tr(), function_name_assignment, r#" var i = function () { i = 5; }; var j = function () { ({ j } = 5); ({ y: j } = 5); ; }; "# ); // function_name_own_bindings test!( // not important ignore, syntax(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), classes(Default::default()), function_name(), ) }, function_name_own_bindings, r#" var f = function () { var f = 2; }; var g = function (g) { g; }; var obj = { f: function (f) { f; } }; "# ); // decorators_legacy_interop_strict test!( // See: https://github.com/swc-project/swc/issues/421 ignore, syntax(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), class_properties(Default::default(), unresolved_mark), classes(Default::default()), ) }, decorators_legacy_interop_strict, r#" function dec() {} class A { @dec a; @dec b = 123; c = 456; } "# ); // function_name_function_collision test!( ignore, syntax(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), classes(Default::default()), function_name(), ) }, function_name_function_collision, r#" function f() { f; } { let obj = { f: function () { f; } }; } (function b() { var obj = { b: function () { b; } }; function commit(b) { b(); } }); "# ); // function_name_collisions test!( syntax(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), classes(Default::default()), function_name(), ) }, function_name_collisions, r#" var obj = { search: function({search}) { console.log(search); } }; function search({search}) { console.log(search); } "# ); // function_name_modules_2 test!( ignore, Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), classes(Default::default()), function_name(), common_js( Default::default(), unresolved_mark, Default::default(), Default::default(), ), ) }, function_name_modules_2, r#" import last from "lodash/last" export default class Container { last(key) { if (!this.has(key)) { return; } return last(this.tokens.get(key)) } } "# ); // function_name_await test!( Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), decorators(decorators::Config { legacy: true, ..Default::default() }), classes(Default::default()), function_name(), ) }, function_name_await, r#" export {}; var obj = { await: function () {} }; "# );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/decorator/.issue-2117/1/exec.ts
TypeScript
class TestClass2 { @deco public testProperty?: string; } function deco(target: any, key: string) { console.log(target, key); } const instance = new TestClass2(); expect(instance.hasOwnProperty("testProperty")).toBe(true);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/decorator/issue-2127/1/exec.ts
TypeScript
const returnValue = "asdasd"; class TestClass { public testProperty: Date; } Object.defineProperty(TestClass.prototype, "testProperty", { get: function () { return returnValue; }, enumerable: true, configurable: true, }); const instance = new TestClass(); expect(instance.testProperty).toBe(returnValue);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/decorator/issue-2127/2/exec.ts
TypeScript
const returnValue = "asdasd"; class TestClass2 { @deco public declare testProperty: Date; } function deco(target: any, key: string) { console.log(target, key); Object.defineProperty(target.constructor.prototype, key, { get: function () { return returnValue; }, enumerable: true, configurable: true, }); } console.log(TestClass2.prototype.testProperty); const instance = new TestClass2(); expect(instance.testProperty).toBe(returnValue);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/decorator/issue-2127/3/exec.ts
TypeScript
const returnValue = "asdasd"; class TestClass2 { @deco public declare testProperty: Date; } function deco(target: any, key: string) { console.log(target, key); Object.defineProperty(target.constructor.prototype, key, { value: returnValue, enumerable: true, configurable: true, }); } console.log(TestClass2.prototype.testProperty); const instance = new TestClass2(); expect(instance.testProperty).toBe(returnValue);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/decorator/issue-3705/exec.ts
TypeScript
function field(host: any, field: any, descr?: any): any { return { ...descr, get: () => {}, set: () => {} }; } class TestMems { @field static some = 1; } expect(Object.keys(TestMems)).toEqual(["some"]); expect(TestMems.some).toBeUndefined();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/deno/stack-overflow/add-1/input.ts
TypeScript
console.log( 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +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 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/deno/stack-overflow/which/input.ts
TypeScript
export interface Environment { /** Gets an environment variable. */ env(key: string): string | undefined; /** Resolves the `Deno.FileInfo` for the specified * path following symlinks. */ stat(filePath: string): Promise<Pick<Deno.FileInfo, "isFile">>; /** Synchronously resolves the `Deno.FileInfo` for * the specified path following symlinks. */ statSync(filePath: string): Pick<Deno.FileInfo, "isFile">; /** Gets the current operating system. */ os: typeof Deno.build.os; } export class RealEnvironment implements Environment { env(key: string): string | undefined { return Deno.env.get(key); } stat(path: string): Promise<Deno.FileInfo> { return Deno.stat(path); } statSync(path: string): Deno.FileInfo { return Deno.statSync(path); } get os() { return Deno.build.os; } } /** Finds the path to the specified command asynchronously. */ export async function which( command: string, environment: Omit<Environment, "statSync"> = new RealEnvironment(), ) { const systemInfo = getSystemInfo(command, environment); if (systemInfo == null) { return undefined; } for (const pathItem of systemInfo.pathItems) { const filePath = pathItem + command; if (systemInfo.pathExts) { for (const pathExt of systemInfo.pathExts) { const filePath = pathItem + command + pathExt; if (await pathMatches(environment, filePath)) { return filePath; } } } else { if (await pathMatches(environment, filePath)) { return filePath; } } } return undefined; } async function pathMatches( environment: Omit<Environment, "statSync">, path: string, ): Promise<boolean> { try { const result = await environment.stat(path); return result.isFile; } catch (err) { if (err instanceof Deno.errors.PermissionDenied) { throw err; } return false; } } /** Finds the path to the specified command synchronously. */ export function whichSync( command: string, environment: Omit<Environment, "stat"> = new RealEnvironment(), ) { const systemInfo = getSystemInfo(command, environment); if (systemInfo == null) { return undefined; } for (const pathItem of systemInfo.pathItems) { const filePath = pathItem + command; if (pathMatchesSync(environment, filePath)) { return filePath; } if (systemInfo.pathExts) { for (const pathExt of systemInfo.pathExts) { const filePath = pathItem + command + pathExt; if (pathMatchesSync(environment, filePath)) { return filePath; } } } } return undefined; } function pathMatchesSync( environment: Omit<Environment, "stat">, path: string, ): boolean { try { const result = environment.statSync(path); return result.isFile; } catch (err) { if (err instanceof Deno.errors.PermissionDenied) { throw err; } return false; } } interface SystemInfo { pathItems: string[]; pathExts: string[] | undefined; isNameMatch: (a: string, b: string) => boolean; } function getSystemInfo( command: string, environment: Omit<Environment, "stat" | "statSync">, ): SystemInfo | undefined { const isWindows = environment.os === "windows"; const envValueSeparator = isWindows ? ";" : ":"; const path = environment.env("PATH"); const pathSeparator = isWindows ? "\\" : "/"; if (path == null) { return undefined; } return { pathItems: splitEnvValue(path).map((item) => normalizeDir(item)), pathExts: getPathExts(), isNameMatch: isWindows ? (a, b) => a.toLowerCase() === b.toLowerCase() : (a, b) => a === b, }; function getPathExts() { if (!isWindows) { return undefined; } const pathExtText = environment.env("PATHEXT") ?? ".EXE;.CMD;.BAT;.COM"; const pathExts = splitEnvValue(pathExtText); const lowerCaseCommand = command.toLowerCase(); for (const pathExt of pathExts) { // Do not use the pathExts if someone has provided a command // that ends with the extenion of an executable extension if (lowerCaseCommand.endsWith(pathExt.toLowerCase())) { return undefined; } } return pathExts; } function splitEnvValue(value: string) { return value .split(envValueSeparator) .map((item) => item.trim()) .filter((item) => item.length > 0); } function normalizeDir(dirPath: string) { if (!dirPath.endsWith(pathSeparator)) { dirPath += pathSeparator; } return dirPath; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/deno/stack-overflow/which/output.js
JavaScript
export class RealEnvironment { env(key) { return Deno.env.get(key); } stat(path) { return Deno.stat(path); } statSync(path) { return Deno.statSync(path); } get os() { return Deno.build.os; } } /** Finds the path to the specified command asynchronously. */ export async function which(command, environment = new RealEnvironment()) { const systemInfo = getSystemInfo(command, environment); if (systemInfo == null) { return undefined; } for (const pathItem of systemInfo.pathItems){ const filePath = pathItem + command; if (systemInfo.pathExts) { for (const pathExt of systemInfo.pathExts){ const filePath = pathItem + command + pathExt; if (await pathMatches(environment, filePath)) { return filePath; } } } else { if (await pathMatches(environment, filePath)) { return filePath; } } } return undefined; } async function pathMatches(environment, path) { try { const result = await environment.stat(path); return result.isFile; } catch (err) { if (err instanceof Deno.errors.PermissionDenied) { throw err; } return false; } } /** Finds the path to the specified command synchronously. */ export function whichSync(command, environment = new RealEnvironment()) { const systemInfo = getSystemInfo(command, environment); if (systemInfo == null) { return undefined; } for (const pathItem of systemInfo.pathItems){ const filePath = pathItem + command; if (pathMatchesSync(environment, filePath)) { return filePath; } if (systemInfo.pathExts) { for (const pathExt of systemInfo.pathExts){ const filePath = pathItem + command + pathExt; if (pathMatchesSync(environment, filePath)) { return filePath; } } } } return undefined; } function pathMatchesSync(environment, path) { try { const result = environment.statSync(path); return result.isFile; } catch (err) { if (err instanceof Deno.errors.PermissionDenied) { throw err; } return false; } } function getSystemInfo(command, environment) { const isWindows = environment.os === "windows"; const envValueSeparator = isWindows ? ";" : ":"; const path = environment.env("PATH"); const pathSeparator = isWindows ? "\\" : "/"; if (path == null) { return undefined; } return { pathItems: splitEnvValue(path).map((item)=>normalizeDir(item)), pathExts: getPathExts(), isNameMatch: isWindows ? (a, b)=>a.toLowerCase() === b.toLowerCase() : (a, b)=>a === b }; function getPathExts() { if (!isWindows) { return undefined; } const pathExtText = environment.env("PATHEXT") ?? ".EXE;.CMD;.BAT;.COM"; const pathExts = splitEnvValue(pathExtText); const lowerCaseCommand = command.toLowerCase(); for (const pathExt of pathExts){ // Do not use the pathExts if someone has provided a command // that ends with the extenion of an executable extension if (lowerCaseCommand.endsWith(pathExt.toLowerCase())) { return undefined; } } return pathExts; } function splitEnvValue(value) { return value.split(envValueSeparator).map((item)=>item.trim()).filter((item)=>item.length > 0); } function normalizeDir(dirPath) { if (!dirPath.endsWith(pathSeparator)) { dirPath += pathSeparator; } return dirPath; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/constructor/param/input.ts
TypeScript
class Foo { constructor(@dec1() p: string, @dec2() readonly p2: string) {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/constructor/param/output.ts
TypeScript
class Foo { constructor(p: string, readonly p2: string){} } Foo = _ts_decorate([ _ts_param(0, dec1()), _ts_param(1, dec2()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ String, String ]) ], Foo);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/1160/1/input.ts
TypeScript
enum MyEnum { x = "xxx", y = "yyy", } class Xpto { @Decorator() value!: MyEnum; } function Decorator() { return function (...args) {}; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/1160/1/output.ts
TypeScript
enum MyEnum { x = "xxx", y = "yyy" } class Xpto { value!: MyEnum; } _ts_decorate([ Decorator(), _ts_metadata("design:type", String) ], Xpto.prototype, "value", void 0); function Decorator() { return function(...args) {}; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/1278/1/input.ts
TypeScript
function MyDecorator(klass) { return () => { // do something console.log(klass); }; } class MyClass { @MyDecorator(MyClass) prop: ""; } console.log(new MyClass());
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/1278/1/output.ts
TypeScript
function MyDecorator(klass) { return ()=>{ // do something console.log(klass); }; } class MyClass { prop: ""; } _ts_decorate([ MyDecorator(MyClass), _ts_metadata("design:type", String) ], MyClass.prototype, "prop", void 0); console.log(new MyClass());
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/1421/1/input.ts
TypeScript
class User { @column() currency!: "usd" | "eur" | "yen"; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/1421/1/output.ts
TypeScript
class User { currency!: "usd" | "eur" | "yen"; } _ts_decorate([ column(), _ts_metadata("design:type", String) ], User.prototype, "currency", void 0);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/1456/1/input.ts
TypeScript
class MyClass { constructor(@Inject() param1: Injected) {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/1456/1/output.ts
TypeScript
class MyClass { constructor(param1: Injected){} } MyClass = _ts_decorate([ _ts_param(0, Inject()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof Injected === "undefined" ? Object : Injected ]) ], MyClass);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/2461/input.ts
TypeScript
const ThingDecorator: PropertyDecorator = () => {}; class Thing { @ThingDecorator thing?: string | null; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/2461/output.ts
TypeScript
const ThingDecorator: PropertyDecorator = ()=>{}; class Thing { thing?: string | null; } _ts_decorate([ ThingDecorator, _ts_metadata("design:type", Object) ], Thing.prototype, "thing", void 0);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/3319/input.ts
TypeScript
import 'reflect-metadata' let returnType: unknown; function decorator(target: any, key: string | symbol, descriptor: PropertyDescriptor): void { returnType = Reflect.getMetadata('design:returntype', target, key); } enum NumericEnum { A, B, C, } enum StringEnum { A = "A", B = "B", C = "C", } enum ObjectEnum { A = "A", B = 2, C = "C", } class Foo { @decorator public foo(x: string): string { return 'foo'; } @decorator public bar(x: string): number { return 123; } @decorator public baz(): string | number { return 'baz'; } @decorator public qux() { return 'qux'; } @decorator public async quux() { return 'quux'; } @decorator public numeric_array(): number[] { return [1, 2, 3]; } @decorator public string_array(): string[] { return ['first', 'second', 'third']; } @decorator public numeric_enum(): NumericEnum { return NumericEnum.A; } @decorator public string_enum(): StringEnum { return StringEnum.A; } @decorator public object_enum(): ObjectEnum { return ObjectEnum.A; } @decorator public array_enum(): StringEnum[] { return [StringEnum.A, StringEnum.B, StringEnum.C]; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/3319/output.ts
TypeScript
import 'reflect-metadata'; let returnType: unknown; function decorator(target: any, key: string | symbol, descriptor: PropertyDescriptor): void { returnType = Reflect.getMetadata('design:returntype', target, key); } enum NumericEnum { A, B, C } enum StringEnum { A = "A", B = "B", C = "C" } enum ObjectEnum { A = "A", B = 2, C = "C" } class Foo { public foo(x: string): string { return 'foo'; } public bar(x: string): number { return 123; } public baz(): string | number { return 'baz'; } public qux() { return 'qux'; } public async quux() { return 'quux'; } public numeric_array(): number[] { return [1, 2, 3]; } public string_array(): string[] { return ['first', 'second', 'third']; } public numeric_enum(): NumericEnum { return NumericEnum.A; } public string_enum(): StringEnum { return StringEnum.A; } public object_enum(): ObjectEnum { return ObjectEnum.A; } public array_enum(): StringEnum[] { return [StringEnum.A, StringEnum.B, StringEnum.C]; } } _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [String]), _ts_metadata("design:returntype", String) ], Foo.prototype, "foo", null); _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [String]), _ts_metadata("design:returntype", Number) ], Foo.prototype, "bar", null); _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", []), _ts_metadata("design:returntype", Object) ], Foo.prototype, "baz", null); _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", []), _ts_metadata("design:returntype", void 0) ], Foo.prototype, "qux", null); _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", []), _ts_metadata("design:returntype", Promise) ], Foo.prototype, "quux", null); _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", []), _ts_metadata("design:returntype", Array) ], Foo.prototype, "numeric_array", null); _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", []), _ts_metadata("design:returntype", Array) ], Foo.prototype, "string_array", null); _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", []), _ts_metadata("design:returntype", Number) ], Foo.prototype, "numeric_enum", null); _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", []), _ts_metadata("design:returntype", String) ], Foo.prototype, "string_enum", null); _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", []), _ts_metadata("design:returntype", Object) ], Foo.prototype, "object_enum", null); _ts_decorate([ decorator, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", []), _ts_metadata("design:returntype", Array) ], Foo.prototype, "array_enum", null);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/3979/input.ts
TypeScript
class A { @foo x = 1; constructor(); constructor() { console.log(123); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/3979/output.ts
TypeScript
class A { x = 1; constructor(); constructor(){ console.log(123); } } _ts_decorate([ foo ], A.prototype, "x", void 0);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/6683/input.ts
TypeScript
function decorator(): PropertyDecorator { return () => null } class Example { @decorator() value?: `prefix${string}`; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/6683/output.ts
TypeScript
function decorator(): PropertyDecorator { return ()=>null; } class Example { value?: `prefix${string}`; } _ts_decorate([ decorator(), _ts_metadata("design:type", String) ], Example.prototype, "value", void 0);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/9435/input.ts
TypeScript
import { Entity, Column } from "typeorm"; import { Field, ObjectType, registerEnumType } from "type-graphql"; import { Enum1, Enum2 } from "./enum.js"; export enum Enum3 { A = "A", B = "B", C = "C", D = "D", } registerEnumType(Enum3, { name: "Enum3" }); @Entity("user", { schema: "public" }) @ObjectType("User") export class User { @Column({ name: "first_name" }) @Field({ nullable: true }) firstName?: string; @Column({ name: "last_name" }) @Field({ nullable: true }) lastName?: string; @Field() get fullName(): string { if (!this.firstName && !this.lastName) { return ""; } return `${this.firstName} ${this.lastName}`.trim(); } @Column() @Field(() => Enum1) enum1: Enum1; @Column() @Field(() => Enum2) enum2: Enum2; @Column() @Field(() => Enum3) enum3: Enum3; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/issues/9435/output.ts
TypeScript
import { Entity, Column } from "typeorm"; import { Field, ObjectType, registerEnumType } from "type-graphql"; import { Enum1, Enum2 } from "./enum.js"; export enum Enum3 { A = "A", B = "B", C = "C", D = "D" } registerEnumType(Enum3, { name: "Enum3" }); export class User { firstName?: string; lastName?: string; get fullName(): string { if (!this.firstName && !this.lastName) { return ""; } return `${this.firstName} ${this.lastName}`.trim(); } enum1: Enum1; enum2: Enum2; enum3: Enum3; } _ts_decorate([ Column({ name: "first_name" }), Field({ nullable: true }), _ts_metadata("design:type", String) ], User.prototype, "firstName", void 0); _ts_decorate([ Column({ name: "last_name" }), Field({ nullable: true }), _ts_metadata("design:type", String) ], User.prototype, "lastName", void 0); _ts_decorate([ Field(), _ts_metadata("design:type", String), _ts_metadata("design:paramtypes", []) ], User.prototype, "fullName", null); _ts_decorate([ Column(), Field(()=>Enum1), _ts_metadata("design:type", typeof Enum1 === "undefined" ? Object : Enum1) ], User.prototype, "enum1", void 0); _ts_decorate([ Column(), Field(()=>Enum2), _ts_metadata("design:type", typeof Enum2 === "undefined" ? Object : Enum2) ], User.prototype, "enum2", void 0); _ts_decorate([ Column(), Field(()=>Enum3), _ts_metadata("design:type", String) ], User.prototype, "enum3", void 0); User = _ts_decorate([ Entity("user", { schema: "public" }), ObjectType("User") ], User);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/metadata/generics/1/input.ts
TypeScript
@Decorate class MyClass { constructor(private generic: Generic<A>, generic2: Generic<A, B>) {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/metadata/generics/1/output.ts
TypeScript
class MyClass { constructor(private generic: Generic<A>, generic2: Generic<A, B>){} } MyClass = _ts_decorate([ Decorate, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof Generic === "undefined" ? Object : Generic, typeof Generic === "undefined" ? Object : Generic ]) ], MyClass);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/metadata/generics/base/input.ts
TypeScript
@Decorate class MyClass { constructor(private generic: Generic<A>, generic2: Generic<A, B>) {} @Run method(generic: Inter<A>, @Arg() generic2: InterGen<A, B>) {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/metadata/generics/base/output.ts
TypeScript
class MyClass { constructor(private generic: Generic<A>, generic2: Generic<A, B>){} method(generic: Inter<A>, generic2: InterGen<A, B>) {} } _ts_decorate([ Run, _ts_param(1, Arg()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof Inter === "undefined" ? Object : Inter, typeof InterGen === "undefined" ? Object : InterGen ]), _ts_metadata("design:returntype", void 0) ], MyClass.prototype, "method", null); MyClass = _ts_decorate([ Decorate, _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof Generic === "undefined" ? Object : Generic, typeof Generic === "undefined" ? Object : Generic ]) ], MyClass);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/metadata/nest/injection/input.ts
TypeScript
import { AppService } from "./app.service"; import { Session, Res } from "@nestjs/common"; import * as express from "express"; @Controller() export class AppController { constructor(private appService: AppService) {} @Inject() appService: AppService; @Inject() private appService2: AppService; @Get() getHello(): string { return this.appService.getHello(); } @Get("/callback") async callback( @Res() res: express.Response, @Session() session: express.Express.Session ) { const token = await this.getToken(code); const user = await this.getUserInfo(token.access_token); session.oauth2Token = token; session.user = user; return res.redirect(state.returnUrl ?? "/"); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/metadata/nest/injection/output.ts
TypeScript
import { AppService } from "./app.service"; import { Session, Res } from "@nestjs/common"; import * as express from "express"; export class AppController { constructor(private appService: AppService){} appService: AppService; private appService2: AppService; getHello(): string { return this.appService.getHello(); } async callback(res: express.Response, session: express.Express.Session) { const token = await this.getToken(code); const user = await this.getUserInfo(token.access_token); session.oauth2Token = token; session.user = user; return res.redirect(state.returnUrl ?? "/"); } } _ts_decorate([ Inject(), _ts_metadata("design:type", typeof AppService === "undefined" ? Object : AppService) ], AppController.prototype, "appService", void 0); _ts_decorate([ Inject(), _ts_metadata("design:type", typeof AppService === "undefined" ? Object : AppService) ], AppController.prototype, "appService2", void 0); _ts_decorate([ Get(), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", []), _ts_metadata("design:returntype", String) ], AppController.prototype, "getHello", null); _ts_decorate([ Get("/callback"), _ts_param(0, Res()), _ts_param(1, Session()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof express === "undefined" || typeof express.Response === "undefined" ? Object : express.Response, typeof express === "undefined" || typeof express.Express === "undefined" || typeof express.Express.Session === "undefined" ? Object : express.Express.Session ]), _ts_metadata("design:returntype", Promise) ], AppController.prototype, "callback", null); AppController = _ts_decorate([ Controller(), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof AppService === "undefined" ? Object : AppService ]) ], AppController);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/metadata/paramters/decorated-types/input.ts
TypeScript
class Injected {} class MyClass { constructor(@inject() parameter: Injected) {} } class MyOtherClass { constructor( @inject() private readonly parameter: Injected, @inject("KIND") otherParam: Injected ) {} methodUndecorated(@demo() param: string, otherParam) {} @decorate("named") method(@inject() param: Injected, @arg() schema: Schema) {} } @Decorate class DecoratedClass { constructor( @inject() private readonly module: Injected, @inject() otherModule: Injected ) {} @decorate("example") method(@inject() param: string) {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/metadata/paramters/decorated-types/output.ts
TypeScript
class Injected { } class MyClass { constructor(parameter: Injected){} } MyClass = _ts_decorate([ _ts_param(0, inject()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof Injected === "undefined" ? Object : Injected ]) ], MyClass); class MyOtherClass { constructor(private readonly parameter: Injected, otherParam: Injected){} methodUndecorated(param: string, otherParam) {} method(param: Injected, schema: Schema) {} } _ts_decorate([ _ts_param(0, demo()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ String, void 0 ]), _ts_metadata("design:returntype", void 0) ], MyOtherClass.prototype, "methodUndecorated", null); _ts_decorate([ decorate("named"), _ts_param(0, inject()), _ts_param(1, arg()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof Injected === "undefined" ? Object : Injected, typeof Schema === "undefined" ? Object : Schema ]), _ts_metadata("design:returntype", void 0) ], MyOtherClass.prototype, "method", null); MyOtherClass = _ts_decorate([ _ts_param(0, inject()), _ts_param(1, inject("KIND")), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof Injected === "undefined" ? Object : Injected, typeof Injected === "undefined" ? Object : Injected ]) ], MyOtherClass); class DecoratedClass { constructor(private readonly module: Injected, otherModule: Injected){} method(param: string) {} } _ts_decorate([ decorate("example"), _ts_param(0, inject()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ String ]), _ts_metadata("design:returntype", void 0) ], DecoratedClass.prototype, "method", null); DecoratedClass = _ts_decorate([ Decorate, _ts_param(0, inject()), _ts_param(1, inject()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof Injected === "undefined" ? Object : Injected, typeof Injected === "undefined" ? Object : Injected ]) ], DecoratedClass);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/metadata/type/serialization/input.ts
TypeScript
import { Service } from "./service"; import { Decorate } from "./Decorate"; const sym = Symbol(); @Decorate() class Sample { constructor( private p0: String, p1: Number, p2: 10, p3: "ABC", p4: boolean, p5: string, p6: number, p7: Object, p8: () => any, p9: "abc" | "def", p10: String | Number, p11: Function, p12: null, p13: undefined, p14: any, p15: (abc: any) => void, p16: false, p17: true, p18: string = "abc" ) {} @Decorate method( @Arg() p0: Symbol, p1: typeof sym, p2: string | null, p3: never, p4: string | never, p5: string | null, p6: Maybe<string>, p7: Object | string, p8: string & MyStringType, p9: string[], p10: [string, number], p11: void, p12: this is number, p13: null | undefined, p14: string | (string | null), p15: Object, p16: any, p17: bigint ) {} /** * Member Expression */ @Decorate() method2(p0: Decorate.Name = "abc", p1: Decorate.Name) {} /** * Assignments */ @Decorate() assignments(p0: string = "abc") {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/metadata/type/serialization/output.ts
TypeScript
import { Service } from "./service"; import { Decorate } from "./Decorate"; const sym = Symbol(); class Sample { constructor(private p0: String, p1: Number, p2: 10, p3: "ABC", p4: boolean, p5: string, p6: number, p7: Object, p8: () => any, p9: "abc" | "def", p10: String | Number, p11: Function, p12: null, p13: undefined, p14: any, p15: (abc: any) => void, p16: false, p17: true, p18: string = "abc"){} method(p0: Symbol, p1: typeof sym, p2: string | null, p3: never, p4: string | never, p5: string | null, p6: Maybe<string>, p7: Object | string, p8: string & MyStringType, p9: string[], p10: [string, number], p11: void, p12: this is number, p13: null | undefined, p14: string | (string | null), p15: Object, p16: any, p17: bigint) {} /** * Member Expression */ method2(p0: Decorate.Name = "abc", p1: Decorate.Name) {} /** * Assignments */ assignments(p0: string = "abc") {} } _ts_decorate([ Decorate, _ts_param(0, Arg()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof Symbol === "undefined" ? Object : Symbol, Object, Object, void 0, String, Object, typeof Maybe === "undefined" ? Object : Maybe, Object, Object, Array, Array, void 0, Boolean, Object, Object, typeof Object === "undefined" ? Object : Object, Object, typeof BigInt === "undefined" ? Object : BigInt ]), _ts_metadata("design:returntype", void 0) ], Sample.prototype, "method", null); _ts_decorate([ Decorate(), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof Decorate === "undefined" || typeof Decorate.Name === "undefined" ? Object : Decorate.Name, typeof Decorate === "undefined" || typeof Decorate.Name === "undefined" ? Object : Decorate.Name ]), _ts_metadata("design:returntype", void 0) ], Sample.prototype, "method2", null); _ts_decorate([ Decorate(), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ String ]), _ts_metadata("design:returntype", void 0) ], Sample.prototype, "assignments", null); Sample = _ts_decorate([ Decorate(), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof String === "undefined" ? Object : String, typeof Number === "undefined" ? Object : Number, Number, String, Boolean, String, Number, typeof Object === "undefined" ? Object : Object, Function, String, Object, typeof Function === "undefined" ? Object : Function, void 0, void 0, Object, Function, Boolean, Boolean, String ]) ], Sample);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/method/param/input.ts
TypeScript
class Foo { foo(@dec1() p: string, @dec2() p2: string) {} static bar(@dec1() p: string, @dec2() p2: string) {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-metadata/method/param/output.ts
TypeScript
class Foo { foo(p: string, p2: string) {} static bar(p: string, p2: string) {} } _ts_decorate([ _ts_param(0, dec1()), _ts_param(1, dec2()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ String, String ]), _ts_metadata("design:returntype", void 0) ], Foo.prototype, "foo", null); _ts_decorate([ _ts_param(0, dec1()), _ts_param(1, dec2()), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ String, String ]), _ts_metadata("design:returntype", void 0) ], Foo, "bar", null);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/decl-to-expression/class-decorators/input.ts
TypeScript
export default @dec class A { } @dec class B { }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/decl-to-expression/class-decorators/output.ts
TypeScript
export default class A { } A = _ts_decorate([ dec ], A); class B { } B = _ts_decorate([ dec ], B);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/decl-to-expression/method-decorators/input.ts
TypeScript
export default class A { @dec foo() {} } class B { @dec foo() {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/decl-to-expression/method-decorators/output.ts
TypeScript
export default class A { foo() {} } _ts_decorate([ dec ], A.prototype, "foo", null); class B { foo() {} } _ts_decorate([ dec ], B.prototype, "foo", null);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/1869/1/input.ts
TypeScript
@someClassDecorator class TestClass { static Something = "hello"; static SomeProperties = { firstProp: TestClass.Something, }; } function someClassDecorator(c) { return c; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/1869/1/output.ts
TypeScript
class TestClass { static Something = "hello"; static SomeProperties = { firstProp: TestClass.Something }; } TestClass = _ts_decorate([ someClassDecorator ], TestClass); function someClassDecorator(c) { return c; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/1913/1/input.ts
TypeScript
class Store { constructor() { this.doSomething(); } @action doSomething = () => { console.log("run"); }; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/1913/1/output.ts
TypeScript
class Store { constructor(){ this.doSomething(); } doSomething = ()=>{ console.log("run"); }; } _ts_decorate([ action ], Store.prototype, "doSomething", void 0);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/1913/2/input.ts
TypeScript
class Store extends BaseStore { constructor() { super(); this.doSomething(); } @action doSomething = () => { console.log("run"); }; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/1913/2/output.ts
TypeScript
class Store extends BaseStore { constructor(){ super(); this.doSomething(); } doSomething = ()=>{ console.log("run"); }; } _ts_decorate([ action ], Store.prototype, "doSomething", void 0);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/591/1/input.ts
TypeScript
export class Example { @foo() bar = "1"; @foo() baz = "2"; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/591/1/output.ts
TypeScript
export class Example { bar = "1"; baz = "2"; } _ts_decorate([ foo() ], Example.prototype, "bar", void 0); _ts_decorate([ foo() ], Example.prototype, "baz", void 0);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/591/2/input.ts
TypeScript
class Example { @foo() bar = "1"; @foo() baz = "2"; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/591/2/output.ts
TypeScript
class Example { bar = "1"; baz = "2"; } _ts_decorate([ foo() ], Example.prototype, "bar", void 0); _ts_decorate([ foo() ], Example.prototype, "baz", void 0);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/823/1/input.ts
TypeScript
import { Debounce } from "lodash-decorators"; class Person { private static debounceTime: number = 500 as const; @Debounce(Person.debounceTime) save() { console.log("Hello World!"); } } const p = new Person(); p.save();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/823/1/output.ts
TypeScript
import { Debounce } from "lodash-decorators"; class Person { private static debounceTime: number = 500 as const; save() { console.log("Hello World!"); } } _ts_decorate([ Debounce(Person.debounceTime) ], Person.prototype, "save", null); const p = new Person(); p.save();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/823/2/input.ts
TypeScript
import { Debounce } from "lodash-decorators"; class Person { private static debounceTime: number = 500 as const; @Debounce(Person.debounceTime) save() { console.log("Hello World!"); } } const p = new Person(); p.save();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/823/2/output.ts
TypeScript
import { Debounce } from "lodash-decorators"; class Person { private static debounceTime: number = 500 as const; save() { console.log("Hello World!"); } } _ts_decorate([ Debounce(Person.debounceTime) ], Person.prototype, "save", null); const p = new Person(); p.save();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/823/3/input.ts
TypeScript
import { Debounce } from "lodash-decorators"; class Person { private static debounceTime: number = 500 as const; @Debounce(Person.debounceTime) save() { console.log("Hello World!"); } } const p = new Person(); p.save();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/823/3/output.ts
TypeScript
import { Debounce } from "lodash-decorators"; class Person { private static debounceTime: number = 500 as const; save() { console.log("Hello World!"); } } _ts_decorate([ Debounce(Person.debounceTime) ], Person.prototype, "save", null); const p = new Person(); p.save();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/862/1/input.ts
TypeScript
@Entity() export class Product extends TimestampedEntity { @PrimaryGeneratedColumn("uuid") public id!: string; @Column() public price!: number; @Column({ enum: ProductType }) public type!: ProductType; @Column() public productEntityId!: string; /* ANCHOR: Relations ------------------------------------------------------ */ @OneToMany(() => Order, (order) => order.product) public orders!: Order[]; @OneToMany(() => Discount, (discount) => discount.product) public discounts!: Discount[]; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/862/1/output.ts
TypeScript
export class Product extends TimestampedEntity { public id!: string; public price!: number; public type!: ProductType; public productEntityId!: string; /* ANCHOR: Relations ------------------------------------------------------ */ public orders!: Order[]; public discounts!: Discount[]; } _ts_decorate([ PrimaryGeneratedColumn("uuid") ], Product.prototype, "id", void 0); _ts_decorate([ Column() ], Product.prototype, "price", void 0); _ts_decorate([ Column({ enum: ProductType }) ], Product.prototype, "type", void 0); _ts_decorate([ Column() ], Product.prototype, "productEntityId", void 0); _ts_decorate([ OneToMany(()=>Order, (order)=>order.product) ], Product.prototype, "orders", void 0); _ts_decorate([ OneToMany(()=>Discount, (discount)=>discount.product) ], Product.prototype, "discounts", void 0); Product = _ts_decorate([ Entity() ], Product);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/862/2/input.ts
TypeScript
@Entity() export class Product extends TimestampedEntity { @PrimaryGeneratedColumn("uuid") public id!: string; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/862/2/output.ts
TypeScript
export class Product extends TimestampedEntity { public id!: string; } _ts_decorate([ PrimaryGeneratedColumn("uuid") ], Product.prototype, "id", void 0); Product = _ts_decorate([ Entity() ], Product);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/863/1/input.ts
TypeScript
class ProductController { @bar() findById( @foo() id: number ) { // ... } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/863/1/output.ts
TypeScript
class ProductController { findById(id: number) { // ... } } _ts_decorate([ bar(), _ts_param(0, foo()) ], ProductController.prototype, "findById", null);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/879/1/input.ts
TypeScript
export default class X { @networked prop: string = ""; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/879/1/output.ts
TypeScript
export default class X { prop: string = ""; } _ts_decorate([ networked ], X.prototype, "prop", void 0);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/swc-node-210/input.ts
TypeScript
class Foo { @dec [foo]() {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/issues/swc-node-210/output.ts
TypeScript
var _key; _key = foo; class Foo { [_key]() {} } _ts_decorate([ dec ], Foo.prototype, _key, null);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/regression-10264/input.ts
TypeScript
function myDecorator(decoratee) {} @myDecorator export default class {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/regression-10264/output.ts
TypeScript
function myDecorator(decoratee) {} export default class _class { } _class = _ts_decorate([ myDecorator ], _class);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/regression-8041/input.ts
TypeScript
export default class { @foo bar() {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms/tests/fixture/legacy-only/regression-8041/output.ts
TypeScript
export default class _class { bar() {} } _ts_decorate([ foo ], _class.prototype, "bar", null);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_antidro/src/lib.rs
Rust
#![allow(warnings)] use std::{ collections::{BTreeSet, HashMap, HashSet}, sync::{ atomic::{AtomicUsize, Ordering}, Mutex, OnceLock, }, }; use bimap::BiMap; use maplit::hashmap; use petgraph::{ algo::toposort, graph::{DiGraph, NodeIndex}, Direction, }; use swc_atoms::Atom; use swc_common::DUMMY_SP; use swc_ecma_ast::{ ArrayLit, ArrowExpr, AssignExpr, AssignTarget, BinExpr, BindingIdent, BlockStmtOrExpr, CallExpr, Callee, Decl, Expr, ExprOrSpread, ExprStmt, FnDecl, Ident, JSXAttrName, JSXAttrOrSpread, JSXAttrValue, JSXElement, JSXElementChild, JSXElementName, JSXExpr, KeyValueProp, Lit, MemberExpr, MemberProp, ModuleItem, Null, ObjectLit, Pass, Pat, Program, Prop, PropOrSpread, SimpleAssignTarget, Stmt, VarDecl, VarDeclarator, }; use swc_ecma_utils::{quote_ident, quote_str}; use swc_ecma_visit::{fold_pass, Fold, FoldWith, Visit, VisitMut}; #[cfg(test)] mod tests; struct Antidro; /* export let SolidCounter = () => { let [n, setN] = createSignal(0); let onClick = () => setN(n() + 1); return ( <div> <button type="button" onClick={onClick}> + </button> <span>{n()}</span> </div> ); }; export let CounterCustom = () => { let div = document.createElement("div"); let n = new Incr(0); let btn = document.createElement("button"); btn.innerText = "+"; btn.addEventListener("click", () => n.set(n.get() + 1)); let span = element("span", incrArray(n.lift(n => new Text(n.toString())))); div.append(btn, span); return div; }; */ fn call(func: &str, args: Vec<Expr>) -> Expr { Expr::Call(CallExpr { callee: Callee::Expr(quote_ident!(func).into()), args: args.into_iter().map(Into::into).collect(), ..Default::default() }) } fn method_call(this: Expr, prop: &str, args: Vec<Expr>) -> Expr { let callee = Expr::Member(MemberExpr { obj: this.into(), prop: quote_ident!(prop).into(), ..Default::default() }); Expr::Call(CallExpr { callee: Callee::Expr(callee.into()), args: args.into_iter().map(Into::into).collect(), ..Default::default() }) } fn arrow(params: Vec<&str>, body: BlockStmtOrExpr) -> Expr { Expr::Arrow(ArrowExpr { params: params .into_iter() .map(|param| quote_ident!(param).into()) .collect(), body: body.into(), ..Default::default() }) } fn binding(id: Ident, expr: Expr) -> Stmt { Stmt::Decl(Decl::Var(Box::new(VarDecl { decls: vec![VarDeclarator { span: DUMMY_SP, name: Pat::Ident(BindingIdent { id, ..Default::default() }), init: Some(Box::new(expr)), definite: true, }], ..Default::default() }))) } fn expr_stmt(e: Expr) -> Stmt { Stmt::Expr(ExprStmt { expr: Box::new(e), ..Default::default() }) } impl Pass for Antidro { fn process(&mut self, program: &mut Program) { let module = program.as_mut_module().unwrap(); for item in &mut module.body { if let ModuleItem::Stmt(Stmt::Decl(Decl::Fn(fn_decl))) = item { self.process_fn(fn_decl); } } } } impl Antidro { fn process_fn(&mut self, fn_decl: &mut FnDecl) { let body = fn_decl.function.body.as_mut().unwrap(); let Stmt::Return(ret) = body.stmts.last_mut().unwrap() else { unimplemented!() }; let val = ret.arg.as_deref_mut().unwrap(); let (id, stmts) = convert_ssa(&val); ret.arg = Some(Box::new(Expr::from(id))); let i = body.stmts.len() - 1; body.stmts.splice(i..i, stmts.clone()); for stmt in body.stmts[..i].iter_mut() { if let Stmt::Decl(decl) = stmt { if let Decl::Var(var_decl) = decl { let val = var_decl.decls[0].init.as_deref_mut().unwrap(); if let Expr::Arrow(arrow) = val { update_callback(arrow, &stmts); } } } } } } fn gensym(prefix: &str) -> Ident { static GENSYM_COUNTER: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new(); let gensym_counter = GENSYM_COUNTER.get_or_init(Default::default); let mut gensym_counter = gensym_counter.lock().unwrap(); let entry = gensym_counter.entry(prefix.to_string()).or_default(); let n = *entry; *entry += 1; quote_ident!(format!("{prefix}{n}")).into() } fn convert_ssa(expr: &Expr) -> (Expr, Vec<Stmt>) { match expr { Expr::Lit(..) | Expr::Object(..) | Expr::Ident(..) | Expr::Arrow(..) => { (expr.clone(), vec![]) } Expr::Array(arr) => { let (exprs, stmts): (Vec<_>, Vec<_>) = arr .elems .iter() .map(|el| convert_ssa(&el.as_ref().unwrap().expr)) .unzip(); let e = Expr::Array(ArrayLit { elems: exprs .into_iter() .map(|expr| { Some(ExprOrSpread { expr: Box::new(expr), spread: None, }) }) .collect(), ..Default::default() }); let stmts = stmts.into_iter().flatten().collect::<Vec<_>>(); (e, stmts) } Expr::Call(call_expr) => { let callee = match &call_expr.callee { Callee::Expr(callee) => &**callee, callee => unimplemented!("{callee:#?}"), }; let (exprs, stmts): (Vec<_>, Vec<_>) = call_expr .args .iter() .map(|arg| convert_ssa(&arg.expr)) .unzip(); const PRIMITIVES: &[&str] = &["element", "text", "map"]; match callee { Expr::Ident(ident) if PRIMITIVES.contains(&ident.sym.as_str()) => { let id = gensym(&ident.sym); let stmt = binding(id.clone(), call(&ident.sym, exprs)); let stmts = stmts .into_iter() .flatten() .chain([stmt]) .collect::<Vec<_>>(); (Expr::Ident(id), stmts) } _ => { let e = Expr::Call(CallExpr { callee: call_expr.callee.clone(), args: exprs .into_iter() .map(|expr| ExprOrSpread { expr: Box::new(expr), spread: None, }) .collect(), ..Default::default() }); (e, stmts.into_iter().flatten().collect()) } } } expr => unimplemented!("{expr:#?}"), } } #[derive(Debug, Clone)] enum ListChange { Push(Expr), Apply { i: usize, d: Box<Change> }, } #[derive(Debug, Clone)] enum Change { Set(Expr), List(ListChange), } impl Change { fn unwrap_list(self) -> ListChange { match self { Change::List(dl) => dl, _ => panic!("unwrap_list"), } } } type ChangeCtx = HashMap<Atom, Change>; fn update_callback(arrow: &mut ArrowExpr, els: &[Stmt]) { let body = arrow.body.as_mut_block_stmt().unwrap(); let mut updates = body .stmts .iter() .enumerate() .filter_map(|(i, stmt)| { let Stmt::Expr(expr) = stmt else { return None; }; let ctx = match &*expr.expr { Expr::Assign(assign) => match &assign.left { AssignTarget::Simple(assign_simple) => match assign_simple { SimpleAssignTarget::Ident(id) => { let lhs = assign.left.as_ident().unwrap(); hashmap! { lhs.sym.clone() => Change::Set(*assign.right.clone()) } } SimpleAssignTarget::Member(mem) => { match &mem.prop { MemberProp::Computed(computed) => { match &*computed.expr { Expr::Lit(Lit::Num(n)) => { let lhs = mem.obj.as_ident().unwrap(); let i = n.value.round() as usize; let d = Change::Set(*assign.right.clone()); hashmap! { lhs.sym.clone() => Change::List(ListChange::Apply { i, d: Box::new(d) })} } _ => todo!("{:#?}", assign.left) } }, _ => todo!("{:#?}", assign.left) } } _ => todo!("{:#?}", assign.left), }, _ => todo!("{:#?}", assign.left), }, Expr::Call(call_expr) => { let callee = call_expr.callee.as_expr().unwrap().as_ident().unwrap(); if callee.sym == "push" { let lhs = call_expr.args[0].expr.as_ident().unwrap(); let rhs = *call_expr.args[1].expr.clone(); hashmap! { lhs.sym.clone() => Change::List(ListChange::Push(rhs))} } else { return None; } } _ => return None, }; Some((i, gen_updates(&ctx, els))) }) .collect::<Vec<_>>(); updates.reverse(); for (i, stmts) in updates { body.stmts.splice(i + 1..i + 1, stmts); } } fn gen_updates(ctx: &ChangeCtx, els: &[Stmt]) -> Vec<Stmt> { els.iter() .flat_map(|el| { let decl = &el.as_decl().unwrap().as_var().unwrap().decls[0]; let lhs = decl.name.as_ident().unwrap(); let expr = decl.init.as_deref().unwrap(); gen_update(ctx, &lhs.sym, expr) }) .collect() } fn gen_changes(ctx: &ChangeCtx, expr: &Expr) -> Vec<Change> { match expr { Expr::Lit(..) | Expr::Object(..) => vec![], Expr::Ident(id) => ctx.get(&id.sym).into_iter().cloned().collect(), Expr::Array(arr) => arr .elems .iter() .enumerate() .flat_map(|(i, el)| { gen_changes(ctx, &el.as_ref().unwrap().expr) .into_iter() .map(move |d| Change::List(ListChange::Apply { i, d: Box::new(d) })) }) .collect(), Expr::Call(call_expr) => { let callee = call_expr.callee.as_expr().unwrap().as_ident().unwrap(); let arg_changes = || { call_expr .args .iter() .map(|arg| gen_changes(ctx, &arg.expr)) .collect::<Vec<_>>() }; if callee.sym == "element" { gen_changes(ctx, &call_expr.args[2].expr) } else if callee.sym == "text" { gen_changes(ctx, &call_expr.args[0].expr) } else if callee.sym == "map" { let l_changes = gen_changes(ctx, &call_expr.args[0].expr); let f = &*call_expr.args[1].expr; l_changes .into_iter() .flat_map(|change| match change.unwrap_list() { ListChange::Push(e) => { vec![Change::List(ListChange::Push(Expr::Call(CallExpr { callee: Callee::Expr(Box::new(f.clone())), args: vec![ExprOrSpread { expr: Box::new(e), spread: None, }], ..Default::default() })))] } ListChange::Apply { i, d } => { let f = f.as_arrow().unwrap(); let arg = &f.params[0].as_ident().unwrap().sym; let mut nested_ctx = ctx.clone(); nested_ctx.insert(arg.clone(), *d); gen_changes(&nested_ctx, f.body.as_expr().unwrap()) .into_iter() .map(|d| Change::List(ListChange::Apply { i, d: Box::new(d) })) .collect() } }) .collect() // let mut nested_ctx = ctx.clone(); // todo!() // nested_ctx.insert(f.p) // gen_changes() } else { let mut arg_changes = call_expr.args.iter().map(|arg| gen_changes(ctx, &arg.expr)); if arg_changes.any(|c| !c.is_empty()) { vec![Change::Set(expr.clone())] } else { vec![] } } } e => todo!("{e:#?}"), } } fn gen_update(ctx: &ChangeCtx, el_ident: &Atom, expr: &Expr) -> Vec<Stmt> { let changes = gen_changes(ctx, expr); let el_expr = Expr::Ident(el_ident.clone().into()); changes .into_iter() .map(|change| match change { Change::List(dl) => match dl { ListChange::Push(e) => expr_stmt(call("appendChild", vec![el_expr.clone(), e])), ListChange::Apply { i, d } => { // println!("{i} {d:#?}"); todo!() } }, Change::Set(e) => expr_stmt(call("setInnerText", vec![el_expr.clone(), e])), }) .collect() } /* fn build_graph(expr: &Expr) -> (Ident, DiGraph<(), ()>, BiMap<String, NodeIndex>, Vec<Stmt>) { let mut graph = DiGraph::new(); let mut node_map = HashMap::new(); let mut id_map = BiMap::new(); let root_id = build_dependency_graph(expr, &mut graph, &mut node_map, &mut id_map); let sorted_nodes = toposort(&graph, None).unwrap(); let stmts = sorted_nodes .into_iter() .map(|node_idx| node_map.remove(&node_idx).unwrap()) .collect(); (root_id, graph, id_map, stmts) } fn build_dependency_graph( expr: &Expr, graph: &mut DiGraph<(), ()>, node_map: &mut HashMap<NodeIndex, Stmt>, id_map: &mut BiMap<String, NodeIndex>, ) -> Ident { match expr { Expr::Lit(..) | Expr::Object(..) => { let id = gensym("lit"); let node_idx = graph.add_node(()); let stmt = binding(id.clone(), call("constant", vec![expr.clone()])); node_map.insert(node_idx, stmt); id_map.insert(id.sym.to_string(), node_idx); id } Expr::Ident(id) => id.clone(), Expr::Array(arr) => { let id = gensym("arr"); let node_idx = graph.add_node(()); let mut idents = Vec::new(); for child in arr.elems.iter().filter_map(|e| e.as_ref()) { let child_id = build_dependency_graph(&child.expr, graph, node_map, id_map); idents.push(child_id.clone()); // Add dependency edge if the child is not just an identifier let child_node = id_map[&child_id.sym.to_string()]; graph.add_edge(child_node, node_idx, ()); } let ident_arr = call("array", idents.into_iter().map(Expr::from).collect()); let stmt = binding(id.clone(), ident_arr); node_map.insert(node_idx, stmt); id_map.insert(id.sym.to_string(), node_idx); id } Expr::Bin(binop) => { let id = gensym("bin"); let node_idx = graph.add_node(()); let x1 = build_dependency_graph(&binop.left, graph, node_map, id_map); let x2 = build_dependency_graph(&binop.right, graph, node_map, id_map); // Add dependency edges if let Some(&left_node) = id_map.get(&x1.sym.to_string()) { graph.add_edge(left_node, node_idx, ()); } if let Some(&right_node) = id_map.get(&x2.sym.to_string()) { graph.add_edge(right_node, node_idx, ()); } let e = Expr::Bin(BinExpr { left: Expr::Ident(x1.clone()).into(), right: Expr::Ident(x2.clone()).into(), op: binop.op.clone(), ..Default::default() }); let stmt = binding( id.clone(), call( "lift2", vec![ Expr::Ident(x1.clone()).into(), Expr::Ident(x2.clone()).into(), arrow(vec![&x1.sym, &x2.sym], BlockStmtOrExpr::Expr(Box::new(e))), ], ), ); node_map.insert(node_idx, stmt); id_map.insert(id.sym.to_string(), node_idx); id } Expr::Call(call_expr) => { let id = gensym("call"); let node_idx = graph.add_node(()); let callee = match &call_expr.callee { Callee::Expr(callee) => &**callee, callee => unimplemented!("{callee:#?}"), }; let mut arg_idents = Vec::new(); for arg in &call_expr.args { let arg_id = build_dependency_graph(&arg.expr, graph, node_map, id_map); arg_idents.push(arg_id.clone()); // Add dependency edge if the arg is not just an identifier if let Some(&arg_node) = id_map.get(&arg_id.sym.to_string()) { graph.add_edge(arg_node, node_idx, ()); } } const PRIMITIVES: &[&str] = &["element", "map"]; let e = match callee { Expr::Ident(ident) if PRIMITIVES.contains(&ident.sym.as_str()) => { call(&ident.sym, arg_idents.into_iter().map(Expr::from).collect()) } _ => unimplemented!("{expr:#?}"), }; let stmt = binding(id.clone(), e); node_map.insert(node_idx, stmt); id_map.insert(id.sym.to_string(), node_idx); id } expr => unimplemented!("{expr:#?}"), } } */ pub fn antidro() -> impl Pass { Antidro }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_antidro/src/tests.rs
Rust
use swc_ecma_ast::Pass; use swc_ecma_transforms_testing::{test, Tester}; use crate::antidro; fn tr(_t: &mut Tester) -> impl Pass { // let unresolved_mark = Mark::new(); antidro() } test!( module, ::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsSyntax { ..Default::default() }), tr, antidro_simple, r#"function App() { let n = 0; let onClick = () => { n = n + 1; }; return element("div", {}, [ element("button", {onClick: onClick}, [text("+")]), element("span", {}, [text(toString(n))]) ]); };"# ); test!( module, ::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsSyntax { ..Default::default() }), tr, antidro_map_push, r#"function App() { let l = []; let onClick = () => { push(l, "Hello"); }; return element("ul", {}, map(l, s => element("li", {}, [text(s)]))); };"# ); test!( module, ::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsSyntax { ..Default::default() }), tr, antidro_map_set, r#"function App() { let l = ["Foo"]; let onClick = () => { l[0] = "Bar"; }; return element("ul", {}, map(l, s => element("li", {}, [text(s)]))); };"# ); /* let x0 = n; let x1 = 2; let x2 = n * 2; let x3 = [x2]; let x4 = {}; let x5 = "span"; let x6 = element(x5, x4, x3); ... */
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_antidro/tests/__swc_snapshots__/src/tests.rs/antidro_map.js
JavaScript
function App() { let l = []; let onClick = ()=>{ push(l, "Hello"); appendChild(el0, ((s)=>element("li", {}, [ text(s) ]))("Hello")); }; var el0 = element("ul", {}, map(l, (s)=>element("li", {}, [ text(s) ]))); return el0; } ;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_antidro/tests/__swc_snapshots__/src/tests.rs/antidro_map_set.js
JavaScript
function App() { let l = [ "Foo" ]; let onClick = ()=>{ l[0] = "Bar"; }; var map0 = map(l, (s)=>element("li", {}, [ text(s) ])); var element0 = element("ul", {}, map0); return element0; } ;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_antidro/tests/__swc_snapshots__/src/tests.rs/antidro_simple.js
JavaScript
function App() { let n = 0; let onClick = ()=>{ n = n + 1; setInnerText(text1, toString(n)); }; var text0 = text("+"); var element0 = element("button", { onClick: onClick }, [ text0 ]); var text1 = text(toString(n)); var element1 = element("span", {}, [ text1 ]); var element2 = element("div", {}, [ element0, element1 ]); return element2; } ;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/benches/assets/AjaxObservable.ts
TypeScript
/** @prettier */ import { Observable } from '../../Observable'; import { Subscriber } from '../../Subscriber'; import { TeardownLogic, PartialObserver } from '../../types'; export interface AjaxRequest { url?: string; body?: any; user?: string; async?: boolean; method?: string; headers?: object; timeout?: number; password?: string; hasContent?: boolean; crossDomain?: boolean; withCredentials?: boolean; createXHR?: () => XMLHttpRequest; progressSubscriber?: PartialObserver<ProgressEvent>; responseType?: string; } function isFormData(body: any): body is FormData { return typeof FormData !== 'undefined' && body instanceof FormData; } /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export class AjaxObservable<T> extends Observable<T> { private request: AjaxRequest; constructor(urlOrRequest: string | AjaxRequest) { super(); const request: AjaxRequest = { async: true, createXHR: () => new XMLHttpRequest(), crossDomain: true, withCredentials: false, headers: {}, method: 'GET', responseType: 'json', timeout: 0, }; if (typeof urlOrRequest === 'string') { request.url = urlOrRequest; } else { for (const prop in urlOrRequest) { if (urlOrRequest.hasOwnProperty(prop)) { (request as any)[prop] = (urlOrRequest as any)[prop]; } } } this.request = request; } /** @deprecated This is an internal implementation detail, do not use. */ _subscribe(subscriber: Subscriber<T>): TeardownLogic { return new AjaxSubscriber(subscriber, this.request); } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ export class AjaxSubscriber<T> extends Subscriber<Event> { // @ts-ignore: Property has no initializer and is not definitely assigned private xhr: XMLHttpRequest; private done: boolean = false; constructor(destination: Subscriber<T>, public request: AjaxRequest) { super(destination); const headers = (request.headers = request.headers || {}); // force CORS if requested if (!request.crossDomain && !this.getHeader(headers, 'X-Requested-With')) { (headers as any)['X-Requested-With'] = 'XMLHttpRequest'; } // ensure content type is set let contentTypeHeader = this.getHeader(headers, 'Content-Type'); if (!contentTypeHeader && typeof request.body !== 'undefined' && !isFormData(request.body)) { (headers as any)['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; } // properly serialize body request.body = this.serializeBody(request.body, this.getHeader(request.headers, 'Content-Type')); this.send(); } next(e: Event): void { this.done = true; const destination = this.destination as Subscriber<any>; let result: AjaxResponse; try { result = new AjaxResponse(e, this.xhr, this.request); } catch (err) { return destination.error(err); } destination.next(result); } private send(): void { const { request, request: { user, method, url, async, password, headers, body }, } = this; try { const xhr = (this.xhr = request.createXHR!()); // set up the events before open XHR // https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest // You need to add the event listeners before calling open() on the request. // Otherwise the progress events will not fire. this.setupEvents(xhr, request); // open XHR if (user) { xhr.open(method!, url!, async!, user, password); } else { xhr.open(method!, url!, async!); } // timeout, responseType and withCredentials can be set once the XHR is open if (async) { xhr.timeout = request.timeout!; xhr.responseType = request.responseType as any; } if ('withCredentials' in xhr) { xhr.withCredentials = !!request.withCredentials; } // set headers this.setHeaders(xhr, headers!); // finally send the request if (body) { xhr.send(body); } else { xhr.send(); } } catch (err) { this.error(err); } } private serializeBody(body: any, contentType?: string) { if (!body || typeof body === 'string') { return body; } else if (isFormData(body)) { return body; } if (contentType) { const splitIndex = contentType.indexOf(';'); if (splitIndex !== -1) { contentType = contentType.substring(0, splitIndex); } } switch (contentType) { case 'application/x-www-form-urlencoded': return Object.keys(body) .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(body[key])}`) .join('&'); case 'application/json': return JSON.stringify(body); default: return body; } } private setHeaders(xhr: XMLHttpRequest, headers: Object) { for (let key in headers) { if (headers.hasOwnProperty(key)) { xhr.setRequestHeader(key, (headers as any)[key]); } } } private getHeader(headers: {}, headerName: string): any { for (let key in headers) { if (key.toLowerCase() === headerName.toLowerCase()) { return (headers as any)[key]; } } return undefined; } private setupEvents(xhr: XMLHttpRequest, request: AjaxRequest) { const progressSubscriber = request.progressSubscriber; xhr.ontimeout = (e: ProgressEvent) => { progressSubscriber?.error?.(e); let error; try { error = new AjaxTimeoutError(xhr, request); // TODO: Make better. } catch (err) { error = err; } this.error(error); }; if (progressSubscriber) { xhr.upload.onprogress = (e: ProgressEvent) => { progressSubscriber.next?.(e); }; } xhr.onerror = (e: ProgressEvent) => { progressSubscriber?.error?.(e); this.error(new AjaxError('ajax error', xhr, request)); }; xhr.onload = (e: ProgressEvent) => { // 4xx and 5xx should error (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) if (xhr.status < 400) { progressSubscriber?.complete?.(); this.next(e); this.complete(); } else { progressSubscriber?.error?.(e); let error; try { error = new AjaxError('ajax error ' + xhr.status, xhr, request); } catch (err) { error = err; } this.error(error); } }; } unsubscribe() { const { done, xhr } = this; if (!done && xhr && xhr.readyState !== 4 && typeof xhr.abort === 'function') { xhr.abort(); } super.unsubscribe(); } } /** * A normalized AJAX response. * * @see {@link ajax} * * @class AjaxResponse */ export class AjaxResponse { /** @type {number} The HTTP status code */ status: number; /** @type {string|ArrayBuffer|Document|object|any} The response data */ response: any; /** @type {string} The raw responseText */ // @ts-ignore: Property has no initializer and is not definitely assigned responseText: string; /** @type {string} The responseType (e.g. 'json', 'arraybuffer', or 'xml') */ responseType: string; constructor(public originalEvent: Event, public xhr: XMLHttpRequest, public request: AjaxRequest) { this.status = xhr.status; this.responseType = xhr.responseType || request.responseType!; this.response = getXHRResponse(xhr); } } export type AjaxErrorNames = 'AjaxError' | 'AjaxTimeoutError'; /** * A normalized AJAX error. * * @see {@link ajax} * * @class AjaxError */ export interface AjaxError extends Error { /** * The XHR instance associated with the error */ xhr: XMLHttpRequest; /** * The AjaxRequest associated with the error */ request: AjaxRequest; /** *The HTTP status code */ status: number; /** *The responseType (e.g. 'json', 'arraybuffer', or 'xml') */ responseType: XMLHttpRequestResponseType; /** * The response data */ response: any; } export interface AjaxErrorCtor { /** * Internal use only. Do not manually create instances of this type. * @internal */ new (message: string, xhr: XMLHttpRequest, request: AjaxRequest): AjaxError; } const AjaxErrorImpl = (() => { function AjaxErrorImpl(this: any, message: string, xhr: XMLHttpRequest, request: AjaxRequest): AjaxError { Error.call(this); this.message = message; this.name = 'AjaxError'; this.xhr = xhr; this.request = request; this.status = xhr.status; this.responseType = xhr.responseType; let response: any; try { response = getXHRResponse(xhr); } catch (err) { response = xhr.responseText; } this.response = response; return this; } AjaxErrorImpl.prototype = Object.create(Error.prototype); return AjaxErrorImpl; })(); /** * Thrown when an error occurs during an AJAX request. * This is only exported because it is useful for checking to see if an error * is an `instanceof AjaxError`. DO NOT create new instances of `AjaxError` with * the constructor. * * @class AjaxError * @see ajax */ export const AjaxError: AjaxErrorCtor = AjaxErrorImpl as any; function getXHRResponse(xhr: XMLHttpRequest) { switch (xhr.responseType) { case 'json': { if ('response' in xhr) { return xhr.response; } else { // IE const ieXHR: any = xhr; return JSON.parse(ieXHR.responseText); } } case 'document': return xhr.responseXML; case 'text': default: { if ('response' in xhr) { return xhr.response; } else { // IE const ieXHR: any = xhr; return ieXHR.responseText; } } } } export interface AjaxTimeoutError extends AjaxError {} export interface AjaxTimeoutErrorCtor { /** * Internal use only. Do not manually create instances of this type. * @internal */ new (xhr: XMLHttpRequest, request: AjaxRequest): AjaxTimeoutError; } const AjaxTimeoutErrorImpl = (() => { function AjaxTimeoutErrorImpl(this: any, xhr: XMLHttpRequest, request: AjaxRequest) { AjaxError.call(this, 'ajax timeout', xhr, request); this.name = 'AjaxTimeoutError'; return this; } AjaxTimeoutErrorImpl.prototype = Object.create(AjaxError.prototype); return AjaxTimeoutErrorImpl; })(); /** * Thrown when an AJAX request timeout. Not to be confused with {@link TimeoutError}. * * This is exported only because it is useful for checking to see if errors are an * `instanceof AjaxTimeoutError`. DO NOT use the constructor to create an instance of * this type. * * @class AjaxTimeoutError * @see ajax */ export const AjaxTimeoutError: AjaxTimeoutErrorCtor = AjaxTimeoutErrorImpl as any;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/benches/base.rs
Rust
#![allow(clippy::redundant_closure_call)] extern crate swc_malloc; use codspeed_criterion_compat::{black_box, criterion_group, criterion_main, Bencher, Criterion}; use swc_common::{errors::HANDLER, FileName, Mark}; use swc_ecma_ast::Program; use swc_ecma_parser::{Parser, StringInput, Syntax}; use swc_ecma_transforms_base::helpers; static SOURCE: &str = include_str!("../../swc_ecma_minifier/benches/full/typescript.js"); /// Benchmark a folder macro_rules! tr { ($b:expr, $tr:expr) => { let _ = ::testing::run_test(false, |cm, handler| { HANDLER.set(&handler, || { let fm = cm.new_source_file(FileName::Anon.into(), SOURCE.into()); let mut parser = Parser::new( Syntax::Typescript(Default::default()), StringInput::from(&*fm), None, ); let module = parser.parse_module().map_err(|_| ()).unwrap(); helpers::HELPERS.set(&Default::default(), || { $b.iter(|| { let module = Program::Module(module.clone()); black_box(module.apply($tr())) }); Ok(()) }) }) }); }; } fn resolver(b: &mut Bencher) { tr!(b, || swc_ecma_transforms_base::resolver( Mark::new(), Mark::new(), false )); } fn fixer(b: &mut Bencher) { tr!(b, || swc_ecma_transforms_base::fixer::fixer(None)); } fn hygiene(b: &mut Bencher) { tr!(b, swc_ecma_transforms_base::hygiene::hygiene); } fn resolver_with_hygiene(b: &mut Bencher) { tr!(b, || ( swc_ecma_transforms_base::resolver(Mark::new(), Mark::new(), false), swc_ecma_transforms_base::hygiene::hygiene() )); } fn bench_cases(c: &mut Criterion) { c.bench_function("es/resolver/typescript", resolver); c.bench_function("es/fixer/typescript", fixer); c.bench_function("es/hygiene/typescript", hygiene); c.bench_function("es/resolver_with_hygiene/typescript", resolver_with_hygiene); } criterion_group!(benches, bench_cases); criterion_main!(benches);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/benches/parallel.rs
Rust
#![allow(clippy::redundant_closure_call)] extern crate swc_malloc; use codspeed_criterion_compat::{black_box, criterion_group, criterion_main, Bencher, Criterion}; use rayon::prelude::*; use swc_common::{errors::HANDLER, FileName, Mark, GLOBALS}; use swc_ecma_ast::Program; use swc_ecma_parser::{Parser, StringInput, Syntax}; use swc_ecma_transforms_base::helpers; static SOURCE: &str = include_str!("../../swc_ecma_minifier/benches/full/typescript.js"); /// Benchmark a folder macro_rules! tr { ($b:expr, $tr:expr) => { let _ = ::testing::run_test(false, |cm, handler| { let fm = cm.new_source_file(FileName::Anon.into(), SOURCE.into()); let mut parser = Parser::new( Syntax::Typescript(Default::default()), StringInput::from(&*fm), None, ); let module = Program::Module(parser.parse_module().map_err(|_| ()).unwrap()); $b.iter(|| { GLOBALS.with(|globals| { (0..50).into_par_iter().for_each(|_| { GLOBALS.set(globals, || { HANDLER.set(&handler, || { helpers::HELPERS.set(&Default::default(), || { let tr = $tr(); let module = module.clone(); black_box(module.apply(tr)); }) }) }) }) }) }); Ok(()) }); }; } fn resolver(b: &mut Bencher) { tr!(b, || swc_ecma_transforms_base::resolver( Mark::new(), Mark::new(), false )); } fn hygiene(b: &mut Bencher) { tr!(b, swc_ecma_transforms_base::hygiene::hygiene); } fn bench_cases(c: &mut Criterion) { let mut group = c.benchmark_group("es/base/parallel"); group.sample_size(10); group.bench_function("resolver/typescript", resolver); group.bench_function("hygiene/typescript", hygiene); } criterion_group!(benches, bench_cases); criterion_main!(benches);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/assumptions.rs
Rust
use serde::{Deserialize, Serialize}; /// Alternative for https://babeljs.io/docs/en/assumptions /// /// All fields default to `false`. #[derive( Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, )] #[non_exhaustive] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Assumptions { /// https://babeljs.io/docs/en/assumptions#arraylikeisiterable #[serde(default)] pub array_like_is_iterable: bool, /// https://babeljs.io/docs/en/assumptions#constantreexports #[serde(default)] pub constant_reexports: bool, /// https://babeljs.io/docs/en/assumptions#constantsuper #[serde(default)] pub constant_super: bool, /// https://babeljs.io/docs/en/assumptions#enumerablemodulemeta #[serde(default)] pub enumerable_module_meta: bool, /// https://babeljs.io/docs/en/assumptions#ignorefunctionlength #[serde(default)] pub ignore_function_length: bool, #[serde(default)] pub ignore_function_name: bool, /// https://babeljs.io/docs/en/assumptions#ignoretoprimitivehint #[serde(default)] pub ignore_to_primitive_hint: bool, /// https://babeljs.io/docs/en/assumptions#iterableisarray #[serde(default)] pub iterable_is_array: bool, /// https://babeljs.io/docs/en/assumptions#mutabletemplateobject #[serde(default)] pub mutable_template_object: bool, /// https://babeljs.io/docs/en/assumptions#noclasscalls #[serde(default)] pub no_class_calls: bool, /// https://babeljs.io/docs/en/assumptions#nodocumentall #[serde(default)] pub no_document_all: bool, /// https://babeljs.io/docs/en/assumptions#noincompletensimportdetection #[serde(default)] pub no_incomplete_ns_import_detection: bool, /// https://babeljs.io/docs/en/assumptions#nonewarrows #[serde(default)] pub no_new_arrows: bool, /// https://babeljs.io/docs/en/assumptions#objectrestnosymbols #[serde(default)] pub object_rest_no_symbols: bool, /// https://babeljs.io/docs/en/assumptions#privatefieldsasproperties #[serde(default)] pub private_fields_as_properties: bool, /// https://babeljs.io/docs/en/assumptions#puregetters #[serde(default)] pub pure_getters: bool, /// https://babeljs.io/docs/en/assumptions#setclassmethods #[serde(default)] pub set_class_methods: bool, /// https://babeljs.io/docs/en/assumptions#setcomputedproperties #[serde(default)] pub set_computed_properties: bool, /// https://babeljs.io/docs/en/assumptions#setpublicclassfields #[serde(default)] pub set_public_class_fields: bool, /// https://babeljs.io/docs/en/assumptions#setspreadproperties #[serde(default)] pub set_spread_properties: bool, /// https://babeljs.io/docs/en/assumptions#skipforofiteratorclosing #[serde(default)] pub skip_for_of_iterator_closing: bool, /// https://babeljs.io/docs/en/assumptions#superiscallableconstructor #[serde(default)] pub super_is_callable_constructor: bool, } #[allow(deprecated)] impl Assumptions { pub fn all() -> Self { Self { array_like_is_iterable: true, constant_reexports: true, constant_super: true, enumerable_module_meta: true, ignore_function_length: true, ignore_function_name: true, ignore_to_primitive_hint: true, iterable_is_array: true, mutable_template_object: true, no_class_calls: true, no_document_all: true, no_incomplete_ns_import_detection: true, no_new_arrows: true, object_rest_no_symbols: true, private_fields_as_properties: true, pure_getters: true, set_class_methods: true, set_computed_properties: true, set_public_class_fields: true, set_spread_properties: true, skip_for_of_iterator_closing: true, super_is_callable_constructor: true, } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/ext.rs
Rust
//! Do not use: This is not a public api and it can be changed without a version //! bump. use swc_ecma_ast::*; use swc_ecma_utils::ExprExt; pub trait ExprRefExt: ExprExt { fn as_ident(&self) -> Option<&Ident> { match self.as_expr() { Expr::Ident(ref i) => Some(i), _ => None, } } } impl<T> ExprRefExt for T where T: ExprExt {} /// Do not use: This is not a public api and it can be changed without a version /// bump. pub trait AsOptExpr { fn as_expr(&self) -> Option<&Expr>; fn as_expr_mut(&mut self) -> Option<&mut Expr>; } impl AsOptExpr for Callee { fn as_expr(&self) -> Option<&Expr> { match self { Callee::Super(_) | Callee::Import(_) => None, Callee::Expr(e) => Some(e), } } fn as_expr_mut(&mut self) -> Option<&mut Expr> { match self { Callee::Super(_) | Callee::Import(_) => None, Callee::Expr(e) => Some(e), } } } impl<N> AsOptExpr for Option<N> where N: AsOptExpr, { fn as_expr(&self) -> Option<&Expr> { match self { Some(n) => n.as_expr(), None => None, } } fn as_expr_mut(&mut self) -> Option<&mut Expr> { match self { None => None, Some(n) => n.as_expr_mut(), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/feature.rs
Rust
#![allow(non_upper_case_globals)] use bitflags::bitflags; use swc_ecma_ast::EsVersion::{self, *}; bitflags! { #[derive(Default, Clone, Copy)] pub struct FeatureFlag: u64 { /// `transform-template-literals` const TemplateLiterals = 1 << 0; /// `transform-literals` const Literals = 1 << 1; /// `transform-function-name` const FunctionName = 1 << 2; /// `transform-arrow-functions` const ArrowFunctions = 1 << 3; /// `transform-block-scoped-functions` const BlockScopedFunctions = 1 << 4; /// `transform-classes` const Classes = 1 << 5; /// `transform-object-super` const ObjectSuper = 1 << 6; /// `transform-shorthand-properties` const ShorthandProperties = 1 << 7; /// `transform-duplicate-keys` const DuplicateKeys = 1 << 8; /// `transform-computed-properties` const ComputedProperties = 1 << 9; /// `transform-for-of` const ForOf = 1 << 10; /// `transform-sticky-regex` const StickyRegex = 1 << 11; /// `transform-dotall-regex` const DotAllRegex = 1 << 12; /// `transform-unicode-regex` const UnicodeRegex = 1 << 13; /// `transform-spread` const Spread = 1 << 14; /// `transform-parameters` const Parameters = 1 << 15; /// `transform-destructuring` const Destructuring = 1 << 16; /// `transform-block-scoping` const BlockScoping = 1 << 17; /// `transform-typeof-symbol` const TypeOfSymbol = 1 << 18; /// `transform-new-target` const NewTarget = 1 << 19; /// `transform-regenerator` const Regenerator = 1 << 20; /// `transform-exponentiation-operator` const ExponentiationOperator = 1 << 21; /// `transform-async-to-generator` const AsyncToGenerator = 1 << 22; /// `proposal-async-generator-functions` const AsyncGeneratorFunctions = 1 << 23; /// `proposal-object-rest-spread` const ObjectRestSpread = 1 << 24; /// `proposal-unicode-property-regex` const UnicodePropertyRegex = 1 << 25; /// `proposal-json-strings` const JsonStrings = 1 << 26; /// `proposal-optional-catch-binding` const OptionalCatchBinding = 1 << 27; /// `transform-named-capturing-groups-regex` const NamedCapturingGroupsRegex = 1 << 28; /// `transform-member-expression-literals` const MemberExpressionLiterals = 1 << 29; /// `transform-property-literals` const PropertyLiterals = 1 << 30; /// `transform-reserved-words` const ReservedWords = 1 << 31; /// `proposal-export-namespace-from` const ExportNamespaceFrom = 1 << 32; /// `proposal-nullish-coalescing-operator` const NullishCoalescing = 1 << 33; /// `proposal-logical-assignment-operators` const LogicalAssignmentOperators = 1 << 34; /// `proposal-optional-chaining` const OptionalChaining = 1 << 35; /// `proposal-class-properties` const ClassProperties = 1 << 36; /// `proposal-numeric-separator` const NumericSeparator = 1 << 37; /// `proposal-private-methods` const PrivateMethods = 1 << 38; /// `proposal-class-static-block` const ClassStaticBlock = 1 << 39; /// `proposal-private-property-in-object` const PrivatePropertyInObject = 1 << 40; /// `transform-unicode-escapes` const UnicodeEscapes = 1 << 41; /// `bugfix/transform-async-arrows-in-class` const BugfixAsyncArrowsInClass = 1 << 42; /// `bugfix/transform-edge-default-parameters` const BugfixEdgeDefaultParam = 1 << 43; /// `bugfix/transform-tagged-template-caching` const BugfixTaggedTemplateCaching = 1 << 44; /// `bugfix/transform-safari-id-destructuring-collision-in-function-expression` const BugfixSafariIdDestructuringCollisionInFunctionExpression = 1 << 45; /// `bugfix/transform-edge-function-name` const BugfixTransformEdgeFunctionName = 1 << 46; // TODO /// `bugfix/transform-safari-block-shadowing` const BugfixTransformSafariBlockShadowing = 1 << 47; // TODO /// `bugfix/transform-safari-for-shadowing` const BugfixTransformSafariForShadowing = 1 << 48; // TODO /// `bugfix/transform-v8-spread-parameters-in-optional-chaining` const BugfixTransformV8SpreadParametersInOptionalChaining = 1 << 49; // TODO } } pub fn enable_available_feature_from_es_version(version: EsVersion) -> FeatureFlag { let mut feature = FeatureFlag::empty(); if version < Es5 { return feature; } feature |= FeatureFlag::PropertyLiterals | FeatureFlag::MemberExpressionLiterals | FeatureFlag::ReservedWords; if version < Es2015 { return feature; } feature |= FeatureFlag::ArrowFunctions | FeatureFlag::BlockScopedFunctions | FeatureFlag::BlockScoping | FeatureFlag::Classes | FeatureFlag::ComputedProperties | FeatureFlag::Destructuring | FeatureFlag::DuplicateKeys | FeatureFlag::ForOf | FeatureFlag::FunctionName | FeatureFlag::NewTarget | FeatureFlag::ObjectSuper | FeatureFlag::Parameters | FeatureFlag::Regenerator | FeatureFlag::ShorthandProperties | FeatureFlag::Spread | FeatureFlag::StickyRegex | FeatureFlag::TemplateLiterals | FeatureFlag::TypeOfSymbol | FeatureFlag::UnicodeRegex; if version < Es2016 { return feature; } feature |= FeatureFlag::ExponentiationOperator; if version < Es2017 { return feature; } // support `async` feature |= FeatureFlag::AsyncToGenerator; if version < Es2018 { return feature; } feature |= FeatureFlag::ObjectRestSpread | FeatureFlag::DotAllRegex | FeatureFlag::NamedCapturingGroupsRegex | FeatureFlag::UnicodePropertyRegex; if version < Es2019 { return feature; } feature |= FeatureFlag::OptionalCatchBinding; if version < Es2020 { return feature; } feature |= FeatureFlag::ExportNamespaceFrom | FeatureFlag::NullishCoalescing | FeatureFlag::OptionalChaining; if version < Es2021 { return feature; } feature |= FeatureFlag::LogicalAssignmentOperators; if version < Es2022 { return feature; } feature |= FeatureFlag::ClassProperties | FeatureFlag::ClassStaticBlock | FeatureFlag::PrivatePropertyInObject; feature }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/fixer.rs
Rust
use std::{hash::BuildHasherDefault, mem, ops::RangeFull}; use indexmap::IndexMap; use rustc_hash::FxHasher; use swc_common::{comments::Comments, util::take::Take, Span, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::stack_size::maybe_grow_default; use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; /// Fixes ast nodes before printing so semantics are preserved. /// /// You don't have to bother to create appropriate parenthesis. /// The pass will insert parenthesis as needed. In other words, it's /// okay to store `a * (b + c)` as `Bin { a * Bin { b + c } }`. pub fn fixer(comments: Option<&dyn Comments>) -> impl '_ + Pass + VisitMut { visit_mut_pass(Fixer { comments, ctx: Default::default(), span_map: Default::default(), in_for_stmt_head: Default::default(), in_opt_chain: Default::default(), remove_only: false, }) } pub fn paren_remover(comments: Option<&dyn Comments>) -> impl '_ + Pass + VisitMut { visit_mut_pass(Fixer { comments, ctx: Default::default(), span_map: Default::default(), in_for_stmt_head: Default::default(), in_opt_chain: Default::default(), remove_only: true, }) } struct Fixer<'a> { comments: Option<&'a dyn Comments>, ctx: Context, /// A hash map to preserve original span. /// /// Key is span of inner expression, and value is span of the paren /// expression. span_map: IndexMap<Span, Span, BuildHasherDefault<FxHasher>>, in_for_stmt_head: bool, in_opt_chain: bool, remove_only: bool, } #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] enum Context { #[default] Default, Callee { is_new: bool, }, /// Always treated as expr. (But number of comma-separated expression /// matters) /// /// - `foo((bar, x))` != `foo(bar, x)` /// - `var foo = (bar, x)` != `var foo = bar, x` /// - `[(foo, bar)]` != `[foo, bar]` ForcedExpr, /// Always treated as expr and comma does not matter. FreeExpr, } impl Fixer<'_> { fn wrap_callee(&mut self, e: &mut Expr) { match e { Expr::Lit(Lit::Num(..) | Lit::Str(..)) => (), Expr::Cond(..) | Expr::Class(..) | Expr::Bin(..) | Expr::Lit(..) | Expr::Unary(..) | Expr::Object(..) | Expr::Await(..) | Expr::Yield(..) => self.wrap(e), _ => (), } } } impl VisitMut for Fixer<'_> { noop_visit_mut_type!(); fn visit_mut_array_lit(&mut self, e: &mut ArrayLit) { let ctx = mem::replace(&mut self.ctx, Context::ForcedExpr); let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, false); e.elems.visit_mut_with(self); self.in_for_stmt_head = in_for_stmt_head; self.ctx = ctx; } fn visit_mut_arrow_expr(&mut self, node: &mut ArrowExpr) { let old = self.ctx; self.ctx = Context::Default; node.visit_mut_children_with(self); match &mut *node.body { BlockStmtOrExpr::Expr(e) if e.is_seq() => { self.wrap(e); } BlockStmtOrExpr::Expr(e) if e.is_assign() => { if let Expr::Assign(assign) = &**e { if let AssignTarget::Pat(..) = &assign.left { self.wrap(e); } } } _ => {} }; self.ctx = old; } fn visit_mut_assign_expr(&mut self, expr: &mut AssignExpr) { expr.left.visit_mut_with(self); let ctx = self.ctx; self.ctx = Context::FreeExpr; expr.right.visit_mut_with(self); self.ctx = ctx; fn rhs_need_paren(e: &Expr) -> bool { match e { Expr::Assign(e) => rhs_need_paren(&e.right), Expr::Seq(..) => true, _ => false, } } if rhs_need_paren(&expr.right) { self.wrap(&mut expr.right); } fn find_nearest_opt_chain_as_obj(e: &mut Expr) -> Option<&mut Expr> { match e { Expr::Member(MemberExpr { obj, .. }) => { if obj.is_opt_chain() { Some(obj) } else { find_nearest_opt_chain_as_obj(obj) } } _ => None, } } let lhs_expr = match &mut expr.left { AssignTarget::Simple(e) => Some(e), AssignTarget::Pat(..) => None, }; if let Some(e) = lhs_expr .and_then(|e| e.as_mut_member()) .and_then(|me| find_nearest_opt_chain_as_obj(&mut me.obj)) { self.wrap(e) }; } fn visit_mut_assign_pat(&mut self, node: &mut AssignPat) { let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, false); node.visit_mut_children_with(self); self.in_for_stmt_head = in_for_stmt_head; if let Expr::Seq(..) = &*node.right { self.wrap(&mut node.right); } } fn visit_mut_assign_pat_prop(&mut self, node: &mut AssignPatProp) { node.key.visit_mut_children_with(self); let old = self.ctx; self.ctx = Context::ForcedExpr; let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, false); node.value.visit_mut_with(self); self.in_for_stmt_head = in_for_stmt_head; self.ctx = old; } fn visit_mut_assign_target(&mut self, n: &mut AssignTarget) { n.visit_mut_children_with(self); match n { AssignTarget::Simple(a) => { if let SimpleAssignTarget::Paren(s) = a { *n = AssignTarget::try_from(s.expr.take()).unwrap(); } } AssignTarget::Pat(b) => { if let AssignTargetPat::Invalid(_) = b { *n = AssignTarget::Simple(SimpleAssignTarget::Invalid(Invalid { span: DUMMY_SP, })); } } } } fn visit_mut_await_expr(&mut self, expr: &mut AwaitExpr) { let old = self.ctx; self.ctx = Context::ForcedExpr; expr.arg.visit_mut_with(self); self.ctx = old; match &*expr.arg { Expr::Cond(..) | Expr::Assign(..) | Expr::Bin(..) | Expr::Yield(..) => { self.wrap(&mut expr.arg) } _ => {} } } fn visit_mut_bin_expr(&mut self, expr: &mut BinExpr) { expr.left.visit_mut_with(self); let ctx = self.ctx; self.ctx = Context::FreeExpr; expr.right.visit_mut_with(self); self.ctx = ctx; match expr.op { op!("||") | op!("&&") => match (&*expr.left, &*expr.right) { (Expr::Update(..), Expr::Call(..)) => { return; } (Expr::Update(..), Expr::Assign(..)) => { self.wrap(&mut expr.right); return; } _ => {} }, op!(">") | op!(">=") | op!("<") | op!("<=") => { if let (Expr::Update(..) | Expr::Lit(..), Expr::Update(..) | Expr::Lit(..)) = (&*expr.left, &*expr.right) { return; } } op!("**") => match &*expr.left { Expr::Unary(..) => { self.wrap(&mut expr.left); } Expr::Lit(Lit::Num(v)) if v.value.is_sign_negative() => { self.wrap(&mut expr.left); } _ => {} }, _ => {} } match &mut *expr.right { Expr::Assign(..) | Expr::Seq(..) | Expr::Yield(..) | Expr::Cond(..) | Expr::Arrow(..) => { self.wrap(&mut expr.right); } Expr::Bin(BinExpr { op: op_of_rhs, .. }) => { if *op_of_rhs == expr.op { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#precedence_and_associativity // `**` is the only right associative operator in js if !(expr.op.may_short_circuit() || expr.op == op!("**")) { self.wrap(&mut expr.right); } } else if op_of_rhs.precedence() <= expr.op.precedence() || (*op_of_rhs == op!("&&") && expr.op == op!("??")) { self.wrap(&mut expr.right); } } _ => {} }; match &mut *expr.left { Expr::Bin(BinExpr { op: op!("??"), .. }) if expr.op != op!("??") => { self.wrap(&mut expr.left); } // While simplifying, (1 + x) * Nan becomes `1 + x * Nan`. // But it should be `(1 + x) * Nan` Expr::Bin(BinExpr { op: op_of_lhs, .. }) => { if op_of_lhs.precedence() < expr.op.precedence() || (op_of_lhs.precedence() == expr.op.precedence() && expr.op == op!("**")) { self.wrap(&mut expr.left); } } Expr::Unary(UnaryExpr { op: op!("void"), .. }) if expr.op == op!("==") || expr.op == op!("===") || expr.op == op!("!=") || expr.op == op!("!==") => {} Expr::Seq(..) | Expr::Unary(UnaryExpr { op: op!("delete"), .. }) | Expr::Unary(UnaryExpr { op: op!("void"), .. }) | Expr::Yield(..) | Expr::Cond(..) | Expr::Assign(..) | Expr::Arrow(..) => { self.wrap(&mut expr.left); } Expr::Object(..) if expr.op == op!("instanceof") || expr.op == op!("==") || expr.op == op!("===") || expr.op == op!("!=") || expr.op == op!("!==") => { self.wrap(&mut expr.left) } _ => {} } if let op!("??") = expr.op { match &*expr.left { Expr::Bin(BinExpr { op, .. }) if *op != op!("??") => { self.wrap(&mut expr.left); } _ => (), } } } fn visit_mut_block_stmt(&mut self, n: &mut BlockStmt) { let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, false); n.visit_mut_children_with(self); self.in_for_stmt_head = in_for_stmt_head; } fn visit_mut_block_stmt_or_expr(&mut self, body: &mut BlockStmtOrExpr) { body.visit_mut_children_with(self); match body { BlockStmtOrExpr::Expr(expr) if expr.is_object() => { self.wrap(expr); } _ => {} } } fn visit_mut_call_expr(&mut self, node: &mut CallExpr) { let ctx = mem::replace(&mut self.ctx, Context::Callee { is_new: false }); node.callee.visit_mut_with(self); if let Callee::Expr(e) = &mut node.callee { match &**e { Expr::OptChain(_) if !self.in_opt_chain => self.wrap(e), _ => self.wrap_callee(e), } } self.ctx = Context::ForcedExpr; node.args.visit_mut_with(self); self.ctx = ctx; } fn visit_mut_class(&mut self, node: &mut Class) { let ctx = mem::replace(&mut self.ctx, Context::Default); node.super_class.visit_mut_with(self); let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, false); node.body.visit_mut_with(self); self.in_for_stmt_head = in_for_stmt_head; match &mut node.super_class { Some(e) if e.is_seq() || e.is_await_expr() || e.is_yield_expr() || e.is_bin() || e.is_assign() || e.is_cond() || e.is_unary() => { self.wrap(e) } _ => {} }; self.ctx = ctx; node.body.retain(|m| !matches!(m, ClassMember::Empty(..))); } fn visit_mut_computed_prop_name(&mut self, name: &mut ComputedPropName) { let ctx = self.ctx; self.ctx = Context::FreeExpr; name.visit_mut_children_with(self); self.ctx = ctx; } fn visit_mut_cond_expr(&mut self, expr: &mut CondExpr) { expr.test.visit_mut_with(self); let ctx = self.ctx; self.ctx = Context::FreeExpr; expr.cons.visit_mut_with(self); expr.alt.visit_mut_with(self); self.ctx = ctx; } fn visit_mut_export_default_expr(&mut self, node: &mut ExportDefaultExpr) { let old = self.ctx; self.ctx = Context::Default; node.visit_mut_children_with(self); match &mut *node.expr { Expr::Arrow(..) | Expr::Seq(..) => self.wrap(&mut node.expr), Expr::Fn(FnExpr { ident: Some(_), .. }) | Expr::Class(ClassExpr { ident: Some(_), .. }) => self.wrap(&mut node.expr), _ => {} }; self.ctx = old; } fn visit_mut_expr(&mut self, e: &mut Expr) { let ctx = self.ctx; if ctx == Context::Default { match e { // might have a child expr in start of stmt Expr::OptChain(_) | Expr::Member(_) | Expr::Bin(_) | Expr::Assign(_) | Expr::Seq(_) | Expr::Cond(_) | Expr::TaggedTpl(_) | Expr::Update(UpdateExpr { prefix: false, .. }) => {} _ => self.ctx = Context::FreeExpr, } } self.unwrap_expr(e); maybe_grow_default(|| e.visit_mut_children_with(self)); self.ctx = ctx; self.wrap_with_paren_if_required(e) } fn visit_mut_expr_or_spread(&mut self, e: &mut ExprOrSpread) { e.visit_mut_children_with(self); if e.spread.is_none() { if let Expr::Yield(..) = *e.expr { self.wrap(&mut e.expr); } } } fn visit_mut_expr_stmt(&mut self, s: &mut ExprStmt) { let old = self.ctx; self.ctx = Context::Default; s.expr.visit_mut_with(self); self.ctx = old; self.handle_expr_stmt(&mut s.expr); } fn visit_mut_for_head(&mut self, n: &mut ForHead) { let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, true); n.visit_mut_children_with(self); self.in_for_stmt_head = in_for_stmt_head; } fn visit_mut_for_of_stmt(&mut self, s: &mut ForOfStmt) { s.visit_mut_children_with(self); if !s.is_await { match &s.left { ForHead::Pat(p) if match &**p { Pat::Ident(BindingIdent { id: Ident { sym, .. }, .. }) => &**sym == "async", _ => false, } => { let expr: Pat = p.clone().expect_ident().into(); s.left = ForHead::Pat(expr.into()); } _ => (), } if let ForHead::Pat(e) = &mut s.left { if let Pat::Expr(expr) = &mut **e { if expr.is_ident_ref_to("async") { self.wrap(&mut *expr); } } } } if let Expr::Seq(..) | Expr::Await(..) = &*s.right { self.wrap(&mut s.right) } } fn visit_mut_for_stmt(&mut self, n: &mut ForStmt) { let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, true); n.init.visit_mut_with(self); self.in_for_stmt_head = in_for_stmt_head; n.test.visit_mut_with(self); n.update.visit_mut_with(self); n.body.visit_mut_with(self); } fn visit_mut_if_stmt(&mut self, node: &mut IfStmt) { node.visit_mut_children_with(self); if will_eat_else_token(&node.cons) { node.cons = Box::new( BlockStmt { span: node.cons.span(), stmts: vec![*node.cons.take()], ..Default::default() } .into(), ); } } fn visit_mut_key_value_pat_prop(&mut self, node: &mut KeyValuePatProp) { let old = self.ctx; self.ctx = Context::ForcedExpr; node.key.visit_mut_with(self); self.ctx = old; node.value.visit_mut_with(self); } fn visit_mut_key_value_prop(&mut self, prop: &mut KeyValueProp) { prop.visit_mut_children_with(self); if let Expr::Seq(..) = *prop.value { self.wrap(&mut prop.value) } } fn visit_mut_member_expr(&mut self, n: &mut MemberExpr) { n.visit_mut_children_with(self); match *n.obj { Expr::Object(..) if self.ctx == Context::ForcedExpr => {} Expr::Fn(..) | Expr::Cond(..) | Expr::Unary(..) | Expr::Seq(..) | Expr::Update(..) | Expr::Bin(..) | Expr::Object(..) | Expr::Assign(..) | Expr::Arrow(..) | Expr::Class(..) | Expr::Yield(..) | Expr::Await(..) | Expr::New(NewExpr { args: None, .. }) => { self.wrap(&mut n.obj); } Expr::Call(..) if self.ctx == Context::Callee { is_new: true } => { self.wrap(&mut n.obj); } Expr::OptChain(..) if !self.in_opt_chain => { self.wrap(&mut n.obj); } _ => {} } } fn visit_mut_module(&mut self, n: &mut Module) { debug_assert!(self.span_map.is_empty()); self.span_map.clear(); n.visit_mut_children_with(self); if let Some(c) = self.comments { for (to, from) in self.span_map.drain(RangeFull).rev() { c.move_leading(from.lo, to.lo); c.move_trailing(from.hi, to.hi); } } } fn visit_mut_new_expr(&mut self, node: &mut NewExpr) { let ctx = mem::replace(&mut self.ctx, Context::ForcedExpr); node.args.visit_mut_with(self); self.ctx = Context::Callee { is_new: true }; node.callee.visit_mut_with(self); match *node.callee { Expr::Call(..) | Expr::Await(..) | Expr::Yield(..) | Expr::Bin(..) | Expr::Assign(..) | Expr::Seq(..) | Expr::Unary(..) | Expr::Lit(..) => self.wrap(&mut node.callee), _ => {} } self.ctx = ctx; } fn visit_mut_opt_call(&mut self, node: &mut OptCall) { let ctx = mem::replace(&mut self.ctx, Context::Callee { is_new: false }); let in_opt_chain = mem::replace(&mut self.in_opt_chain, true); node.callee.visit_mut_with(self); self.wrap_callee(&mut node.callee); self.in_opt_chain = in_opt_chain; self.ctx = Context::ForcedExpr; node.args.visit_mut_with(self); self.ctx = ctx; } fn visit_mut_opt_chain_base(&mut self, n: &mut OptChainBase) { if !n.is_member() { n.visit_mut_children_with(self); return; } let in_opt_chain = mem::replace(&mut self.in_opt_chain, true); n.visit_mut_children_with(self); self.in_opt_chain = in_opt_chain; } fn visit_mut_param(&mut self, node: &mut Param) { let old = self.ctx; self.ctx = Context::ForcedExpr; node.visit_mut_children_with(self); self.ctx = old; } fn visit_mut_prop_name(&mut self, name: &mut PropName) { name.visit_mut_children_with(self); match name { PropName::Computed(c) if c.expr.is_seq() => { self.wrap(&mut c.expr); } _ => {} } } fn visit_mut_script(&mut self, n: &mut Script) { debug_assert!(self.span_map.is_empty()); self.span_map.clear(); n.visit_mut_children_with(self); if let Some(c) = self.comments { for (to, from) in self.span_map.drain(RangeFull).rev() { c.move_leading(from.lo, to.lo); c.move_trailing(from.hi, to.hi); } } } fn visit_mut_seq_expr(&mut self, seq: &mut SeqExpr) { if seq.exprs.len() > 1 { seq.exprs[0].visit_mut_with(self); let ctx = self.ctx; self.ctx = Context::FreeExpr; for expr in seq.exprs.iter_mut().skip(1) { expr.visit_mut_with(self) } self.ctx = ctx; } else { seq.exprs.visit_mut_children_with(self) } } fn visit_mut_spread_element(&mut self, e: &mut SpreadElement) { let old = self.ctx; self.ctx = Context::ForcedExpr; e.visit_mut_children_with(self); self.ctx = old; } fn visit_mut_stmt(&mut self, s: &mut Stmt) { let old = self.ctx; // only ExprStmt would have unparented expr, // which would be handled in its own visit function self.ctx = Context::FreeExpr; s.visit_mut_children_with(self); self.ctx = old; } fn visit_mut_tagged_tpl(&mut self, e: &mut TaggedTpl) { e.visit_mut_children_with(self); match &*e.tag { Expr::Object(..) if self.ctx == Context::Default => { self.wrap(&mut e.tag); } Expr::OptChain(..) | Expr::Arrow(..) | Expr::Cond(..) | Expr::Bin(..) | Expr::Seq(..) | Expr::Fn(..) | Expr::Assign(..) | Expr::Unary(..) => { self.wrap(&mut e.tag); } _ => {} } } fn visit_mut_unary_expr(&mut self, n: &mut UnaryExpr) { let old = self.ctx; self.ctx = Context::FreeExpr; n.visit_mut_children_with(self); self.ctx = old; match &*n.arg { Expr::Bin(BinExpr { op: op!("/") | op!("*"), left, right, .. }) if n.op == op!(unary, "-") && match (&**left, &**right) { (Expr::Lit(Lit::Num(l)), Expr::Lit(Lit::Num(..))) => { !l.value.is_sign_negative() } _ => false, } => {} Expr::Assign(..) | Expr::Bin(..) | Expr::Seq(..) | Expr::Cond(..) | Expr::Arrow(..) | Expr::Yield(..) => self.wrap(&mut n.arg), _ => {} } } fn visit_mut_var_declarator(&mut self, node: &mut VarDeclarator) { node.name.visit_mut_children_with(self); let old = self.ctx; self.ctx = Context::ForcedExpr; node.init.visit_mut_with(self); self.ctx = old; } fn visit_mut_yield_expr(&mut self, expr: &mut YieldExpr) { let old = self.ctx; self.ctx = Context::ForcedExpr; expr.arg.visit_mut_with(self); self.ctx = old; } fn visit_mut_object_lit(&mut self, n: &mut ObjectLit) { let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, false); n.visit_mut_children_with(self); self.in_for_stmt_head = in_for_stmt_head; } fn visit_mut_params(&mut self, n: &mut Vec<Param>) { let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, false); n.visit_mut_children_with(self); self.in_for_stmt_head = in_for_stmt_head; } // only used in ArrowExpr fn visit_mut_pats(&mut self, n: &mut Vec<Pat>) { let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, false); n.visit_mut_children_with(self); self.in_for_stmt_head = in_for_stmt_head; } fn visit_mut_expr_or_spreads(&mut self, n: &mut Vec<ExprOrSpread>) { let in_for_stmt_head = mem::replace(&mut self.in_for_stmt_head, false); n.visit_mut_children_with(self); self.in_for_stmt_head = in_for_stmt_head; } } impl Fixer<'_> { fn wrap_with_paren_if_required(&mut self, e: &mut Expr) { let mut has_padding_value = false; match e { Expr::Bin(BinExpr { op: op!("in"), .. }) if self.in_for_stmt_head => { // TODO: // if the in expression is in a parentheses, we should not wrap it with a // parentheses again. But the parentheses is added later, // so we don't have enough information to detect it at this moment. // Example: // for(var a = 1 + (2 || b in c) in {}); // |~~~~~~~~~~~| // this parentheses is removed by unwrap_expr and added again later self.wrap(e); } Expr::Bin(BinExpr { left, .. }) if self.ctx == Context::Default && matches!(&**left, Expr::Object(..) | Expr::Fn(..) | Expr::Class(..)) => { self.wrap(left); } // Flatten seq expr Expr::Seq(SeqExpr { span, exprs }) => { let len = exprs .iter() .map(|expr| match **expr { Expr::Paren(ParenExpr { ref expr, .. }) => { if let Expr::Seq(SeqExpr { exprs, .. }) = expr.as_ref() { exprs.len() } else { 1 } } Expr::Seq(SeqExpr { ref exprs, .. }) => exprs.len(), _ => 1, }) .sum(); let exprs_len = exprs.len(); // don't has child seq let mut exprs = if len == exprs_len { let mut exprs = exprs .iter_mut() .enumerate() .filter_map(|(i, e)| { let is_last = i + 1 == exprs_len; if is_last { Some(e.take()) } else { ignore_return_value(e.take(), &mut has_padding_value) } }) .collect::<Vec<_>>(); if exprs.len() == 1 { *e = *exprs.pop().unwrap(); return; } ignore_padding_value(exprs) } else { let mut buf = Vec::with_capacity(len); for (i, expr) in exprs.iter_mut().enumerate() { let is_last = i + 1 == exprs_len; match &mut **expr { Expr::Seq(SeqExpr { exprs, .. }) => { let exprs = exprs.take(); if !is_last { buf.extend(exprs.into_iter().filter_map(|expr| { ignore_return_value(expr, &mut has_padding_value) })); } else { let exprs_len = exprs.len(); for (i, expr) in exprs.into_iter().enumerate() { let is_last = i + 1 == exprs_len; if is_last { buf.push(expr); } else { buf.extend(ignore_return_value( expr, &mut has_padding_value, )); } } } } _ => { if is_last { buf.push(expr.take()); } else { buf.extend(ignore_return_value( expr.take(), &mut has_padding_value, )); } } } } if buf.len() == 1 { *e = *buf.pop().unwrap(); return; } ignore_padding_value(buf) }; if self.ctx == Context::Default { if let Some(expr) = exprs.first_mut() { match &mut **expr { Expr::Call(CallExpr { callee: Callee::Expr(callee_expr), .. }) if callee_expr.is_fn_expr() => self.wrap(callee_expr), _ => (), } } } let mut expr = SeqExpr { span: *span, exprs }.into(); if let Context::ForcedExpr = self.ctx { self.wrap(&mut expr); }; *e = expr; } Expr::Cond(expr) => { match &mut *expr.test { Expr::Seq(..) | Expr::Assign(..) | Expr::Cond(..) | Expr::Arrow(..) | Expr::Yield(..) => self.wrap(&mut expr.test), Expr::Object(..) | Expr::Fn(..) | Expr::Class(..) => { if self.ctx == Context::Default { self.wrap(&mut expr.test) } } _ => {} }; if let Expr::Seq(..) = *expr.cons { self.wrap(&mut expr.cons) }; if let Expr::Seq(..) = *expr.alt { self.wrap(&mut expr.alt) }; if let Context::Callee { is_new: true } = self.ctx { self.wrap(e) } } Expr::Call(CallExpr { callee: Callee::Expr(callee), .. }) if callee.is_seq() || callee.is_arrow() || callee.is_await_expr() || callee.is_assign() => { self.wrap(callee); } Expr::OptChain(OptChainExpr { base, .. }) => match &mut **base { OptChainBase::Call(OptCall { callee, .. }) if callee.is_seq() || callee.is_arrow() || callee.is_await_expr() || callee.is_assign() => { self.wrap(callee); } OptChainBase::Call(OptCall { callee, .. }) if callee.is_fn_expr() => match self.ctx { Context::ForcedExpr | Context::FreeExpr => {} Context::Callee { is_new: true } => self.wrap(e), _ => self.wrap(callee), }, _ => {} }, // Function expression cannot start with `function` Expr::Call(CallExpr { callee: Callee::Expr(callee), .. }) if callee.is_fn_expr() => match self.ctx { Context::ForcedExpr | Context::FreeExpr => {} Context::Callee { is_new: true } => self.wrap(e), _ => self.wrap(callee), }, Expr::Member(MemberExpr { obj, .. }) => match &**obj { Expr::Lit(Lit::Num(num)) if num.value.signum() == -1. => { self.wrap(obj); } _ => {} }, _ => {} } } /// Wrap with a paren. fn wrap(&mut self, e: &mut Expr) { if self.remove_only { return; } let mut span = e.span(); if let Some(new_span) = self.span_map.shift_remove(&span) { span = new_span; } if span.is_pure() { span = DUMMY_SP; } let expr = Box::new(e.take()); *e = ParenExpr { expr, span }.into(); } /// Removes paren fn unwrap_expr(&mut self, e: &mut Expr) { loop { match e { Expr::Seq(SeqExpr { exprs, .. }) if exprs.len() == 1 => { *e = *exprs[0].take(); } Expr::Paren(ParenExpr { span: paren_span, expr, .. }) => { let expr_span = expr.span(); let paren_span = *paren_span; *e = *expr.take(); self.span_map.insert(expr_span, paren_span); } _ => return, } } } fn handle_expr_stmt(&mut self, expr: &mut Expr) { match expr { // It's important for arrow pass to work properly. Expr::Object(..) | Expr::Class(..) | Expr::Fn(..) => self.wrap(expr), // ({ a } = foo) Expr::Assign(AssignExpr { left: AssignTarget::Pat(left), .. }) if left.is_object() => self.wrap(expr), Expr::Seq(SeqExpr { exprs, .. }) => { debug_assert!( exprs.len() != 1, "SeqExpr should be unwrapped if exprs.len() == 1, but length is 1" ); let len = exprs.len(); exprs.iter_mut().enumerate().for_each(|(i, expr)| { let is_last = len == i + 1; if !is_last { self.handle_expr_stmt(expr); } }); } _ => {} } } } fn ignore_return_value(expr: Box<Expr>, has_padding_value: &mut bool) -> Option<Box<Expr>> { match *expr { Expr::Fn(..) | Expr::Arrow(..) | Expr::Lit(..) => { if *has_padding_value { None } else { *has_padding_value = true; Some(expr) } } Expr::Seq(SeqExpr { span, exprs }) => { let len = exprs.len(); let mut exprs: Vec<_> = exprs .into_iter() .enumerate() .filter_map(|(i, expr)| { if i + 1 == len { Some(expr) } else { ignore_return_value(expr, has_padding_value) } }) .collect(); match exprs.len() { 0 | 1 => exprs.pop(), _ => Some(SeqExpr { span, exprs }.into()), } } Expr::Unary(UnaryExpr { op: op!("void"), arg, .. }) => ignore_return_value(arg, has_padding_value), _ => Some(expr), } } // at least 3 element in seq, which means we can safely // remove that padding, if not at last position #[allow(clippy::vec_box)] fn ignore_padding_value(exprs: Vec<Box<Expr>>) -> Vec<Box<Expr>> { let len = exprs.len(); if len > 2 { exprs .into_iter() .enumerate() .filter_map(|(i, e)| match e.as_ref() { Expr::Fn(..) | Expr::Arrow(..) | Expr::Lit(..) if i + 1 != len => None, _ => Some(e), }) .collect() } else { exprs } } fn will_eat_else_token(s: &Stmt) -> bool { match s { Stmt::If(s) => match &s.alt { Some(alt) => will_eat_else_token(alt), None => true, }, // Ends with `}`. Stmt::Block(..) => false, Stmt::Labeled(s) => will_eat_else_token(&s.body), Stmt::While(s) => will_eat_else_token(&s.body), Stmt::For(s) => will_eat_else_token(&s.body), Stmt::ForIn(s) => will_eat_else_token(&s.body), Stmt::ForOf(s) => will_eat_else_token(&s.body), _ => false, } } #[cfg(test)] mod tests { use swc_ecma_ast::noop_pass; fn run_test(from: &str, to: &str) { crate::tests::test_transform( Default::default(), // test_transform has alreay included fixer |_| noop_pass(), from, to, true, Default::default, ); } macro_rules! test_fixer { ($name:ident, $from:literal, $to:literal) => { #[test] fn $name() { run_test($from, $to); } }; } macro_rules! identical { ($name:ident, $src:literal) => { test_fixer!($name, $src, $src); }; } identical!(fn_expr_position, r#"foo(function(){}())"#); identical!(fn_decl, r#"function foo(){}"#); identical!(iife, r#"(function(){})()"#); identical!(paren_seq_arg, "foo(( _temp = _this = init(), _temp));"); identical!( regression_01, "_set(_get_prototype_of(Obj.prototype), _ref = proper.prop, (_superRef = \ +_get(_get_prototype_of(Obj.prototype), _ref, this)) + 1, this, true), _superRef;" ); identical!( regression_02, "var obj = (_obj = {}, _define_property(_obj, 'first', 'first'), _define_property(_obj, \ 'second', 'second'), _obj);" ); identical!( regression_03, "_iteratorNormalCompletion = (_step = _iterator.next()).done" ); identical!( regression_04, "var _tmp; const _ref = {}, { c =( _tmp = {}, d = _extends({}, _tmp), _tmp) } = _ref;" ); identical!( regression_05, "for (var _iterator = arr[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step \ = _iterator.next()).done); _iteratorNormalCompletion = true) { i = _step.value; }" ); identical!( regression_06, " var _tmp; const { [( _tmp = {}, d = _extends({}, _tmp), _tmp)]: c } = _ref; " ); identical!( regression_07, "( _temp = super(), _initialize(this), _temp).method();" ); identical!(regression_08, "exports.bar = exports.default = void 0;"); identical!(regression_09, "({x} = { x: 1 });"); identical!(regression_10, "({x} = { x: 1 }), exports.x = x;"); identical!(regression_11, "(void 0).foo();"); identical!(regression_12, "(function(){})()"); identical!(regression_13, "a || (a = 1);"); identical!(issue_192, "a === true && (a = true)"); identical!(issue_199, "(i - 1).toString()"); identical!( issue_201_01, "outer = { inner: (_obj = {}, _define_property(_obj, ns.EXPORT1, true), _define_property(_obj, \ ns.EXPORT2, true), _obj) };" ); identical!(issue_207, "a => ({x: 'xxx', y: {a}});"); test_fixer!( fixer_01, "var a, b, c, d, e, f; ((a, b), (c())) + ((d, e), (f())); ", "var a, b, c, d, e, f; (a, b, c()) + (d, e, f())" ); test_fixer!(fixer_02, "(b, c), d;", "b, c, d;"); test_fixer!(fixer_03, "((a, b), (c && d)) && e;", "(a, b, c && d) && e;"); test_fixer!(fixer_04, "for ((a, b), c;;) ;", "for(a, b, c;;);"); test_fixer!( fixer_05, "var a, b, c = (1), d, e, f = (2); ((a, b), c) + ((d, e), f);", "var a, b, c = 1, d, e, f = 2; (a, b, c) + (d, e, f);" ); test_fixer!( fixer_06, "var a, b, c, d; a = ((b, c), d);", "var a, b, c, d; a = (b, c, d);" ); test_fixer!( fixer_07, "a => ((b, c) => ((a, b), c));", "(a)=>(b, c)=>(a, b, c);" ); test_fixer!(fixer_08, "typeof (((1), a), (2));", "typeof (a, 2)"); test_fixer!( fixer_09, "(((a, b), c), d) ? e : f;", "(a, b, c, d) ? e : f;" ); test_fixer!( fixer_10, " function a() { return (((void (1)), (void (2))), a), (void (3)); } ", " function a() { return a, void 3; } " ); test_fixer!(fixer_11, "c && ((((2), (3)), d), b);", "c && (d, b)"); test_fixer!(fixer_12, "(((a, b), c), d) + e;", "(a, b, c, d) + e;"); test_fixer!(fixer_13, "delete (((1), a), (2));", "delete (a, 2)"); test_fixer!(fixer_14, "(1, 2, a)", "1, a"); identical!(issue_231, "'' + (truthy && '?') + truthy;"); identical!(issue_252, "!!(a && b);"); identical!(issue_255, "b < 0 ? (t = b, b = 1) : (t = -b, b = 0);"); identical!( issue_266_1, "'Q' + +x1 + ',' + +y1 + ',' + (this._x1 = +x) + ',' + (this._y1 = +y);" ); test_fixer!( issue_266_2, "'Q' + (+x1) + ',' + (+y1) + ',' + (this._x1 = +x) + ',' + (this._y1 = +y);", "'Q' + +x1 + ',' + +y1 + ',' + (this._x1 = +x) + ',' + (this._y1 = +y);" ); identical!( issue_280, "e.hasOwnProperty(a) && (t = e[a] ? this[a] = t(n) : 'target' === a ? this.target = r : \ this[a] = n[a]);" ); identical!( issue_282, "!(A = [], B = (function () { return classNames; }).apply(exports, A), B !== undefined && \ (module.exports = B));" ); identical!( issue_286, "var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: core.version, mode: __webpack_require__(39) ? 'pure' : 'global', copyright: '© 2018 Denis Pushkarev (zloirock.ru)' });" ); identical!( issue_293_1, "for (var e in a) a.hasOwnProperty(e) && ((b = a[e]) ? this[e] = b(c) : 'target' === e ? \ this.target = d : this[e] = c[e]);" ); identical!( issue_293_2, "(a = rb ? zb(a, c) : Ab(a, c)) ? (b = nb.getPooled(ub.beforeInput, b, c, d), b.data = a, \ Ra(b)) : b = null;" ); identical!(member_object_lit, "({}).foo"); identical!(member_cond_expr, "(foo ? 1 : 2).foo"); identical!(member_new_exp_1, "(new Foo).foo"); identical!(member_new_exp_2, "new ctor().property"); identical!(member_tagged_tpl, "tag``.foo"); identical!(member_arrow_expr_1, "(a => a).foo"); identical!(member_arrow_expr_2, "((a) => a).foo"); identical!(member_class, "(class Foo{}).foo"); identical!(member_yield, "function* foo(){ (yield bar).baz }"); identical!(member_await, "async function foo(){ (await bar).baz }"); identical!(bin_yield_expr_1, "function* foo(){ (yield foo) && bar }"); identical!(bin_yield_expr_2, "function* foo(){ bar && (yield foo) }"); identical!(bin_seq_expr_1, "(foo(), op) || (seq(), foo)"); identical!(bin_seq_expr_2, "(foo, op) || (seq, foo)"); identical!(cond_object_1, "let foo = {} ? 1 : 2;"); identical!(cond_object_2, "({}) ? 1 : 2;"); identical!(cond_in_cond, "(foo ? 1 : 2) ? 3 : 4"); identical!(arrow_in_cond, "(() => {}) ? 3 : 4"); identical!(unary_cond_arg, "void (foo ? 1 : 2)"); identical!(unary_arrow_arg, "void ((foo) => foo)"); identical!(unary_yield_arg, "(function* foo() { void (yield foo); })()"); identical!( issue_365, "const foo = (() => { return 1 })();" ); identical!( issue_382_1, "const myFilter = (arr, filter) => arr.filter(((x) => x) || filter);" ); identical!( issue_382_2, "const myFilter = (arr, filter) => arr.filter(filter || ((x) => x));" ); identical!(issue_418, "const a = 1 - (1 - 1)"); test_fixer!( issue_439, "() => { return ( Promise.resolve('foo') // Interfering comment .then(() => {}) ); };", "() => { return Promise.resolve('foo') // Interfering comment .then(() => {}) ; };" ); test_fixer!( issue_451, "const instance = new ( function() { function klass(opts) { this.options = opts; } return (Object.assign(klass.prototype, { method() {} }), klass); }() )({ foo: 1 });", "const instance = new (function() { function klass(opts) { this.options = opts; } return Object.assign(klass.prototype, { method () { } }), klass; }())({ foo: 1 });" ); test_fixer!(void_and_bin, "(void 0) * 2", "(void 0) * 2"); test_fixer!(new_cond, "new (a ? B : C)()", "new (a ? B : C)()"); identical!(issue_931, "new (eval('Date'))();"); identical!(issue_1002, "new (P || (P = Promise))"); identical!( issue_1050, " (a) => (set) => (elemE(a, set) ? removeE : insertE)(a)(set) " ); identical!( deno_001, " var Status; (function init(Status1) { })(Status || (Status = { })); " ); identical!(issue_1093, "const x = (fnA || fnB)();"); identical!( issue_1133, "async function foo() { const item = await (data === null || data === void 0 ? void 0 : data.foo()); }" ); identical!(deno_8722, "console.log((true || false) ?? true);"); identical!( deno_8597, " biasInitializer = new (_a = class CustomInit extends Initializer {})(); " ); test_fixer!( minifier_001, "var bitsLength = 3, bitsOffset = 3, what = (len = 0)", "var bitsLength = 3, bitsOffset = 3, what = len = 0" ); test_fixer!(minifier_002, "!(function(){})()", "!function(){}()"); identical!( issue_1397, "const main = async () => await (await server)()" ); identical!(deno_9810, "await (bar = Promise.resolve(2));"); identical!(issue_1493, "('a' ?? 'b') || ''"); identical!(call_seq, "let x = ({}, () => 2)();"); test_fixer!( call_seq_with_padding, "let x = ({}, (1, 2), () => 2)();", "let x = ({}, () => 2)();" ); identical!( param_seq, "function t(x = ({}, 2)) { return x; }" ); identical!( yield_expr_cond, "function *test1(foo) { return (yield foo) ? 'bar' : 'baz'; }" ); identical!( deno_10487_1, "var generator = class MultiVector extends (options.baseType||Float32Array) {}" ); identical!( deno_10487_2, "class MultiVector extends (options.baseType||Float32Array) {}" ); identical!( extends_nullish_coalescing, "class Foo extends (Bar ?? class{}) {}" ); identical!(extends_assign, "class Foo extends (Bar = class{}) {}"); identical!( extends_logical_or_assin, "class Foo extends (Bar ||= class{}) {}" ); identical!( extends_logical_and_assin, "class Foo extends (Bar &&= class{}) {}" ); identical!( extends_logical_nullish_assin, "class Foo extends (Bar ??= class{}) {}" ); identical!(extends_cond, "class Foo extends (true ? Bar : Baz) {}"); identical!( extends_await_yield, " async function* func() { class A extends (await p) {} class B extends (yield p) {} } " ); identical!(deno_10668_1, "console.log(null ?? (undefined && true))"); identical!(deno_10668_2, "console.log(null && (undefined ?? true))"); identical!(minifier_003, "(four ** one) ** two"); identical!(minifier_004, "(void 0)(0)"); identical!(issue_1781, "const n = ~~(Math.PI * 10)"); identical!(issue_1789, "+(+1 / 4)"); identical!(new_member_call_1, "new (getObj()).ctor()"); test_fixer!( new_member_call_2, "new (getObj().ctor)()", "new (getObj()).ctor()" ); test_fixer!( new_member_call_3, "new (x.getObj().ctor)()", "new (x.getObj()).ctor()" ); identical!(new_call, "new (getCtor())"); test_fixer!(new_member_1, "new obj.ctor()", "new obj.ctor()"); test_fixer!(new_member_2, "new (obj.ctor)", "new obj.ctor"); identical!( new_await_1, "async function foo() { new (await getServerImpl())(options) }" ); test_fixer!(minifier_005, "-(1/0)", "-1/0"); test_fixer!(minifier_006, "-('s'/'b')", "-('s'/'b')"); test_fixer!(minifier_007, "(void 0) === value", "void 0 === value"); test_fixer!(minifier_008, "(size--) && (b = (c))", "size-- && (b = c)"); test_fixer!( minifier_009, "(--remaining) || deferred.resolveWith()", "--remaining || deferred.resolveWith()" ); test_fixer!(minifier_010, "(--remaining) + ''", "--remaining + ''"); identical!( if_stmt_001, " export const obj = { each: function (obj, callback, args) { var i = 0, length = obj.length, isArray = isArraylike(obj); if (args) { if (isArray) for (; i < length && !1 !== callback.apply(obj[i], args); i++); else for (i in obj) if (!1 === callback.apply(obj[i], args)) break } else if (isArray) for (; i < length && !1 !== callback.call(obj[i], i, obj[i]); i++); else for (i in obj) if (!1 === callback.call(obj[i], i, obj[i])) break; return obj } }; " ); identical!( issue_2155, " async function main() { let promise; await (promise || (promise = Promise.resolve('this is a string'))); } " ); identical!(issue_2163_1, "() => ({foo} = bar());"); identical!(issue_2163_2, "() => ([foo] = bar());"); identical!(issue_2191, "(-1) ** h"); identical!( minifier_011, " function ItemsList() { var _ref; var _temp, _this, _ret; _class_call_check(this, ItemsList); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possible_constructor_return(this, (_ref = \ ItemsList.__proto__ || Object.getPrototypeOf(ItemsList)).call.apply(_ref, \ [this].concat(args))), _this), _this.storeHighlightedItemReference = function \ (highlightedItem) { _this.props.onHighlightedItemChange(highlightedItem === null ? null : \ highlightedItem.item); }, _temp), _possible_constructor_return(_this, _ret); } " ); identical!( minifier_012, " function ItemsList() { for(var _ref, _temp, _this, _len = arguments.length, args = Array(_len), _key = 0; \ _key < _len; _key++)args[_key] = arguments[_key]; return _possible_constructor_return(_this, (_temp = (_this = \ _possible_constructor_return(this, (_ref = ItemsList.__proto__ || \ Object.getPrototypeOf(ItemsList)).call.apply(_ref, [ this ].concat(args))), _this), _this.storeHighlightedItemReference = \ function(highlightedItem) { _this.props.onHighlightedItemChange(null === highlightedItem ? null : \ highlightedItem.item); }, _temp)); } " ); test_fixer!(issue_2550_1, "(1 && { a: 1 })", "1 && { a:1 }"); identical!(issue_2550_2, "({ isNewPrefsActive }) && { a: 1 }"); test_fixer!(paren_of_bin_left_1, "({} && 1)", "({}) && 1"); identical!(paren_of_bin_left_2, "({}) && 1"); test_fixer!( paren_of_bin_left_3, "(function () {} || 2)", "(function () {}) || 2" ); identical!(paren_of_bin_left_4, "(function () {}) || 2"); test_fixer!(paren_of_bin_left_5, "(class{} ?? 3)", "(class{}) ?? 3"); identical!(paren_of_bin_left_6, "(class{}) ?? 3"); identical!(issue_4761, "x = { ...(0, foo) }"); identical!(issue_4914, "(a ?? b)?.()"); identical!(issue_5109_1, "(0, b)?.()"); identical!(issue_5109_2, "1 + (0, b)?.()"); identical!(issue_5109_3, "(0, a)() ? undefined : (0, b)?.()"); identical!( issue_5313, " async function* foo() { (await a)(); (yield b)(); } " ); identical!(issue_5417, "console.log(a ?? b ?? c)"); identical!(bin_and_unary, "console.log(a++ && b--)"); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/helpers/_apply_decorated_descriptor.js
JavaScript
function _apply_decorated_descriptor(target, property, decorators, descriptor, context) { var desc = {}; Object["ke" + "ys"](descriptor).forEach(function(key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ("value" in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function(desc, decorator) { return decorator ? decorator(target, property, desc) || desc : desc; }, desc); var hasAccessor = Object.prototype.hasOwnProperty.call(desc, "get") || Object.prototype.hasOwnProperty.call(desc, "set"); if (context && desc.initializer !== void 0 && !hasAccessor) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (hasAccessor) { delete desc.writable; delete desc.initializer; delete desc.value; } if (desc.initializer === void 0) { Object["define" + "Property"](target, property, desc); desc = null; } return desc; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/helpers/_apply_decs_2203_r.js
JavaScript
/* @minVersion 7.20.0 */ /** Enums are used in this file, but not assigned to vars to avoid non-hoistable values CONSTRUCTOR = 0; PUBLIC = 1; PRIVATE = 2; FIELD = 0; ACCESSOR = 1; METHOD = 2; GETTER = 3; SETTER = 4; STATIC = 5; CLASS = 10; // only used in assertValidReturnValue */ function applyDecs2203RFactory() { function createAddInitializerMethod(initializers, decoratorFinishedRef) { return function addInitializer(initializer) { assertNotFinished(decoratorFinishedRef, "addInitializer"); assertCallable(initializer, "An initializer"); initializers.push(initializer); }; } function memberDec( dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value ) { var kindStr; switch (kind) { case 1 /* ACCESSOR */: kindStr = "accessor"; break; case 2 /* METHOD */: kindStr = "method"; break; case 3 /* GETTER */: kindStr = "getter"; break; case 4 /* SETTER */: kindStr = "setter"; break; default: kindStr = "field"; } var ctx = { kind: kindStr, name: isPrivate ? "#" + name : name, static: isStatic, private: isPrivate, metadata: metadata, }; var decoratorFinishedRef = { v: false }; ctx.addInitializer = createAddInitializerMethod( initializers, decoratorFinishedRef ); var get, set; if (kind === 0 /* FIELD */) { if (isPrivate) { get = desc.get; set = desc.set; } else { get = function () { return this[name]; }; set = function (v) { this[name] = v; }; } } else if (kind === 2 /* METHOD */) { get = function () { return desc.value; }; } else { // replace with values that will go through the final getter and setter if (kind === 1 /* ACCESSOR */ || kind === 3 /* GETTER */) { get = function () { return desc.get.call(this); }; } if (kind === 1 /* ACCESSOR */ || kind === 4 /* SETTER */) { set = function (v) { desc.set.call(this, v); }; } } ctx.access = get && set ? { get: get, set: set } : get ? { get: get } : { set: set }; try { return dec(value, ctx); } finally { decoratorFinishedRef.v = true; } } function assertNotFinished(decoratorFinishedRef, fnName) { if (decoratorFinishedRef.v) { throw new Error( "attempted to call " + fnName + " after decoration was finished" ); } } function assertCallable(fn, hint) { if (typeof fn !== "function") { throw new TypeError(hint + " must be a function"); } } function assertValidReturnValue(kind, value) { var type = typeof value; if (kind === 1 /* ACCESSOR */) { if (type !== "object" || value === null) { throw new TypeError( "accessor decorators must return an object with get, set, or init properties or void 0" ); } if (value.get !== undefined) { assertCallable(value.get, "accessor.get"); } if (value.set !== undefined) { assertCallable(value.set, "accessor.set"); } if (value.init !== undefined) { assertCallable(value.init, "accessor.init"); } } else if (type !== "function") { var hint; if (kind === 0 /* FIELD */) { hint = "field"; } else if (kind === 10 /* CLASS */) { hint = "class"; } else { hint = "method"; } throw new TypeError( hint + " decorators must return a function or void 0" ); } } function applyMemberDec( ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata ) { var decs = decInfo[0]; var desc, init, value; if (isPrivate) { if (kind === 0 /* FIELD */ || kind === 1 /* ACCESSOR */) { desc = { get: decInfo[3], set: decInfo[4], }; } else if (kind === 3 /* GETTER */) { desc = { get: decInfo[3], }; } else if (kind === 4 /* SETTER */) { desc = { set: decInfo[3], }; } else { desc = { value: decInfo[3], }; } } else if (kind !== 0 /* FIELD */) { desc = Object.getOwnPropertyDescriptor(base, name); } if (kind === 1 /* ACCESSOR */) { value = { get: desc.get, set: desc.set, }; } else if (kind === 2 /* METHOD */) { value = desc.value; } else if (kind === 3 /* GETTER */) { value = desc.get; } else if (kind === 4 /* SETTER */) { value = desc.set; } var newValue, get, set; if (typeof decs === "function") { newValue = memberDec( decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value ); if (newValue !== void 0) { assertValidReturnValue(kind, newValue); if (kind === 0 /* FIELD */) { init = newValue; } else if (kind === 1 /* ACCESSOR */) { init = newValue.init; get = newValue.get || value.get; set = newValue.set || value.set; value = { get: get, set: set }; } else { value = newValue; } } } else { for (var i = decs.length - 1; i >= 0; i--) { var dec = decs[i]; newValue = memberDec( dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value ); if (newValue !== void 0) { assertValidReturnValue(kind, newValue); var newInit; if (kind === 0 /* FIELD */) { newInit = newValue; } else if (kind === 1 /* ACCESSOR */) { newInit = newValue.init; get = newValue.get || value.get; set = newValue.set || value.set; value = { get: get, set: set }; } else { value = newValue; } if (newInit !== void 0) { if (init === void 0) { init = newInit; } else if (typeof init === "function") { init = [init, newInit]; } else { init.push(newInit); } } } } } if (kind === 0 /* FIELD */ || kind === 1 /* ACCESSOR */) { if (init === void 0) { // If the initializer was void 0, sub in a dummy initializer init = function (instance, init) { return init; }; } else if (typeof init !== "function") { var ownInitializers = init; init = function (instance, init) { var value = init; for (var i = 0; i < ownInitializers.length; i++) { value = ownInitializers[i].call(instance, value); } return value; }; } else { var originalInitializer = init; init = function (instance, init) { return originalInitializer.call(instance, init); }; } ret.push(init); } if (kind !== 0 /* FIELD */) { if (kind === 1 /* ACCESSOR */) { desc.get = value.get; desc.set = value.set; } else if (kind === 2 /* METHOD */) { desc.value = value; } else if (kind === 3 /* GETTER */) { desc.get = value; } else if (kind === 4 /* SETTER */) { desc.set = value; } if (isPrivate) { if (kind === 1 /* ACCESSOR */) { ret.push(function (instance, args) { return value.get.call(instance, args); }); ret.push(function (instance, args) { return value.set.call(instance, args); }); } else if (kind === 2 /* METHOD */) { ret.push(value); } else { ret.push(function (instance, args) { return value.call(instance, args); }); } } else { Object.defineProperty(base, name, desc); } } } function applyMemberDecs(Class, decInfos, metadata) { var ret = []; var protoInitializers; var staticInitializers; var existingProtoNonFields = new Map(); var existingStaticNonFields = new Map(); for (var i = 0; i < decInfos.length; i++) { var decInfo = decInfos[i]; // skip computed property names if (!Array.isArray(decInfo)) continue; var kind = decInfo[1]; var name = decInfo[2]; var isPrivate = decInfo.length > 3; var isStatic = kind >= 5; /* STATIC */ var base; var initializers; if (isStatic) { base = Class; kind = kind - 5 /* STATIC */; // initialize staticInitializers when we see a non-field static member staticInitializers = staticInitializers || []; initializers = staticInitializers; } else { base = Class.prototype; // initialize protoInitializers when we see a non-field member protoInitializers = protoInitializers || []; initializers = protoInitializers; } if (kind !== 0 /* FIELD */ && !isPrivate) { var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields; var existingKind = existingNonFields.get(name) || 0; if ( existingKind === true || (existingKind === 3 /* GETTER */ && kind !== 4) /* SETTER */ || (existingKind === 4 /* SETTER */ && kind !== 3) /* GETTER */ ) { throw new Error( "Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name ); } else if (!existingKind && kind > 2 /* METHOD */) { existingNonFields.set(name, kind); } else { existingNonFields.set(name, true); } } applyMemberDec( ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata ); } pushInitializers(ret, protoInitializers); pushInitializers(ret, staticInitializers); return ret; } function pushInitializers(ret, initializers) { if (initializers) { ret.push(function (instance) { for (var i = 0; i < initializers.length; i++) { initializers[i].call(instance); } return instance; }); } } function applyClassDecs(targetClass, classDecs, metadata) { if (classDecs.length > 0) { var initializers = []; var newClass = targetClass; var name = targetClass.name; for (var i = classDecs.length - 1; i >= 0; i--) { var decoratorFinishedRef = { v: false }; try { var nextNewClass = classDecs[i](newClass, { kind: "class", name: name, addInitializer: createAddInitializerMethod( initializers, decoratorFinishedRef ), metadata, }); } finally { decoratorFinishedRef.v = true; } if (nextNewClass !== undefined) { assertValidReturnValue(10 /* CLASS */, nextNewClass); newClass = nextNewClass; } } return [ defineMetadata(newClass, metadata), function () { for (var i = 0; i < initializers.length; i++) { initializers[i].call(newClass); } }, ]; } // The transformer will not emit assignment when there are no class decorators, // so we don't have to return an empty array here. } function defineMetadata(Class, metadata) { return Object.defineProperty( Class, Symbol.metadata || Symbol.for("Symbol.metadata"), { configurable: true, enumerable: true, value: metadata } ); } /** Basic usage: applyDecs( Class, [ // member decorators [ dec, // dec or array of decs 0, // kind of value being decorated 'prop', // name of public prop on class containing the value being decorated, '#p', // the name of the private property (if is private, void 0 otherwise), ] ], [ // class decorators dec1, dec2 ] ) ``` Fully transpiled example: ```js @dec class Class { @dec a = 123; @dec #a = 123; @dec @dec2 accessor b = 123; @dec accessor #b = 123; @dec c() { console.log('c'); } @dec #c() { console.log('privC'); } @dec get d() { console.log('d'); } @dec get #d() { console.log('privD'); } @dec set e(v) { console.log('e'); } @dec set #e(v) { console.log('privE'); } } // becomes let initializeInstance; let initializeClass; let initA; let initPrivA; let initB; let initPrivB, getPrivB, setPrivB; let privC; let privD; let privE; let Class; class _Class { static { let ret = applyDecs( this, [ [dec, 0, 'a'], [dec, 0, 'a', (i) => i.#a, (i, v) => i.#a = v], [[dec, dec2], 1, 'b'], [dec, 1, 'b', (i) => i.#privBData, (i, v) => i.#privBData = v], [dec, 2, 'c'], [dec, 2, 'c', () => console.log('privC')], [dec, 3, 'd'], [dec, 3, 'd', () => console.log('privD')], [dec, 4, 'e'], [dec, 4, 'e', () => console.log('privE')], ], [ dec ] ) initA = ret[0]; initPrivA = ret[1]; initB = ret[2]; initPrivB = ret[3]; getPrivB = ret[4]; setPrivB = ret[5]; privC = ret[6]; privD = ret[7]; privE = ret[8]; initializeInstance = ret[9]; Class = ret[10] initializeClass = ret[11]; } a = (initializeInstance(this), initA(this, 123)); #a = initPrivA(this, 123); #bData = initB(this, 123); get b() { return this.#bData } set b(v) { this.#bData = v } #privBData = initPrivB(this, 123); get #b() { return getPrivB(this); } set #b(v) { setPrivB(this, v); } c() { console.log('c'); } #c(...args) { return privC(this, ...args) } get d() { console.log('d'); } get #d() { return privD(this); } set e(v) { console.log('e'); } set #e(v) { privE(this, v); } } initializeClass(Class); */ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) { if (parentClass !== void 0) { var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")]; } var metadata = Object.create( parentMetadata === void 0 ? null : parentMetadata ); var e = applyMemberDecs(targetClass, memberDecs, metadata); if (!classDecs.length) defineMetadata(targetClass, metadata); return { e: e, // Lazily apply class decorations so that member init locals can be properly bound. get c() { return applyClassDecs(targetClass, classDecs, metadata); }, }; }; } function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) { return (_apply_decs_2203_r = applyDecs2203RFactory())( targetClass, memberDecs, classDecs, parentClass ); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/helpers/_array_like_to_array.js
JavaScript
function _array_like_to_array(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/helpers/_array_with_holes.js
JavaScript
function _array_with_holes(arr) { if (Array.isArray(arr)) return arr; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/helpers/_array_without_holes.js
JavaScript
function _array_without_holes(arr) { if (Array.isArray(arr)) return _array_like_to_array(arr); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/helpers/_assert_this_initialized.js
JavaScript
function _assert_this_initialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/helpers/_async_generator.js
JavaScript
function _async_generator(gen) { var front, back; function send(key, arg) { return new Promise(function(resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; var wrappedAwait = value instanceof _await_value; Promise.resolve(wrappedAwait ? value.wrapped : value).then(function(arg) { if (wrappedAwait) { resume("next", arg); return; } settle(result.done ? "return" : "normal", arg); }, function(err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { _async_generator.prototype[Symbol.asyncIterator] = function() { return this; }; } _async_generator.prototype.next = function(arg) { return this._invoke("next", arg); }; _async_generator.prototype.throw = function(arg) { return this._invoke("throw", arg); }; _async_generator.prototype.return = function(arg) { return this._invoke("return", arg); };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/helpers/_async_generator_delegate.js
JavaScript
function _async_generator_delegate(inner, awaitWrap) { var iter = {}, waiting = false; function pump(key, value) { waiting = true; value = new Promise(function(resolve) { resolve(inner[key](value)); }); return { done: false, value: awaitWrap(value) }; } if (typeof Symbol === "function" && Symbol.iterator) { iter[Symbol.iterator] = function() { return this; }; } iter.next = function(value) { if (waiting) { waiting = false; return value; } return pump("next", value); }; if (typeof inner.throw === "function") { iter.throw = function(value) { if (waiting) { waiting = false; throw value; } return pump("throw", value); }; } if (typeof inner.return === "function") { iter.return = function(value) { return pump("return", value); }; } return iter; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_base/src/helpers/_async_iterator.js
JavaScript
function _async_iterator(iterable) { var method, async, sync, retry = 2; for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { if (async && null != (method = iterable[async])) return method.call(iterable); if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable)); async = "@@asyncIterator", sync = "@@iterator"; } throw new TypeError("Object is not async iterable"); } function AsyncFromSyncIterator(s) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var done = r.done; return Promise.resolve(r.value).then(function(value) { return { value: value, done: done }; }); } return AsyncFromSyncIterator = function(s) { this.s = s, this.n = s.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function() { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, return: function(value) { var ret = this.s.return; return void 0 === ret ? Promise.resolve({ value: value, done: !0 }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); }, throw: function(value) { var thr = this.s.return; return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(s); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University