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_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/spack_issue_009.js
JavaScript
class A { } function a() { return new A(); } console.log(a, a());
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/spack_issue_010.js
JavaScript
class A { } console.log(new A());
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/closure_compiler_1234.js
JavaScript
var x; switch('a'){ case 'a': break; default: x = 1; break; } use(x);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/const_1.js
JavaScript
function f(x) { if (true) { const y = x; x; x; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/custom_loop_1.js
JavaScript
let b; let a = 1; if (2) { a = 2; } let c; if (a) { c = 3; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/custom_loop_2.js
JavaScript
let b; let a; a = 2; let c; if (2) c = 3;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/custom_loop_3.js
JavaScript
let c; c = 3; console.log(3);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/deno_8180_1.js
JavaScript
var Status; (function(Status) { Status[Status["Continue"] = 100] = "Continue"; Status[Status["SwitchingProtocols"] = 101] = "SwitchingProtocols"; })(Status || (Status = {})); const STATUS_TEXT = new Map([ [ Status.Continue, "Continue" ], [ Status.SwitchingProtocols, "Switching Protocols" ] ]);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/deno_8189_1.js
JavaScript
let A, I = null; function g() { return null !== I && I.buffer === A.memory.buffer || (I = new Uint8Array(A.memory.buffer)), I; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/for_of_1.js
JavaScript
var i = 0; for (i of n){}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/for_of_2.js
JavaScript
for (var i of n){ var x = i; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/function_scope_simple_var.js
JavaScript
var a; var b; use(1);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/function_scope_var_1.js
JavaScript
var x = 1; function foo() { x = 2; } use(x);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/function_scope_var_2.js
JavaScript
(function() { var x = 1; function foo() { x = 2; } use(x); })();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/generator_let_increment.js
JavaScript
function* f(x) { let y = x++; yield y; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/generator_let_yield.js
JavaScript
function* f() { let x; yield 1; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/issue_1156_1.js
JavaScript
export function d() { let methods; const promise = new Promise((resolve, reject)=>{ methods = { resolve, reject }; }); return Object.assign(promise, methods); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/issue_1156_2.js
JavaScript
function d() { let methods; const promise = new Promise((resolve, reject)=>{ methods = { resolve, reject }; }); return Object.assign(promise, methods); } class A { a() { this.s.resolve(); } b() { this.s = d(); } constructor(){ this.s = d(); } } new A();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/let_1.js
JavaScript
function f(x) { if (true) { let y; x; x; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/let_2.js
JavaScript
let y; { let y; x; }y;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/let_const_1.js
JavaScript
const g = 3; let y; 3;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/let_const_2.js
JavaScript
let y; x; const g = 2; { const g = 3; let y; 3; }x; 2;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/regex.js
JavaScript
var b; b = /ab/; /ab/ ? x = 1 : x = 2;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/simple_inline_in_fn.js
JavaScript
var x; var z; use(1);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/tagged_tpl_lit_2.js
JavaScript
var name; function myTag(strings, nameExp, numExp) { var modStr; if (numExp > 2) { modStr = nameExp + 'Bar'; } else { modStr = nameExp + 'BarBar'; } } var output = myTag`My name is ${'Foo'} ${3}`; output = myTag`My name is ${'Foo'} ${2}`;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/top_level_assign_op.js
JavaScript
var x = 1; x += 3;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/top_level_decrement.js
JavaScript
var x = 1; x--;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/top_level_does_not_inline_fn_decl.js
JavaScript
function foo() {} use(foo);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/top_level_increment.js
JavaScript
var x = 1; x++;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/top_level_simple_var.js
JavaScript
var a; var b;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/tpl_lit_1.js
JavaScript
var name; `Hello ${'Foo'}`;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/tpl_lit_2.js
JavaScript
var name; var foo; `Hello ${'Foo'}`;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_inlining.rs/tpl_lit_3.js
JavaScript
var age; `Age: ${3}`;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/const-modules/issue-7747/input.js
JavaScript
import foo from "some-const-module"; console.log(foo); export function _() { console.log(foo); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/const-modules/issue-7747/output.js
JavaScript
console.log(42); export function _() { console.log(42); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/const_modules.rs
Rust
use std::{collections::HashMap, fs::read_to_string, path::PathBuf}; use swc_ecma_ast::Pass; use swc_ecma_transforms_optimization::const_modules; use swc_ecma_transforms_testing::{test, test_fixture, Tester}; fn tr(t: &mut Tester<'_>, sources: &[(&str, &[(&str, &str)])]) -> impl Pass { let mut m = HashMap::default(); for (src, values) in sources { let values = values .iter() .map(|(k, v)| ((*k).into(), v.to_string())) .collect(); m.insert((*src).into(), values); } const_modules(t.cm.clone(), m) } test!( ::swc_ecma_parser::Syntax::default(), |tester| tr(tester, &[("@ember/env-flags", &[("DEBUG", "true")])]), simple_flags, r#"import { DEBUG } from '@ember/env-flags'; if (DEBUG) { console.log('Foo!'); }"# ); test!( ::swc_ecma_parser::Syntax::default(), |tester| tr(tester, &[("@ember/env-flags", &[("DEBUG", "true")])]), imports_hoisted, r#" if (DEBUG) { console.log('Foo!'); } import { DEBUG } from '@ember/env-flags'; "# ); test!( ::swc_ecma_parser::Syntax::default(), |tester| tr( tester, &[ ("@ember/env-flags", &[("DEBUG", "true")]), ( "@ember/features", &[("FEATURE_A", "false"), ("FEATURE_B", "true")] ) ] ), complex_multiple, " import { DEBUG } from '@ember/env-flags'; import { FEATURE_A, FEATURE_B } from '@ember/features'; if (DEBUG) { console.log('Foo!'); } let woot; if (FEATURE_A) { woot = () => 'woot'; } else if (FEATURE_B) { woot = () => 'toow'; } " ); test!( ::swc_ecma_parser::Syntax::default(), |tester| tr(tester, &[("foo", &[("bar", "true")])]), namespace_import, r#" import * as foo from 'foo'; console.log(foo.bar) "# ); test!( ::swc_ecma_parser::Syntax::default(), |tester| tr(tester, &[("foo", &[("bar", "true")])]), namespace_import_computed, r#" import * as foo from 'foo'; console.log(foo["bar"]) "# ); test!( ::swc_ecma_parser::Syntax::default(), |tester| tr( tester, &[("testModule", &[("testMap", "{ 'var': 'value' }")])] ), issue_7025, r#" import { testMap } from "testModule"; testMap['var']; "# ); test!( ::swc_ecma_parser::Syntax::default(), |tester| tr(tester, &[("foo", &[("bar", "true")])]), use_as_object_prop_shorthand, r#" import { bar } from 'foo'; console.log({ bar }); "# ); test!( ::swc_ecma_parser::Syntax::default(), |tester| tr(tester, &[("my-mod", &[("default", "true")])]), default_import_issue_7601, r#" import something from 'my-mod'; console.log(something); "# ); #[testing::fixture("tests/const-modules/**/input.js")] fn const_modules_test(input: PathBuf) { let globals = input.with_file_name("globals.json"); let output = input.with_file_name("output.js"); test_fixture( ::swc_ecma_parser::Syntax::default(), &|t| { let globals = read_to_string(&globals) .ok() .and_then(|s| serde_json::from_str(&s).ok()) .unwrap_or_default(); const_modules(t.cm.clone(), globals) }, &input, &output, Default::default(), ); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce-jsx/property/input.js
JavaScript
function A() { return "a"; } const b = "b"; export function c() { return <A.b />; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce-jsx/property/output.js
JavaScript
function A() { return "a"; } export function c() { return <A.b />; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce-jsx/property2/input.js
JavaScript
function A() { return "a"; } const b = "b"; const c = "c"; export function d() { return <A.b.c />; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce-jsx/property2/output.js
JavaScript
function A() { return "a"; } export function d() { return <A.b.c />; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce-jsx/spread/input.js
JavaScript
function A() { return "a"; } const b = "b"; const c = "c"; export function d() { return <A {...b}>{c}</A>; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce-jsx/spread/output.js
JavaScript
function A() { return "a"; } const b = "b"; const c = "c"; export function d() { return <A {...b}>{c}</A>; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce-jsx/var/input.js
JavaScript
function A() { return "a"; } const b = "b"; const c = "c"; export function d() { return <A val={b}>{c}</A>; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce-jsx/var/output.js
JavaScript
function A() { return "a"; } const b = "b"; const c = "c"; export function d() { return <A val={b}>{c}</A>; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-1/input.js
JavaScript
function foo() { bar() baz() } function bar() { foo() } function baz() { foo() } class A { b() { new B() } } class B { a() { new A() } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-2/input.js
JavaScript
function foo() { bar() baz() } function bar() { foo() } function baz() { foo() } class A { b() { new B() } } class B { a() { new A() } } bar()
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-2/output.full.js
JavaScript
function foo() { bar(); baz(); } function bar() { foo(); } function baz() { foo(); } bar();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-2/output.js
JavaScript
function foo() { bar(); baz(); } function bar() { foo(); } function baz() { foo(); } bar();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-3/input.js
JavaScript
function foo() { bar() baz() } function bar() { foo() } function baz() { foo() } class A { b() { new B() } } class B { a() { new A() } } export function use() { return bar() }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-3/output.full.js
JavaScript
function foo() { bar(); baz(); } function bar() { foo(); } function baz() { foo(); } export function use() { return bar(); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-3/output.js
JavaScript
function foo() { bar(); baz(); } function bar() { foo(); } function baz() { foo(); } export function use() { return bar(); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-4/input.js
JavaScript
__self.push(function () { "use strict"; __webpack_require__.r(__webpack_exports__), __webpack_require__.d(__webpack_exports__, { axios: function () { return _axios_0_21_4_axios_default(); }, axiosUtils: function () { return axiosUtils; } }); var _axios_0_21_4_axios = __webpack_require__(73035), _axios_0_21_4_axios_default = __webpack_require__.n(_axios_0_21_4_axios); function isArray(val) { return "[object Array]" === toString.call(val); } function isPlainObject(val) { if ("[object Object]" !== toString.call(val)) return !1; var prototype = Object.getPrototypeOf(val); return null === prototype || prototype === Object.prototype; } function forEach(obj, fn) { if (null != obj) { if ("object" != typeof obj && (obj = [ obj ]), isArray(obj)) for (var i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj); else for (var key in obj) Object.prototype.hasOwnProperty.call(obj, key) && fn.call(null, obj[key], key, obj); } } var axiosUtils = { forEach: forEach, merge: function merge() { for (var args = [], _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i]; var result = {}; function assignValue(val, key) { isPlainObject(result[key]) && isPlainObject(val) ? result[key] = merge(result[key], val) : isPlainObject(val) ? result[key] = merge({}, val) : isArray(val) ? result[key] = val.slice() : result[key] = val; } for (var i = 0, l = args.length; i < l; i++)forEach(args[i], assignValue); return result; }, isArray: isArray }; })
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-4/output.full.js
JavaScript
__self.push(function() { "use strict"; __webpack_require__.r(__webpack_exports__), __webpack_require__.d(__webpack_exports__, { axios: function() { return _axios_0_21_4_axios_default(); }, axiosUtils: function() { return axiosUtils; } }); var _axios_0_21_4_axios = __webpack_require__(73035), _axios_0_21_4_axios_default = __webpack_require__.n(_axios_0_21_4_axios); function isArray(val) { return "[object Array]" === toString.call(val); } function isPlainObject(val) { if ("[object Object]" !== toString.call(val)) return !1; var prototype = Object.getPrototypeOf(val); return null === prototype || prototype === Object.prototype; } function forEach(obj, fn) { if (null != obj) { if ("object" != typeof obj && (obj = [ obj ]), isArray(obj)) for(var i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj); else for(var key in obj)Object.prototype.hasOwnProperty.call(obj, key) && fn.call(null, obj[key], key, obj); } } var axiosUtils = { forEach: forEach, merge: function merge() { for(var args = [], _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i]; var result = {}; function assignValue(val, key) { isPlainObject(result[key]) && isPlainObject(val) ? result[key] = merge(result[key], val) : isPlainObject(val) ? result[key] = merge({}, val) : isArray(val) ? result[key] = val.slice() : result[key] = val; } for(var i = 0, l = args.length; i < l; i++)forEach(args[i], assignValue); return result; }, isArray: isArray }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-4/output.js
JavaScript
__self.push(function() { "use strict"; __webpack_require__.r(__webpack_exports__), __webpack_require__.d(__webpack_exports__, { axios: function() { return _axios_0_21_4_axios_default(); }, axiosUtils: function() { return axiosUtils; } }); var _axios_0_21_4_axios = __webpack_require__(73035), _axios_0_21_4_axios_default = __webpack_require__.n(_axios_0_21_4_axios); function isArray(val) { return "[object Array]" === toString.call(val); } function isPlainObject(val) { if ("[object Object]" !== toString.call(val)) return !1; var prototype = Object.getPrototypeOf(val); return null === prototype || prototype === Object.prototype; } function forEach(obj, fn) { if (null != obj) { if ("object" != typeof obj && (obj = [ obj ]), isArray(obj)) for(var i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj); else for(var key in obj)Object.prototype.hasOwnProperty.call(obj, key) && fn.call(null, obj[key], key, obj); } } var axiosUtils = { forEach: forEach, merge: function merge() { for(var args = [], _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i]; var result = {}; function assignValue(val, key) { isPlainObject(result[key]) && isPlainObject(val) ? result[key] = merge(result[key], val) : isPlainObject(val) ? result[key] = merge({}, val) : isArray(val) ? result[key] = val.slice() : result[key] = val; } for(var i = 0, l = args.length; i < l; i++)forEach(args[i], assignValue); return result; }, isArray: isArray }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-5/input.js
JavaScript
export function f(x, y) { function g() { return h(); } function h() { return g(); } return x + y; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-5/output.full.js
JavaScript
export function f(x, y) { return x + y; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/cycle-5/output.js
JavaScript
export function f(x, y) { return x + y; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-18789/case1/input.js
JavaScript
@decorator class Class {} function decorator(cls) { console.log(cls.name); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-18789/case1/output.full.js
JavaScript
@decorator class Class { } function decorator(cls) { console.log(cls.name); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-18789/case1/output.js
JavaScript
@decorator class Class { } function decorator(cls) { console.log(cls.name); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-9546/case1/input.js
JavaScript
function a() { return "a"; } function b() { return "b"; } export function c() { return b(); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-9546/case1/output.full.js
JavaScript
function b() { return "b"; } export function c() { return b(); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-9546/case1/output.js
JavaScript
function b() { return "b"; } export function c() { return b(); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-9546/case2/input.js
JavaScript
function a() { return "a"; } function b() { return "b"; } a();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-9546/case2/output.full.js
JavaScript
function a() { return "a"; } a();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-9546/case2/output.js
JavaScript
function a() { return "a"; } a();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-9546/case3/input.js
JavaScript
function a() { return "a"; } function b() { return "b"; } function c() { return b(); } a();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-9546/case3/output.full.js
JavaScript
function a() { return "a"; } a();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/deno-9546/case3/output.js
JavaScript
function a() { return "a"; } function b() { return "b"; } a();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/issue-6066/input.js
JavaScript
// Generated by Peggy 2.0.1. // // https://peggyjs.org/ "use strict"; function peg$subclass(child, parent) { function C() { this.constructor = child; } C.prototype = parent.prototype; child.prototype = new C(); } function peg$SyntaxError(message, expected, found, location) { var self = Error.call(this, message); // istanbul ignore next Check is a necessary evil to support older environments if (Object.setPrototypeOf) { Object.setPrototypeOf(self, peg$SyntaxError.prototype); } self.expected = expected; self.found = found; self.location = location; self.name = "SyntaxError"; return self; } peg$subclass(peg$SyntaxError, Error); function peg$padEnd(str, targetLength, padString) { padString = padString || " "; if (str.length > targetLength) { return str; } targetLength -= str.length; padString += padString.repeat(targetLength); return str + padString.slice(0, targetLength); } peg$SyntaxError.prototype.format = function (sources) { var str = "Error: " + this.message; if (this.location) { var src = null; var k; for (k = 0; k < sources.length; k++) { if (sources[k].source === this.location.source) { src = sources[k].text.split(/\r\n|\n|\r/g); break; } } var s = this.location.start; var loc = this.location.source + ":" + s.line + ":" + s.column; if (src) { var e = this.location.end; var filler = peg$padEnd("", s.line.toString().length, ' '); var line = src[s.line - 1]; var last = s.line === e.line ? e.column : line.length + 1; var hatLen = (last - s.column) || 1; str += "\n --> " + loc + "\n" + filler + " |\n" + s.line + " | " + line + "\n" + filler + " | " + peg$padEnd("", s.column - 1, ' ') + peg$padEnd("", hatLen, "^"); } else { str += "\n at " + loc; } } return str; }; peg$SyntaxError.buildMessage = function (expected, found) { var DESCRIBE_EXPECTATION_FNS = { literal: function (expectation) { return "\"" + literalEscape(expectation.text) + "\""; }, class: function (expectation) { var escapedParts = expectation.parts.map(function (part) { return Array.isArray(part) ? classEscape(part[0]) + "-" + classEscape(part[1]) : classEscape(part); }); return "[" + (expectation.inverted ? "^" : "") + escapedParts.join("") + "]"; }, any: function () { return "any character"; }, end: function () { return "end of input"; }, other: function (expectation) { return expectation.description; } }; function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } function literalEscape(s) { return s .replace(/\\/g, "\\\\") .replace(/"/g, "\\\"") .replace(/\0/g, "\\0") .replace(/\t/g, "\\t") .replace(/\n/g, "\\n") .replace(/\r/g, "\\r") .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); } function classEscape(s) { return s .replace(/\\/g, "\\\\") .replace(/\]/g, "\\]") .replace(/\^/g, "\\^") .replace(/-/g, "\\-") .replace(/\0/g, "\\0") .replace(/\t/g, "\\t") .replace(/\n/g, "\\n") .replace(/\r/g, "\\r") .replace(/[\x00-\x0F]/g, function (ch) { return "\\x0" + hex(ch); }) .replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return "\\x" + hex(ch); }); } function describeExpectation(expectation) { return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); } function describeExpected(expected) { var descriptions = expected.map(describeExpectation); var i, j; descriptions.sort(); if (descriptions.length > 0) { for (i = 1, j = 1; i < descriptions.length; i++) { if (descriptions[i - 1] !== descriptions[i]) { descriptions[j] = descriptions[i]; j++; } } descriptions.length = j; } switch (descriptions.length) { case 1: return descriptions[0]; case 2: return descriptions[0] + " or " + descriptions[1]; default: return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; } } function describeFound(found) { return found ? "\"" + literalEscape(found) + "\"" : "end of input"; } return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; function peg$parse(input, options) { options = options !== undefined ? options : {}; var peg$FAILED = {}; var peg$source = options.grammarSource; var peg$startRuleFunctions = { TEST: peg$parseTEST }; var peg$startRuleFunction = peg$parseTEST; var peg$r0 = /^[a]/; var peg$r1 = /^[b]/; var peg$r2 = /^[c]/; var peg$r3 = /^[d]/; var peg$r4 = /^[e]/; var peg$r5 = /^[f]/; var peg$r6 = /^[g]/; var peg$r7 = /^[h]/; var peg$r8 = /^[i]/; var peg$r9 = /^[j]/; var peg$r10 = /^[k]/; var peg$r11 = /^[l]/; var peg$r12 = /^[m]/; var peg$r13 = /^[n]/; var peg$r14 = /^[o]/; var peg$r15 = /^[p]/; var peg$r16 = /^[q]/; var peg$r17 = /^[r]/; var peg$r18 = /^[s]/; var peg$r19 = /^[t]/; var peg$r20 = /^[u]/; var peg$r21 = /^[v]/; var peg$e0 = peg$classExpectation(["a"], false, false); var peg$e1 = peg$classExpectation(["b"], false, false); var peg$e2 = peg$classExpectation(["c"], false, false); var peg$e3 = peg$classExpectation(["d"], false, false); var peg$e4 = peg$classExpectation(["e"], false, false); var peg$e5 = peg$classExpectation(["f"], false, false); var peg$e6 = peg$classExpectation(["g"], false, false); var peg$e7 = peg$classExpectation(["h"], false, false); var peg$e8 = peg$classExpectation(["i"], false, false); var peg$e9 = peg$classExpectation(["j"], false, false); var peg$e10 = peg$classExpectation(["k"], false, false); var peg$e11 = peg$classExpectation(["l"], false, false); var peg$e12 = peg$classExpectation(["m"], false, false); var peg$e13 = peg$classExpectation(["n"], false, false); var peg$e14 = peg$classExpectation(["o"], false, false); var peg$e15 = peg$classExpectation(["p"], false, false); var peg$e16 = peg$classExpectation(["q"], false, false); var peg$e17 = peg$classExpectation(["r"], false, false); var peg$e18 = peg$classExpectation(["s"], false, false); var peg$e19 = peg$classExpectation(["t"], false, false); var peg$e20 = peg$classExpectation(["u"], false, false); var peg$e21 = peg$classExpectation(["v"], false, false); var peg$currPos = 0; var peg$savedPos = 0; var peg$posDetailsCache = [{ line: 1, column: 1 }]; var peg$maxFailPos = 0; var peg$maxFailExpected = []; var peg$silentFails = 0; var peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function text() { return input.substring(peg$savedPos, peg$currPos); } function offset() { return peg$savedPos; } function range() { return { source: peg$source, start: peg$savedPos, end: peg$currPos }; } function location() { return peg$computeLocation(peg$savedPos, peg$currPos); } function expected(description, location) { location = location !== undefined ? location : peg$computeLocation(peg$savedPos, peg$currPos); throw peg$buildStructuredError( [peg$otherExpectation(description)], input.substring(peg$savedPos, peg$currPos), location ); } function error(message, location) { location = location !== undefined ? location : peg$computeLocation(peg$savedPos, peg$currPos); throw peg$buildSimpleError(message, location); } function peg$literalExpectation(text, ignoreCase) { return { type: "literal", text: text, ignoreCase: ignoreCase }; } function peg$classExpectation(parts, inverted, ignoreCase) { return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; } function peg$anyExpectation() { return { type: "any" }; } function peg$endExpectation() { return { type: "end" }; } function peg$otherExpectation(description) { return { type: "other", description: description }; } function peg$computePosDetails(pos) { var details = peg$posDetailsCache[pos]; var p; if (details) { return details; } else { p = pos - 1; while (!peg$posDetailsCache[p]) { p--; } details = peg$posDetailsCache[p]; details = { line: details.line, column: details.column }; while (p < pos) { if (input.charCodeAt(p) === 10) { details.line++; details.column = 1; } else { details.column++; } p++; } peg$posDetailsCache[pos] = details; return details; } } function peg$computeLocation(startPos, endPos) { var startPosDetails = peg$computePosDetails(startPos); var endPosDetails = peg$computePosDetails(endPos); return { source: peg$source, start: { offset: startPos, line: startPosDetails.line, column: startPosDetails.column }, end: { offset: endPos, line: endPosDetails.line, column: endPosDetails.column } }; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildSimpleError(message, location) { return new peg$SyntaxError(message, null, null, location); } function peg$buildStructuredError(expected, found, location) { return new peg$SyntaxError( peg$SyntaxError.buildMessage(expected, found), expected, found, location ); } function peg$parseTEST() { var s0; if (peg$r0.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e0); } } if (s0 === peg$FAILED) { if (peg$r1.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e1); } } if (s0 === peg$FAILED) { if (peg$r2.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e2); } } if (s0 === peg$FAILED) { if (peg$r3.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e3); } } if (s0 === peg$FAILED) { if (peg$r4.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e4); } } if (s0 === peg$FAILED) { if (peg$r5.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e5); } } if (s0 === peg$FAILED) { if (peg$r6.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e6); } } if (s0 === peg$FAILED) { if (peg$r7.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e7); } } if (s0 === peg$FAILED) { if (peg$r8.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e8); } } if (s0 === peg$FAILED) { if (peg$r9.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e9); } } if (s0 === peg$FAILED) { if (peg$r10.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e10); } } if (s0 === peg$FAILED) { if (peg$r11.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e11); } } if (s0 === peg$FAILED) { if (peg$r12.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e12); } } if (s0 === peg$FAILED) { if (peg$r13.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e13); } } if (s0 === peg$FAILED) { if (peg$r14.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e14); } } if (s0 === peg$FAILED) { if (peg$r15.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e15); } } if (s0 === peg$FAILED) { if (peg$r16.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e16); } } if (s0 === peg$FAILED) { if (peg$r17.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e17); } } if (s0 === peg$FAILED) { if (peg$r18.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e18); } } if (s0 === peg$FAILED) { if (peg$r19.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e19); } } if (s0 === peg$FAILED) { if (peg$r20.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e20); } } if (s0 === peg$FAILED) { if (peg$r21.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e21); } } } } } } } } } } } } } } } } } } } } } } } return s0; } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail(peg$endExpectation()); } throw peg$buildStructuredError( peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) ); } } module.exports = { SyntaxError: peg$SyntaxError, parse: peg$parse };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/issue-6066/output.full.js
JavaScript
// Generated by Peggy 2.0.1. // // https://peggyjs.org/ "use strict"; function peg$subclass(child, parent) { function C() { this.constructor = child; } C.prototype = parent.prototype; child.prototype = new C(); } function peg$SyntaxError(message, expected, found, location) { var self = Error.call(this, message); // istanbul ignore next Check is a necessary evil to support older environments if (Object.setPrototypeOf) { Object.setPrototypeOf(self, peg$SyntaxError.prototype); } self.expected = expected; self.found = found; self.location = location; self.name = "SyntaxError"; return self; } peg$subclass(peg$SyntaxError, Error); function peg$padEnd(str, targetLength, padString) { padString = padString || " "; if (str.length > targetLength) { return str; } targetLength -= str.length; padString += padString.repeat(targetLength); return str + padString.slice(0, targetLength); } peg$SyntaxError.prototype.format = function(sources) { var str = "Error: " + this.message; if (this.location) { var src = null; var k; for(k = 0; k < sources.length; k++){ if (sources[k].source === this.location.source) { src = sources[k].text.split(/\r\n|\n|\r/g); break; } } var s = this.location.start; var loc = this.location.source + ":" + s.line + ":" + s.column; if (src) { var e = this.location.end; var filler = peg$padEnd("", s.line.toString().length, ' '); var line = src[s.line - 1]; var last = s.line === e.line ? e.column : line.length + 1; var hatLen = last - s.column || 1; str += "\n --> " + loc + "\n" + filler + " |\n" + s.line + " | " + line + "\n" + filler + " | " + peg$padEnd("", s.column - 1, ' ') + peg$padEnd("", hatLen, "^"); } else { str += "\n at " + loc; } } return str; }; peg$SyntaxError.buildMessage = function(expected, found) { var DESCRIBE_EXPECTATION_FNS = { literal: function(expectation) { return "\"" + literalEscape(expectation.text) + "\""; }, class: function(expectation) { var escapedParts = expectation.parts.map(function(part) { return Array.isArray(part) ? classEscape(part[0]) + "-" + classEscape(part[1]) : classEscape(part); }); return "[" + (expectation.inverted ? "^" : "") + escapedParts.join("") + "]"; }, any: function() { return "any character"; }, end: function() { return "end of input"; }, other: function(expectation) { return expectation.description; } }; function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } function literalEscape(s) { return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\0/g, "\\0").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/[\x00-\x0F]/g, function(ch) { return "\\x0" + hex(ch); }).replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return "\\x" + hex(ch); }); } function classEscape(s) { return s.replace(/\\/g, "\\\\").replace(/\]/g, "\\]").replace(/\^/g, "\\^").replace(/-/g, "\\-").replace(/\0/g, "\\0").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/[\x00-\x0F]/g, function(ch) { return "\\x0" + hex(ch); }).replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return "\\x" + hex(ch); }); } function describeExpectation(expectation) { return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); } function describeExpected(expected) { var descriptions = expected.map(describeExpectation); var i, j; descriptions.sort(); if (descriptions.length > 0) { for(i = 1, j = 1; i < descriptions.length; i++){ if (descriptions[i - 1] !== descriptions[i]) { descriptions[j] = descriptions[i]; j++; } } descriptions.length = j; } switch(descriptions.length){ case 1: return descriptions[0]; case 2: return descriptions[0] + " or " + descriptions[1]; default: return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; } } function describeFound(found) { return found ? "\"" + literalEscape(found) + "\"" : "end of input"; } return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; function peg$parse(input, options) { options = options !== undefined ? options : {}; var peg$FAILED = {}; var peg$source = options.grammarSource; var peg$startRuleFunctions = { TEST: peg$parseTEST }; var peg$startRuleFunction = peg$parseTEST; var peg$r0 = /^[a]/; var peg$r1 = /^[b]/; var peg$r2 = /^[c]/; var peg$r3 = /^[d]/; var peg$r4 = /^[e]/; var peg$r5 = /^[f]/; var peg$r6 = /^[g]/; var peg$r7 = /^[h]/; var peg$r8 = /^[i]/; var peg$r9 = /^[j]/; var peg$r10 = /^[k]/; var peg$r11 = /^[l]/; var peg$r12 = /^[m]/; var peg$r13 = /^[n]/; var peg$r14 = /^[o]/; var peg$r15 = /^[p]/; var peg$r16 = /^[q]/; var peg$r17 = /^[r]/; var peg$r18 = /^[s]/; var peg$r19 = /^[t]/; var peg$r20 = /^[u]/; var peg$r21 = /^[v]/; var peg$e0 = peg$classExpectation([ "a" ], false, false); var peg$e1 = peg$classExpectation([ "b" ], false, false); var peg$e2 = peg$classExpectation([ "c" ], false, false); var peg$e3 = peg$classExpectation([ "d" ], false, false); var peg$e4 = peg$classExpectation([ "e" ], false, false); var peg$e5 = peg$classExpectation([ "f" ], false, false); var peg$e6 = peg$classExpectation([ "g" ], false, false); var peg$e7 = peg$classExpectation([ "h" ], false, false); var peg$e8 = peg$classExpectation([ "i" ], false, false); var peg$e9 = peg$classExpectation([ "j" ], false, false); var peg$e10 = peg$classExpectation([ "k" ], false, false); var peg$e11 = peg$classExpectation([ "l" ], false, false); var peg$e12 = peg$classExpectation([ "m" ], false, false); var peg$e13 = peg$classExpectation([ "n" ], false, false); var peg$e14 = peg$classExpectation([ "o" ], false, false); var peg$e15 = peg$classExpectation([ "p" ], false, false); var peg$e16 = peg$classExpectation([ "q" ], false, false); var peg$e17 = peg$classExpectation([ "r" ], false, false); var peg$e18 = peg$classExpectation([ "s" ], false, false); var peg$e19 = peg$classExpectation([ "t" ], false, false); var peg$e20 = peg$classExpectation([ "u" ], false, false); var peg$e21 = peg$classExpectation([ "v" ], false, false); var peg$currPos = 0; var peg$savedPos = 0; var peg$posDetailsCache = [ { line: 1, column: 1 } ]; var peg$maxFailPos = 0; var peg$maxFailExpected = []; var peg$silentFails = 0; var peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function location() { return peg$computeLocation(peg$savedPos, peg$currPos); } function expected(description, location) { location = location !== undefined ? location : peg$computeLocation(peg$savedPos, peg$currPos); throw peg$buildStructuredError([ peg$otherExpectation(description) ], input.substring(peg$savedPos, peg$currPos), location); } function peg$classExpectation(parts, inverted, ignoreCase) { return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; } function peg$endExpectation() { return { type: "end" }; } function peg$otherExpectation(description) { return { type: "other", description: description }; } function peg$computePosDetails(pos) { var details = peg$posDetailsCache[pos]; var p; if (details) { return details; } else { p = pos - 1; while(!peg$posDetailsCache[p]){ p--; } details = peg$posDetailsCache[p]; details = { line: details.line, column: details.column }; while(p < pos){ if (input.charCodeAt(p) === 10) { details.line++; details.column = 1; } else { details.column++; } p++; } peg$posDetailsCache[pos] = details; return details; } } function peg$computeLocation(startPos, endPos) { var startPosDetails = peg$computePosDetails(startPos); var endPosDetails = peg$computePosDetails(endPos); return { source: peg$source, start: { offset: startPos, line: startPosDetails.line, column: startPosDetails.column }, end: { offset: endPos, line: endPosDetails.line, column: endPosDetails.column } }; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildStructuredError(expected, found, location) { return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location); } function peg$parseTEST() { var s0; if (peg$r0.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e0); } } if (s0 === peg$FAILED) { if (peg$r1.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e1); } } if (s0 === peg$FAILED) { if (peg$r2.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e2); } } if (s0 === peg$FAILED) { if (peg$r3.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e3); } } if (s0 === peg$FAILED) { if (peg$r4.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e4); } } if (s0 === peg$FAILED) { if (peg$r5.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e5); } } if (s0 === peg$FAILED) { if (peg$r6.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e6); } } if (s0 === peg$FAILED) { if (peg$r7.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e7); } } if (s0 === peg$FAILED) { if (peg$r8.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e8); } } if (s0 === peg$FAILED) { if (peg$r9.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e9); } } if (s0 === peg$FAILED) { if (peg$r10.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e10); } } if (s0 === peg$FAILED) { if (peg$r11.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e11); } } if (s0 === peg$FAILED) { if (peg$r12.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e12); } } if (s0 === peg$FAILED) { if (peg$r13.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e13); } } if (s0 === peg$FAILED) { if (peg$r14.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e14); } } if (s0 === peg$FAILED) { if (peg$r15.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e15); } } if (s0 === peg$FAILED) { if (peg$r16.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e16); } } if (s0 === peg$FAILED) { if (peg$r17.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e17); } } if (s0 === peg$FAILED) { if (peg$r18.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e18); } } if (s0 === peg$FAILED) { if (peg$r19.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e19); } } if (s0 === peg$FAILED) { if (peg$r20.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e20); } } if (s0 === peg$FAILED) { if (peg$r21.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e21); } } } } } } } } } } } } } } } } } } } } } } } return s0; } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail(peg$endExpectation()); } throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); } } module.exports = { SyntaxError: peg$SyntaxError, parse: peg$parse };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/dce/issue-6066/output.js
JavaScript
// Generated by Peggy 2.0.1. // // https://peggyjs.org/ "use strict"; function peg$subclass(child, parent) { function C() { this.constructor = child; } C.prototype = parent.prototype; child.prototype = new C(); } function peg$SyntaxError(message, expected, found, location) { var self = Error.call(this, message); // istanbul ignore next Check is a necessary evil to support older environments if (Object.setPrototypeOf) { Object.setPrototypeOf(self, peg$SyntaxError.prototype); } self.expected = expected; self.found = found; self.location = location; self.name = "SyntaxError"; return self; } peg$subclass(peg$SyntaxError, Error); function peg$padEnd(str, targetLength, padString) { padString = padString || " "; if (str.length > targetLength) { return str; } targetLength -= str.length; padString += padString.repeat(targetLength); return str + padString.slice(0, targetLength); } peg$SyntaxError.prototype.format = function(sources) { var str = "Error: " + this.message; if (this.location) { var src = null; var k; for(k = 0; k < sources.length; k++){ if (sources[k].source === this.location.source) { src = sources[k].text.split(/\r\n|\n|\r/g); break; } } var s = this.location.start; var loc = this.location.source + ":" + s.line + ":" + s.column; if (src) { var e = this.location.end; var filler = peg$padEnd("", s.line.toString().length, ' '); var line = src[s.line - 1]; var last = s.line === e.line ? e.column : line.length + 1; var hatLen = last - s.column || 1; str += "\n --> " + loc + "\n" + filler + " |\n" + s.line + " | " + line + "\n" + filler + " | " + peg$padEnd("", s.column - 1, ' ') + peg$padEnd("", hatLen, "^"); } else { str += "\n at " + loc; } } return str; }; peg$SyntaxError.buildMessage = function(expected, found) { var DESCRIBE_EXPECTATION_FNS = { literal: function(expectation) { return "\"" + literalEscape(expectation.text) + "\""; }, class: function(expectation) { var escapedParts = expectation.parts.map(function(part) { return Array.isArray(part) ? classEscape(part[0]) + "-" + classEscape(part[1]) : classEscape(part); }); return "[" + (expectation.inverted ? "^" : "") + escapedParts.join("") + "]"; }, any: function() { return "any character"; }, end: function() { return "end of input"; }, other: function(expectation) { return expectation.description; } }; function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } function literalEscape(s) { return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\0/g, "\\0").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/[\x00-\x0F]/g, function(ch) { return "\\x0" + hex(ch); }).replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return "\\x" + hex(ch); }); } function classEscape(s) { return s.replace(/\\/g, "\\\\").replace(/\]/g, "\\]").replace(/\^/g, "\\^").replace(/-/g, "\\-").replace(/\0/g, "\\0").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/[\x00-\x0F]/g, function(ch) { return "\\x0" + hex(ch); }).replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return "\\x" + hex(ch); }); } function describeExpectation(expectation) { return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); } function describeExpected(expected) { var descriptions = expected.map(describeExpectation); var i, j; descriptions.sort(); if (descriptions.length > 0) { for(i = 1, j = 1; i < descriptions.length; i++){ if (descriptions[i - 1] !== descriptions[i]) { descriptions[j] = descriptions[i]; j++; } } descriptions.length = j; } switch(descriptions.length){ case 1: return descriptions[0]; case 2: return descriptions[0] + " or " + descriptions[1]; default: return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; } } function describeFound(found) { return found ? "\"" + literalEscape(found) + "\"" : "end of input"; } return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; function peg$parse(input, options) { options = options !== undefined ? options : {}; var peg$FAILED = {}; var peg$source = options.grammarSource; var peg$startRuleFunctions = { TEST: peg$parseTEST }; var peg$startRuleFunction = peg$parseTEST; var peg$r0 = /^[a]/; var peg$r1 = /^[b]/; var peg$r2 = /^[c]/; var peg$r3 = /^[d]/; var peg$r4 = /^[e]/; var peg$r5 = /^[f]/; var peg$r6 = /^[g]/; var peg$r7 = /^[h]/; var peg$r8 = /^[i]/; var peg$r9 = /^[j]/; var peg$r10 = /^[k]/; var peg$r11 = /^[l]/; var peg$r12 = /^[m]/; var peg$r13 = /^[n]/; var peg$r14 = /^[o]/; var peg$r15 = /^[p]/; var peg$r16 = /^[q]/; var peg$r17 = /^[r]/; var peg$r18 = /^[s]/; var peg$r19 = /^[t]/; var peg$r20 = /^[u]/; var peg$r21 = /^[v]/; var peg$e0 = peg$classExpectation([ "a" ], false, false); var peg$e1 = peg$classExpectation([ "b" ], false, false); var peg$e2 = peg$classExpectation([ "c" ], false, false); var peg$e3 = peg$classExpectation([ "d" ], false, false); var peg$e4 = peg$classExpectation([ "e" ], false, false); var peg$e5 = peg$classExpectation([ "f" ], false, false); var peg$e6 = peg$classExpectation([ "g" ], false, false); var peg$e7 = peg$classExpectation([ "h" ], false, false); var peg$e8 = peg$classExpectation([ "i" ], false, false); var peg$e9 = peg$classExpectation([ "j" ], false, false); var peg$e10 = peg$classExpectation([ "k" ], false, false); var peg$e11 = peg$classExpectation([ "l" ], false, false); var peg$e12 = peg$classExpectation([ "m" ], false, false); var peg$e13 = peg$classExpectation([ "n" ], false, false); var peg$e14 = peg$classExpectation([ "o" ], false, false); var peg$e15 = peg$classExpectation([ "p" ], false, false); var peg$e16 = peg$classExpectation([ "q" ], false, false); var peg$e17 = peg$classExpectation([ "r" ], false, false); var peg$e18 = peg$classExpectation([ "s" ], false, false); var peg$e19 = peg$classExpectation([ "t" ], false, false); var peg$e20 = peg$classExpectation([ "u" ], false, false); var peg$e21 = peg$classExpectation([ "v" ], false, false); var peg$currPos = 0; var peg$savedPos = 0; var peg$posDetailsCache = [ { line: 1, column: 1 } ]; var peg$maxFailPos = 0; var peg$maxFailExpected = []; var peg$silentFails = 0; var peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function text() { return input.substring(peg$savedPos, peg$currPos); } function location() { return peg$computeLocation(peg$savedPos, peg$currPos); } function expected(description, location) { location = location !== undefined ? location : peg$computeLocation(peg$savedPos, peg$currPos); throw peg$buildStructuredError([ peg$otherExpectation(description) ], input.substring(peg$savedPos, peg$currPos), location); } function peg$classExpectation(parts, inverted, ignoreCase) { return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; } function peg$endExpectation() { return { type: "end" }; } function peg$otherExpectation(description) { return { type: "other", description: description }; } function peg$computePosDetails(pos) { var details = peg$posDetailsCache[pos]; var p; if (details) { return details; } else { p = pos - 1; while(!peg$posDetailsCache[p]){ p--; } details = peg$posDetailsCache[p]; details = { line: details.line, column: details.column }; while(p < pos){ if (input.charCodeAt(p) === 10) { details.line++; details.column = 1; } else { details.column++; } p++; } peg$posDetailsCache[pos] = details; return details; } } function peg$computeLocation(startPos, endPos) { var startPosDetails = peg$computePosDetails(startPos); var endPosDetails = peg$computePosDetails(endPos); return { source: peg$source, start: { offset: startPos, line: startPosDetails.line, column: startPosDetails.column }, end: { offset: endPos, line: endPosDetails.line, column: endPosDetails.column } }; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildSimpleError(message, location) { return new peg$SyntaxError(message, null, null, location); } function peg$buildStructuredError(expected, found, location) { return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location); } function peg$parseTEST() { var s0; if (peg$r0.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e0); } } if (s0 === peg$FAILED) { if (peg$r1.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e1); } } if (s0 === peg$FAILED) { if (peg$r2.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e2); } } if (s0 === peg$FAILED) { if (peg$r3.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e3); } } if (s0 === peg$FAILED) { if (peg$r4.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e4); } } if (s0 === peg$FAILED) { if (peg$r5.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e5); } } if (s0 === peg$FAILED) { if (peg$r6.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e6); } } if (s0 === peg$FAILED) { if (peg$r7.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e7); } } if (s0 === peg$FAILED) { if (peg$r8.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e8); } } if (s0 === peg$FAILED) { if (peg$r9.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e9); } } if (s0 === peg$FAILED) { if (peg$r10.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e10); } } if (s0 === peg$FAILED) { if (peg$r11.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e11); } } if (s0 === peg$FAILED) { if (peg$r12.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e12); } } if (s0 === peg$FAILED) { if (peg$r13.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e13); } } if (s0 === peg$FAILED) { if (peg$r14.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e14); } } if (s0 === peg$FAILED) { if (peg$r15.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e15); } } if (s0 === peg$FAILED) { if (peg$r16.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e16); } } if (s0 === peg$FAILED) { if (peg$r17.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e17); } } if (s0 === peg$FAILED) { if (peg$r18.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e18); } } if (s0 === peg$FAILED) { if (peg$r19.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e19); } } if (s0 === peg$FAILED) { if (peg$r20.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e20); } } if (s0 === peg$FAILED) { if (peg$r21.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$e21); } } } } } } } } } } } } } } } } } } } } } } } return s0; } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail(peg$endExpectation()); } throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); } } module.exports = { SyntaxError: peg$SyntaxError, parse: peg$parse };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-1688/case1/input.js
JavaScript
({ notafunction: null }?.notafunction?.());
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-1688/case1/output.js
JavaScript
({ notafunction: null })?.notafunction?.();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-1688/case2/input.js
JavaScript
({ notafunction: null }?.notafunction());
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-1688/case2/output.js
JavaScript
({ notafunction: null })?.notafunction();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-1688/case3/input.js
JavaScript
({ notafunction: null }.notafunction?.());
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-1688/case3/output.js
JavaScript
({ notafunction: null }).notafunction?.();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-1846/fcase1/input.js
JavaScript
import "reflect-metadata"; const Test = (target) => { const metadata = Reflect.getMetadataKeys(target).reduce((metadata, key) => { const { [key]: values = [] } = metadata; const all = Reflect.getMetadata(key, target); const own = Reflect.getOwnMetadata(key, target); return { ...metadata, [key]: [{ all, own }, ...values], }; }, {}); console.dir(metadata, { depth: 5 }); }; export class Foo {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-1846/fcase1/output.js
JavaScript
import "reflect-metadata"; const Test = (target)=>{ const metadata = Reflect.getMetadataKeys(target).reduce((metadata, key)=>{ const { [key]: values = [] } = metadata; const all = Reflect.getMetadata(key, target); const own = Reflect.getOwnMetadata(key, target); return { ...metadata, [key]: [ { all, own }, ...values ] }; }, { }); console.dir(metadata, { depth: 5 }); }; export class Foo { }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-1901/case1/input.js
JavaScript
const object = { a: true }; export const mapContextToProps = () => { return { ...object }; };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-1901/case1/output.js
JavaScript
const object = { a: true }; export const mapContextToProps = ()=>{ return { ...object }; };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-2165/case1/input.js
JavaScript
var bit = 0; var sum = 0; sum += (bit ^= 1) ? 0 : 1; sum += (bit ^= 1) ? 0 : 1; console.log(sum);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-2165/case1/output.js
JavaScript
var bit = 0; var sum = 0; sum += (bit ^= 1) ? 0 : 1; sum += (bit ^= 1) ? 0 : 1; console.log(sum);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-3115/input.js
JavaScript
var flm = /*#__PURE__*/ hMap(flt, 9, 0); var deo = /*#__PURE__*/ new Uint32Array([65540, 131080, 131088]); var Unzip = /*#__PURE__*/ (function () { console.log("Unzip"); })();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-3115/output.js
JavaScript
var flm = /*#__PURE__*/ hMap(flt, 9, 0); var deo = /*#__PURE__*/ new Uint32Array([ 65540, 131080, 131088 ]); var Unzip = /*#__PURE__*/ function() { console.log("Unzip"); }();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-3816/input.js
JavaScript
/** @license React v17.0.2 * react-jsx-runtime.profiling.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ "use strict"; require("object-assign"); var f = require("react"), g = 60103; exports.Fragment = 60107; if ("function" === typeof Symbol && Symbol.for) { var h = Symbol.for; g = h("react.element"); exports.Fragment = h("react.fragment"); } var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { key: !0, ref: !0, __self: !0, __source: !0 }; function q(c, a, k) { var b, d = {}, e = null, l = null; void 0 !== k && (e = "" + k); void 0 !== a.key && (e = "" + a.key); void 0 !== a.ref && (l = a.ref); for (b in a) n.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); if (c && c.defaultProps) for (b in ((a = c.defaultProps), a)) void 0 === d[b] && (d[b] = a[b]); return { $$typeof: g, type: c, key: e, ref: l, props: d, _owner: m.current, }; } exports.jsx = q; exports.jsxs = q;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/expr-simplifier/issue-3816/output.js
JavaScript
/** @license React v17.0.2 * react-jsx-runtime.profiling.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ "use strict"; require("object-assign"); var f = require("react"), g = 60103; exports.Fragment = 60107; if ("function" === typeof Symbol && Symbol.for) { var h = Symbol.for; g = h("react.element"); exports.Fragment = h("react.fragment"); } var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { key: !0, ref: !0, __self: !0, __source: !0 }; function q(c, a, k) { var b, d = {}, e = null, l = null; void 0 !== k && (e = "" + k); void 0 !== a.key && (e = "" + a.key); void 0 !== a.ref && (l = a.ref); for(b in a)n.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); if (c && c.defaultProps) for(b in a = c.defaultProps, a)void 0 === d[b] && (d[b] = a[b]); return { $$typeof: g, type: c, key: e, ref: l, props: d, _owner: m.current }; } exports.jsx = q; exports.jsxs = q;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/fixture.rs
Rust
use std::path::PathBuf; use swc_common::{pass::Repeat, Mark}; use swc_ecma_ast::Pass; use swc_ecma_parser::{EsSyntax, Syntax}; use swc_ecma_transforms_base::fixer::paren_remover; use swc_ecma_transforms_optimization::simplify::{dce::dce, expr_simplifier}; use swc_ecma_transforms_testing::{test_fixture, Tester}; use swc_ecma_visit::visit_mut_pass; fn remover(t: &Tester) -> impl Pass { visit_mut_pass(paren_remover(Some( Box::leak(Box::new(t.comments.clone())) as _ ))) } #[testing::fixture("tests/dce/**/input.js")] fn dce_single_pass(input: PathBuf) { let output = input.with_file_name("output.js"); test_fixture( Syntax::Es(EsSyntax { decorators: true, ..Default::default() }), &|t| { let unresolved_mark = Mark::new(); (remover(t), dce(Default::default(), unresolved_mark)) }, &input, &output, Default::default(), ); } #[testing::fixture("tests/dce/**/input.js")] fn dce_repeated(input: PathBuf) { let output = input.with_file_name("output.full.js"); test_fixture( Syntax::Es(EsSyntax { decorators: true, ..Default::default() }), &|t| { ( remover(t), Repeat::new(dce(Default::default(), Mark::new())), ) }, &input, &output, Default::default(), ); } #[testing::fixture("tests/dce-jsx/**/input.js")] fn dce_jsx(input: PathBuf) { let output = input.with_file_name("output.js"); test_fixture( Syntax::Es(EsSyntax { decorators: true, jsx: true, ..Default::default() }), &|t| (remover(t), dce(Default::default(), Mark::new())), &input, &output, Default::default(), ); } #[testing::fixture("tests/expr-simplifier/**/input.js")] fn expr(input: PathBuf) { let output = input.with_file_name("output.js"); test_fixture( Syntax::Es(Default::default()), &|t| { let top_level_mark = Mark::fresh(Mark::root()); ( remover(t), Repeat::new(expr_simplifier(top_level_mark, Default::default())), ) }, &input, &output, Default::default(), ); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/remove_imports_with_side_effects.rs
Rust
use swc_common::{pass::Repeat, Mark}; use swc_ecma_ast::Pass; use swc_ecma_parser::{EsSyntax, Syntax}; use swc_ecma_transforms_base::resolver; use swc_ecma_transforms_optimization::simplify::dce::{dce, Config}; use swc_ecma_transforms_testing::test; fn tr() -> impl Pass { Repeat::new(dce( Config { top_level: true, preserve_imports_with_side_effects: false, ..Default::default() }, Mark::new(), )) } macro_rules! to { ($name:ident, $src:expr) => { test!( Syntax::Es(EsSyntax { decorators: true, ..Default::default() }), |_| (resolver(Mark::new(), Mark::new(), false), tr()), $name, $src ); }; } macro_rules! optimized_out { ($name:ident, $src:expr) => { to!($name, $src); }; } macro_rules! noop { ($name:ident, $src:expr) => { to!($name, $src); }; } to!( single_pass, " const a = 1; if (a) { const b = 2; } " ); optimized_out!(import_default_unused, "import foo from 'foo'"); optimized_out!(import_specific_unused, "import {foo} from 'foo'"); optimized_out!(import_mixed_unused, "import foo, { bar } from 'foo'"); noop!( import_export_named, "import foo from 'src'; export { foo };" ); to!( import_unused_export_named, "import foo, { bar } from 'src'; export { foo }; " );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/simplify.rs
Rust
//! Copied from PeepholeIntegrationTest from the google closure compiler. #![deny(warnings)] use swc_common::{pass::Repeat, Mark}; use swc_ecma_parser::{Syntax, TsSyntax}; use swc_ecma_transforms_base::{helpers::inject_helpers, resolver}; use swc_ecma_transforms_compat::{es2015, es2016, es2017, es2018, es2022::class_properties, es3}; use swc_ecma_transforms_module::{common_js::common_js, import_analysis::import_analyzer}; use swc_ecma_transforms_optimization::simplify::{ dce::{self, dce}, dead_branch_remover, expr_simplifier, inlining::{self, inlining}, }; use swc_ecma_transforms_proposal::decorators; use swc_ecma_transforms_testing::{test, test_transform}; use swc_ecma_transforms_typescript::strip; fn test(src: &str, expected: &str) { test_transform( ::swc_ecma_parser::Syntax::default(), None, |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), Repeat::new(( expr_simplifier(unresolved_mark, Default::default()), inlining::inlining(Default::default()), dead_branch_remover(unresolved_mark), dce::dce(Default::default(), unresolved_mark), )), ) }, src, expected, ) } fn test_same(src: &str) { test(src, src) } macro_rules! to { ($name:ident, $src:expr) => { test!( Default::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), Repeat::new(( expr_simplifier(unresolved_mark, Default::default()), inlining::inlining(Default::default()), dead_branch_remover(unresolved_mark), dce::dce(Default::default(), unresolved_mark), )), ) }, $name, $src ); }; } macro_rules! optimized_out { ($name:ident, $src:expr) => { to!($name, $src); }; } to!( single_pass, " const a = 1; if (a) { const b = 2; } " ); optimized_out!(issue_607, "let a"); to!( multi_run, " let b = 2; let a = 1; if (b) { // Removed by first run of remove_dead_branch a = 2; // It becomes `flat assignment` to a on second run of inlining } let c; if (a) { // Removed by second run of remove_dead_branch c = 3; // It becomes `flat assignment` to c on third run of inlining. } console.log(c); // Prevent optimizing out. " ); #[test] #[ignore] // TODO fn test_fold_one_child_blocks_integration() { test( "function f(){switch(foo()){default:{break}}}", "function f(){foo()}", ); test( "function f(){switch(x){default:{break}}} use(f);", "function f(){} use(f);", ); test( "function f(){switch(x){default:x;case 1:return 2}} use(f);", "function f(){switch(x){default:case 1:return 2}} use(f);", ); // ensure that block folding does not break hook ifs test( "if(x){if(true){foo();foo()}else{bar();bar()}}", "if(x){foo();foo()}", ); test( "if(x){if(false){foo();foo()}else{bar();bar()}}", "if(x){bar();bar()}", ); // Cases where the then clause has no side effects. test("if(x()){}", "x()"); test("if(x()){} else {x()}", "x()||x()"); test("if(x){}", ""); // Even the condition has no side effect. test( "if(a()){A()} else if (b()) {} else {C()}", "a()?A():b()||C()", ); test( "if(a()){} else if (b()) {} else {C()}", "a() || (b() || C())", ); test( "if(a()){A()} else if (b()) {} else if (c()) {} else{D()}", "a() ? A() : b() || (c() || D())", ); test( "if(a()){} else if (b()) {} else if (c()) {} else{D()}", "a() || (b() || (c() || D()))", ); test( "if(a()){A()} else if (b()) {} else if (c()) {} else{}", "a()?A():b()||c()", ); // Verify that non-global scope works. test("function foo(){if(x()){}}", "function foo(){x()}"); } #[test] #[ignore] // swc optimizes out everything fn test_fold_one_child_blocks_string_compare() { test( "if (x) {if (y) { var x; } } else{ var z; }", "if (x) { if (y) var x } else var z", ); } #[test] fn test_necessary_dangling_else() { test( "if (x) if (y){ y(); z() } else; else x()", "if (x) { if(y) { y(); z() } } else x()", ); } #[test] #[ignore] // TODO fn test_fold_returns_integration() { // if-then-else duplicate statement removal handles this case: test("function f(){if(x)return;else return}", "function f(){}"); } #[test] fn test_bug1059649() { // ensure that folding blocks with a single var node doesn't explode test( "if(x){var y=3;}var z=5; use(y, z)", "if(x)var y=3; use(y, 5)", ); test( "for(var i=0;i<10;i++){var y=3;}var z=5; use(y, z)", "for(var i=0;i<10;i++)var y=3; use(y, 5)", ); test( "for(var i in x){var y=3;}var z=5; use(y, z)", "for(var i in x)var y=3; use(y, 5)", ); test( "do{var y=3;}while(x);var z=5; use(y, z)", "do var y=3;while(x); use(y, 5)", ); } #[test] #[ignore] // TODO fn test_hook_if_integration() { test( "if (false){ x = 1; } else if (cond) { x = 2; } else { x = 3; }", "x=cond?2:3", ); test("x?void 0:y()", "x||y()"); test("!x?void 0:y()", "x&&y()"); test("x?y():void 0", "x&&y()"); } #[test] #[ignore] // normalize fn test_remove_duplicate_statements_integration() { test( concat!( "function z() {if (a) { return true }", "else if (b) { return true }", "else { return true }}", ), "function z() {return true;}", ); test( concat!( "function z() {if (a()) { return true }", "else if (b()) { return true }", "else { return true }}", ), "function z() {a()||b();return true;}", ); } #[test] #[ignore] // TODO fn test_fold_logical_op_integration() { test("if(x && true) z()", "x&&z()"); test("if(x && false) z()", ""); test("if(x || 3) z()", "z()"); test("if(x || false) z()", "x&&z()"); test("if(x==y && false) z()", ""); test("if(y() || x || 3) z()", "y();z()"); } #[test] #[ignore] // TODO: This is a bug, but does anyone write code like this? fn test_fold_bitwise_op_string_compare_integration() { test("for (;-1 | 0;) {}", "for (;;);"); } #[test] fn test_var_lifting_integration() { test("if(true);else var a;", ""); test("if(false) foo();else var a;", ""); test("if(true)var a;else;", ""); test("if(false)var a;else;", ""); test("if(false)var a,b;", ""); test("if(false){var a;var a;}", ""); test("if(false)var a=function(){var b};", ""); // TODO(kdy1): We can optimize this. // test("if(a)if(false)var a;else var b;", ""); test("if(a)if(false)var a;else var b;", "if(a) var a;"); } #[test] fn test_bug1438784() { test_same("for(var i=0;i<10;i++)if(x)x.y;"); } #[test] fn test_fold_useless_for_integration() { test("for(;!true;) { foo() }", ""); test("for(;void 0;) { foo() }", ""); // test("for(;undefined;) { foo() }", ""); test("for(;1;) foo()", "for(;;) foo()"); test("for(;!void 0;) foo()", "for(;;) foo()"); // Make sure proper empty nodes are inserted. // test("if(foo())for(;false;){foo()}else bar()", "foo()||bar()"); test( "if(foo())for(;false;){foo()}else bar()", "if (foo()); else bar();", ); } #[test] fn test_fold_useless_do_integration() { test("do { foo() } while(!true);", "foo()"); test("do { foo() } while(void 0);", "foo()"); // test("do { foo() } while(undefined);", "foo()"); test("do { foo() } while(!void 0);", "for(;;)foo();"); // Make sure proper empty nodes are inserted. // test( // "if(foo())do {foo()} while(false) else bar()", // "foo()?foo():bar()", // ); test( "if(foo())do {foo()} while(false) else bar()", "if (foo()) foo(); else bar();", ); } #[test] #[ignore] // TODO fn test_minimize_expr() { test("!!true", ""); test("!!x()", "x()"); test("!(!x()&&!y())", "x()||y()"); test("x()||!!y()", "x()||y()"); /* This is similar to the !!true case */ test("!!x()&&y()", "x()&&y()"); } #[test] fn test_bug_issue3() { test( concat!( "function foo() {", " if(sections.length != 1) children[i] = 0;", " else var selectedid = children[i]", "}", "foo()" ), concat!( "function foo() {", " if(sections.length != 1) children[i] = 0;", " else children[i]", "}", "foo()" ), ); } #[test] fn test_bug_issue43() { test_same("function foo() {\n if (a) bar(); else a.b = 1; \n} use(foo);"); } #[test] fn test_fold_negative_bug() { test("for (;-3;){};", "for (;;);"); } #[test] #[ignore] // normalize fn test_no_normalize_labeled_expr() { test_same("var x; foo:{x = 3;}"); test_same("var x; foo:x = 3;"); } #[test] fn test_short_circuit1() { test("1 && a()", "a()"); } #[test] fn test_short_circuit2() { test("1 && a() && 2", "a()"); } #[test] fn test_short_circuit3() { test("a() && 1 && 2", "a()"); } #[test] #[ignore] fn test_short_circuit4() { test("a() && (1 && b())", "a() && b()"); test("a() && 1 && b()", "a() && b()"); test("(a() && 1) && b()", "a() && b()"); } #[test] #[ignore] // TODO fn test_minimize_expr_condition() { test("(x || true) && y()", "y()"); test("(x || false) && y()", "x&&y()"); test("(x && true) && y()", "x && y()"); test("(x && false) && y()", ""); test("a = x || false ? b : c", "a=x?b:c"); test("do {x()} while((x && false) && y())", "x()"); } // A few miscellaneous cases where one of the peephole passes increases the // size, but it does it in such a way that a later pass can decrease it. // Test to make sure the overall change is a decrease, not an increase. #[test] #[ignore] // TODO fn test_misc() { test("use(x = [foo()] && x)", "use(x = (foo(),x))"); test("x = foo() && false || bar()", "x = (foo(), bar())"); test("if(foo() && false) z()", "foo()"); } #[test] #[ignore] // swc strips out whole of this fn test_comma_spliting_constant_condition() { test("(b=0,b=1);if(b)x=b;", "b=0;b=1;x=b;"); test("(b=0,b=1);if(b)x=b;", "b=0;b=1;x=b;"); } #[test] #[ignore] fn test_avoid_comma_splitting() { test("x(),y(),z()", "x();y();z()"); } #[test] fn test_object_literal() { test("({})", ""); test("({a:1})", ""); test("({a:foo()})", "foo()"); test("({'a':foo()})", "foo()"); } #[test] fn test_array_literal() { test("([])", ""); test("([1])", ""); test("([a])", "a"); test("([foo()])", "foo()"); } #[test] #[ignore] // TODO fn test_fold_ifs1() { test( "function f() {if (x) return 1; else if (y) return 1;}", "function f() {if (x||y) return 1;}", ); test( "function f() {if (x) return 1; else {if (y) return 1; else foo();}}", "function f() {if (x||y) return 1; foo();}", ); } #[test] #[ignore] // TODO fn test_fold_ifs2() { test( "function f() {if (x) { a(); } else if (y) { a() }}", "function f() {x?a():y&&a();}", ); } #[test] #[ignore] // TODO fn test_fold_hook2() { test( "function f(a) {if (!a) return a; else return a;}", "function f(a) {return a}", ); } #[test] #[ignore] // TODO fn test_template_strings_known_methods() { test("x = `abcdef`.indexOf('b')", "x = 1"); test("x = [`a`, `b`, `c`].join(``)", "x='abc'"); test("x = `abcdef`.substr(0,2)", "x = 'ab'"); test("x = `abcdef`.substring(0,2)", "x = 'ab'"); test("x = `abcdef`.slice(0,2)", "x = 'ab'"); test("x = `abcdef`.charAt(0)", "x = 'a'"); test("x = `abcdef`.charCodeAt(0)", "x = 97"); test("x = `abc`.toUpperCase()", "x = 'ABC'"); test("x = `ABC`.toLowerCase()", "x = 'abc'"); //test("x = `\t\n\uFEFF\t asd foo bar \r\n`.trim()", "x = 'asd foo bar'"); test("x = parseInt(`123`)", "x = 123"); test("x = parseFloat(`1.23`)", "x = 1.23"); } test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), strip(unresolved_mark, top_level_mark), class_properties( class_properties::Config { set_public_fields: true, ..Default::default() }, unresolved_mark, ), dce(Default::default(), unresolved_mark), inlining(Default::default()), ) }, issue_1156_1, " interface D { resolve: any; reject: any; } function d(): D { let methods; const promise = new Promise((resolve, reject) => { methods = { resolve, reject }; }); return Object.assign(promise, methods); } class A { private s: D = d(); a() { this.s.resolve(); } b() { this.s = d(); } } new A(); " ); test!( Syntax::Es(Default::default()), |t| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( decorators(Default::default()), resolver(unresolved_mark, top_level_mark, false), strip(unresolved_mark, top_level_mark), class_properties(Default::default(), unresolved_mark), Repeat::new(( expr_simplifier(unresolved_mark, Default::default()), inlining::inlining(Default::default()), dead_branch_remover(unresolved_mark), dce::dce(Default::default(), unresolved_mark), )), es2018(Default::default()), es2017(Default::default(), unresolved_mark), es2016(), es2015( unresolved_mark, Some(t.comments.clone()), Default::default(), ), es3(true), import_analyzer(false.into(), false), inject_helpers(unresolved_mark), common_js( Default::default(), Mark::fresh(Mark::root()), Default::default(), Default::default(), ), ) }, issue_389_3, " import Foo from 'foo'; Foo.bar = true; " ); test!( Syntax::default(), |_| { let top_level_mark = Mark::fresh(Mark::root()); expr_simplifier(top_level_mark, Default::default()) }, issue_1619_1, r#" "use strict"; console.log("\x00" + "\x31"); "# ); test!( Syntax::default(), |_| { let top_level_mark = Mark::fresh(Mark::root()); dead_branch_remover(top_level_mark) }, issue_2466_1, " const X = { run() { console.log(this === globalThis); }, }; X.run(); (0, X.run)(); " ); test!( Syntax::default(), |_| { let top_level_mark = Mark::fresh(Mark::root()); dead_branch_remover(top_level_mark) }, issue_4272, " function oe() { var e, t; return t !== i && (e, t = t), e = t; } " ); test!( Syntax::default(), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), Repeat::new(( inlining(Default::default()), dead_branch_remover(unresolved_mark), )), ) }, issue_4173, " function emit(type) { const e = events[type]; if (Array.isArray(e)) { for (let i = 0; i < e.length; i += 1) { e[i].apply(this); } } } " );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/simplify_dce.rs
Rust
use swc_common::{pass::Repeat, Mark}; use swc_ecma_ast::Pass; use swc_ecma_parser::{EsSyntax, Syntax, TsSyntax}; use swc_ecma_transforms_base::resolver; use swc_ecma_transforms_compat::es2022::class_properties; use swc_ecma_transforms_optimization::simplify::dce::{dce, Config}; use swc_ecma_transforms_proposal::decorators; use swc_ecma_transforms_testing::test; use swc_ecma_transforms_typescript::strip; fn tr() -> impl Pass { Repeat::new(dce( Config { top_level: true, ..Default::default() }, Mark::new(), )) } macro_rules! to { ($name:ident, $src:expr) => { test!( Syntax::Es(EsSyntax { decorators: true, ..Default::default() }), |_| (resolver(Mark::new(), Mark::new(), false), tr()), $name, $src ); }; } macro_rules! optimized_out { ($name:ident, $src:expr) => { to!($name, $src); }; } macro_rules! noop { ($name:ident, $src:expr) => { to!($name, $src); }; } to!( single_pass, " const a = 1; if (a) { const b = 2; } " ); optimized_out!(issue_607, "let a"); noop!( noop_1, " let b = 2; let a = 1; if (b) { a = 2; } let c; if (a) { c = 3; } console.log(c); " ); noop!( noop_2, " switch (1){ case 1: a = '1'; } console.log(a); " ); noop!( noop_3, " try { console.log(foo()) } catch (e) { console.error(e); }" ); to!( custom_loop_2, "let b = 2; let a = 1; a = 2; let c; if (2) c = 3 console.log(c)" ); optimized_out!(simple_const, "{const x = 1}"); noop!(assign_op, "x *= 2; use(x)"); to!(import_default_unused, "import foo from 'foo'"); to!(import_specific_unused, "import {foo} from 'foo'"); to!(import_mixed_unused, "import foo, { bar } from 'foo'"); noop!(export_named, "export { x };"); noop!(export_named_from, "export {foo} from 'src';"); noop!( import_default_export_named, "import foo from 'src'; export { foo }; " ); to!( import_unused_export_named, "import foo, { bar } from 'src'; export { foo }; " ); noop!( issue_760_1, "var ref; export const Auth = window === null || window === void 0 ? void 0 : (ref = window.aws) === \ null || ref === void 0 ? void 0 : ref.Auth; " ); noop!( issue_760_2_export_default, "const initialState = 'foo'; export default function reducer(state = initialState, action = {}) { }" ); noop!( issue_760_2_export_named, "const initialState = 'foo'; export function reducer(state = initialState, action = {}) { }" ); optimized_out!( issue_760_2_no_export, "const initialState = 'foo'; function reducer(state = initialState, action = {}) { }" ); to!( issue_763_1, "import { INSTAGRAM_CHECK_PATTERN, RESOURCE_FACEBOOK, RESOURCE_INSTAGRAM, RESOURCE_WEBSITE, } from '../../../../consts' export const resources = [ { value: RESOURCE_WEBSITE, label: 'Webové stránky', }, { value: RESOURCE_FACEBOOK, label: 'Facebook', }, { value: RESOURCE_INSTAGRAM, label: 'Instagram', }, ]" ); to!( issue_763_2, "import { INSTAGRAM_CHECK_PATTERN, RESOURCE_FACEBOOK, RESOURCE_INSTAGRAM, RESOURCE_WEBSITE, } from '../../../../consts' const resources = [ { value: RESOURCE_WEBSITE, label: 'Webové stránky', }, { value: RESOURCE_FACEBOOK, label: 'Facebook', }, { value: RESOURCE_INSTAGRAM, label: 'Instagram', }, ] resources.map(console.log.bind(console));" ); noop!( issue_763_3, "import { RESOURCE_FACEBOOK, RESOURCE_INSTAGRAM, RESOURCE_WEBSITE, } from '../../../../consts' const resources = [ { value: RESOURCE_WEBSITE, label: 'Webové stránky', }, { value: RESOURCE_FACEBOOK, label: 'Facebook', }, { value: RESOURCE_INSTAGRAM, label: 'Instagram', }, ]; resources.map(v => v)" ); noop!( issue_763_4, "import { RESOURCE_FACEBOOK, RESOURCE_INSTAGRAM, RESOURCE_WEBSITE } from './consts'; const resources = [ { value: RESOURCE_WEBSITE, label: 'Webové stránky', }, { value: RESOURCE_FACEBOOK, label: 'Facebook', }, { value: RESOURCE_INSTAGRAM, label: 'Instagram', }, ]; export function foo(websites) { const a = resources.map((resource) => ( { value: resource.value, } )); const b = website.type_id === RESOURCE_INSTAGRAM ? 'text' : 'url'; return a + b; }" ); noop!( issue_763_5_1, "import { A, B } from './consts'; const resources = [A, B]; use(B) resources.map(v => v) " ); noop!( issue_763_5_2, "import { A, B } from './consts'; const resources = {A, B}; use(B) resources.map(v => v) " ); to!( spack_issue_004, "const FOO = 'foo', BAR = 'bar'; export default BAR;" ); noop!( spack_issue_005, "function a() { } function foo() { } console.log(a(), foo());" ); noop!( spack_issue_006, "import * as a from './a'; function foo() {} console.log(foo(), a.a(), a.foo());" ); noop!( spack_issue_007, " var load = function(){} var { progress } = load(); console.log(progress);" ); noop!( spack_issue_008, "class B { } class A extends B { } console.log('foo'); new A();" ); noop!( spack_issue_009, " class A { } function a() { return new A(); } console.log(a, a()); " ); noop!( spack_issue_010, " class A {} console.log(new A()); " ); noop!( issue_898_1, " export default class X { @whatever anything= 0; x() { const localVar = aFunctionSomewhere(); return localVar; } } " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( decorators(decorators::Config { legacy: true, emit_metadata: false, use_define_for_class_fields: false, }), resolver(unresolved_mark, top_level_mark, false), strip(unresolved_mark, top_level_mark), tr(), ) }, issue_898_2, "export default class X { @whatever anything: number = 0; x() { const localVar = aFunctionSomewhere(); return localVar; } } " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( decorators(decorators::Config { legacy: true, emit_metadata: false, use_define_for_class_fields: false, }), resolver(unresolved_mark, top_level_mark, false), strip(unresolved_mark, top_level_mark), tr(), ) }, issue_1111, " const a = 1; export const d = { a }; " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); (resolver(unresolved_mark, top_level_mark, false), tr()) }, issue_1150_1, " class A { constructor(o = {}) { const { a = defaultA, c, } = o; this.#a = a; this.#c = c; } a() { this.#a(); } c() { console.log(this.#c); } } new A(); " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), strip(unresolved_mark, top_level_mark), class_properties( class_properties::Config { set_public_fields: true, ..Default::default() }, unresolved_mark, ), tr(), ) }, issue_1156_1, " export interface D { resolve: any; reject: any; } export function d(): D { let methods; const promise = new Promise((resolve, reject) => { methods = { resolve, reject }; }); return Object.assign(promise, methods); } " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), strip(unresolved_mark, top_level_mark), class_properties( class_properties::Config { set_public_fields: true, ..Default::default() }, unresolved_mark, ), tr(), ) }, issue_1156_2, " interface D { resolve: any; reject: any; } function d(): D { let methods; const promise = new Promise((resolve, reject) => { methods = { resolve, reject }; }); return Object.assign(promise, methods); } class A { private s: D = d(); a() { this.s.resolve(); } b() { this.s = d(); } } new A(); " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), strip(unresolved_mark, top_level_mark), tr(), ) }, issue_1156_3, " function d() { let methods; const promise = new Promise((resolve, reject) => { methods = { resolve, reject }; }); return Object.assign(promise, methods); } d() " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), strip(unresolved_mark, top_level_mark), class_properties( class_properties::Config { set_public_fields: true, ..Default::default() }, unresolved_mark, ), tr(), ) }, issue_1156_4, " interface D { resolve: any; reject: any; } function d(): D { let methods; const promise = new Promise((resolve, reject) => { methods = { resolve, reject }; }); return Object.assign(promise, methods); } class A { private s: D = d(); a() { this.s.resolve(); } } new A(); " ); optimized_out!( self_referential_function_01, " function foo() { if (Math.random() > 0.5) { foo() } } " ); optimized_out!( pr_1199_01, " function _nonIterableSpread() { throw new TypeError('Invalid attempt to spread non-iterable instance'); } " ); noop!( deno_8736_1, " class DenoStdInternalError1 extends Error { constructor(message){ super(message); this.name = 'DenoStdInternalError'; } } const DenoStdInternalError = DenoStdInternalError1; function assert2(expr, msg = '') { if (!expr) { throw new DenoStdInternalError(msg); } } const assert1 = assert2; const assert = assert1; const TEST = Deno.env.get('TEST'); assert(TEST, 'TEST must be defined!'); console.log(`Test is ${TEST}`); " ); noop!( deno_8736_2, " class DenoStdInternalError extends Error { constructor(message){ super(message); this.name = 'DenoStdInternalError'; } } function assert(expr, msg = '') { throw new DenoStdInternalError(msg); } const TEST = Deno.env.get('TEST'); assert(TEST, 'TEST must be defined!'); console.log(`Test is ${TEST}`); " ); noop!( deno_9076, " class App { constructor() { console.log('Hello from app') } } new App; " ); noop!( deno_9212_1, " var _ = []; _ = l.baseState; " ); noop!( deno_9212_2, " if (u !== null) { if (y !== null) { var _ = y.lastBaseUpdate; } } if (i !== null) { _ = l.baseState; } " ); noop!( deno_9121_3, " function wt(e, n, t, r) { var l = e.updateQueue; Fe = !1; var i = l.firstBaseUpdate, o = l.lastBaseUpdate, u = l.shared.pending; if (u !== null) { l.shared.pending = null; var s = u, d = s.next; s.next = null, o === null ? i = d : o.next = d, o = s; var y = e.alternate; if (y !== null) { y = y.updateQueue; var _ = y.lastBaseUpdate; _ !== o && (_ === null ? y.firstBaseUpdate = d : _.next = d, y.lastBaseUpdate = s) } } if (i !== null) { _ = l.baseState, o = 0, y = d = s = null; do { u = i.lane; var h = i.eventTime; if ((r & u) === u) { y !== null && (y = y.next = { eventTime: h, lane: 0, tag: i.tag, payload: i.payload, callback: i.callback, next: null }); e: { var k = e, E = i; switch (u = n, h = t, E.tag) { case 1: if (k = E.payload, typeof k == 'function') { _ = k.call(h, _, u); break e } _ = k; break e; case 3: k.flags = k.flags & -4097 | 64; case 0: if (k = E.payload, u = typeof k == 'function' ? k.call(h, _, u) : \ k, u == null) break e; _ = R({}, _, u); break e; case 2: Fe = !0 } } i.callback !== null && (e.flags |= 32, u = l.effects, u === null ? l.effects = \ [i] : u.push(i)) } else h = { eventTime: h, lane: u, tag: i.tag, payload: i.payload, callback: i.callback, next: null }, y === null ? (d = y = h, s = _) : y = y.next = h, o |= u; if (i = i.next, i === null) { if (u = l.shared.pending, u === null) break; i = u.next, u.next = null, l.lastBaseUpdate = u, l.shared.pending = null } } while (1); y === null && (s = _), l.baseState = s, l.firstBaseUpdate = d, l.lastBaseUpdate = y, \ gt |= o, e.lanes = o, e.memoizedState = _ } } wt() " );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/tests/simplify_inlining.rs
Rust
//! Copied from https://github.com/google/closure-compiler/blob/6ca3b62990064488074a1a8931b9e8dc39b148b3/test/com/google/javascript/jscomp/InlineVariablesTest.java use swc_common::Mark; use swc_ecma_ast::Pass; use swc_ecma_parser::{Syntax, TsSyntax}; use swc_ecma_transforms_base::resolver; use swc_ecma_transforms_compat::es2022::class_properties; use swc_ecma_transforms_optimization::simplify::inlining::inlining; use swc_ecma_transforms_testing::test; use swc_ecma_transforms_typescript::typescript; fn simple_strip(unresolved_mark: Mark, top_level_mark: Mark) -> impl Pass { typescript( typescript::Config { no_empty_export: true, ..Default::default() }, unresolved_mark, top_level_mark, ) } macro_rules! to { ($name:ident, $src:expr) => { test!( Default::default(), |_| ( resolver(Mark::new(), Mark::new(), false), inlining(Default::default()) ), $name, $src ); }; (ignore, $name:ident, $src:expr) => { test!( ignore, Default::default(), |_| ( resolver(Mark::new(), Mark::new(), false), inlining(Default::default()) ), $name, $src ); }; } macro_rules! identical { ($name:ident, $src:expr) => { to!($name, $src); }; } #[track_caller] fn test(src: &str, expected: &str) { swc_ecma_transforms_testing::test_transform( ::swc_ecma_parser::Syntax::default(), None, |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), inlining(Default::default()), ) }, src, expected, ) } /// Should not modify expression. fn test_same(s: &str) { test(s, s) } to!(top_level_simple_var, "var a = 1; var b = a;"); to!( function_scope_simple_var, "var a = 1; var b = a; use(b);" ); identical!(top_level_increment, "var x = 1; x++;"); identical!(top_level_decrement, "var x = 1; x--;"); identical!(top_level_assign_op, "var x = 1; x += 3;"); to!(simple_inline_in_fn, "var x = 1; var z = x; use(z)"); to!( ignore, unresolved_inline_in_fn, "var a = new obj(); result = a;" ); // GitHub issue #1234: https://github.com/google/closure-compiler/issues/1234 identical!( closure_compiler_1234, "var x; switch ('a') { case 'a': break; default: x = 1; break; } use(x);" ); to!( let_1, "function f(x) { if (true) { let y = x; y; y; } }" ); to!( const_1, "function f(x) { if (true) { const y = x; y; y; } }" ); to!( let_2, "let y; { let y = x; y; } y; " ); to!( let_const_1, " const g = 3; let y = g; y; " ); to!( let_const_2, "let y = x; y; const g = 2; { const g = 3; let y = g; y; } y; g; " ); to!(regex, "var b;b=/ab/;(b)?x=1:x=2;"); to!( generator_let_yield, "function* f() { let x = 1; yield x; }" ); // TODO: Inline single use identical!( generator_let_increment, "function* f(x) { let y = x++; yield y; }" ); identical!(for_of_1, "var i = 0; for(i of n) {}"); identical!(for_of_2, "for( var i of n) { var x = i; }"); to!(tpl_lit_1, "var name = 'Foo'; `Hello ${name}`"); to!( tpl_lit_2, "var name = 'Foo'; var foo = name; `Hello ${foo}`" ); to!(tpl_lit_3, "var age = 3; `Age: ${age}`"); to!( ignore, tagged_tpl_lit_1, concat!( "var name = 'Foo';", "function myTag(strings, nameExp, numExp) {", " var modStr;", " if (numExp > 2) {", " modStr = nameExp + 'Bar'", " } else { ", " modStr = nameExp + 'BarBar'", " }", "}", "var output = myTag`My name is ${name} ${3}`;", ) ); to!( tagged_tpl_lit_2, concat!( "var name = 'Foo';", "function myTag(strings, nameExp, numExp) {", " var modStr;", " if (numExp > 2) {", " modStr = nameExp + 'Bar'", " } else { ", " modStr = nameExp + 'BarBar'", " }", "}", "var output = myTag`My name is ${name} ${3}`;", "output = myTag`My name is ${name} ${2}`;", ) ); identical!( function_scope_var_1, "var x = 1; function foo(){ x = 2; } use(x); " ); identical!( function_scope_var_2, "(function(){ var x = 1; function foo(){ x = 2; } use(x); })();" ); identical!( top_level_does_not_inline_fn_decl, "function foo(){} use(foo);" ); to!( custom_loop_1, " let b = 2; let a = 1; if (b) { a = 2; } let c; if (a) { c = 3; } " ); to!( custom_loop_2, "let b = 2; let a = 1; a = 2; let c; if (a) c = 3" ); to!( custom_loop_3, "let c; c = 3; console.log(c);" ); #[test] fn test_pass_doesnt_produce_invalid_code1() { test_same(concat!( "function f(x = void 0) {", " var z;", " {", " const y = {};", " x && (y['x'] = x);", " z = y;", " }", " return z;", "}", )); } #[test] fn test_pass_doesnt_produce_invalid_code2() { test_same(concat!( "function f(x = void 0) {", " {", " var z;", " const y = {};", " x && (y['x'] = x);", " z = y;", " }", " return z;", "}", )); } #[test] fn test_pass_doesnt_produce_invalid_code3() { test( concat!( "function f(x = void 0) {", " var z;", " const y = {};", " x && (y['x'] = x);", " z = y;", " {", " return z;", " }", "}", ), concat!( "function f(x = void 0) {", " var z;", " const y = {};", " x && (y['x'] = x);", " z = y;", " {", " return y;", " }", "}", ), ); } // Test respect for scopes and blocks #[test] fn test_inline_global() { test("var x = 1; var z = x;", "var x; var z;"); } #[test] fn test_do_not_inline_increment() { test_same("var x = 1; x++;"); } #[test] fn test_do_not_inline_decrement() { test_same("var x = 1; x--;"); } #[test] fn test_do_not_inline_into_lhs_of_assign() { test_same("var x = 1; x += 3;"); } #[test] #[ignore] fn orig_test_inline_into_rhs_of_assign() { test("var x = foo(); var y = x;", "var x; var y = foo();"); } #[test] fn test_inline_into_rhs_of_assign() { test("var x = foo(); var y = x;", "var x = foo(); var y = x;"); } #[test] fn test_inline_in_function1() { test( "function baz() { var x = 1; var z = x; }", "function baz() { var x; var z; }", ); } #[test] #[ignore] fn test_inline_in_function2() { test( "function baz() { var a = new obj(); result = a; }", "function baz() { result = new obj() }", ); } #[test] fn test_inline_in_function3() { test_same("function baz() { var a = new obj(); (function(){a;})(); result = a; }"); } #[test] fn test_inline_in_function4() { test_same("function baz() { var a = new obj(); foo.result = a; }"); } #[test] fn test_inline_in_function5() { test( "function baz() { var a = (foo = new obj()); foo.x(); result = a; }", "function baz() { var a = foo = new obj(); foo.x(); result = a; }", ); } #[test] #[ignore] fn orig_test_inline_in_function6() { test( "function baz() { { var x = foo(); var z = x; } }", "function baz() { { var x; var z = foo(); } }", ); } #[test] fn test_inline_in_function6() { test( "function baz() { { var x = foo(); var z = x; } }", "function baz() { { var x = foo(); var z = x; } }", ); } #[test] fn test_inline_in_function7() { test( "function baz() { var x = 1; { var z = x; } }", "function baz() { var x; { var z; } }", ); } #[test] #[ignore] fn test_inline_into_arrow_function1() { test("var x = 0; var f = () => x + 1;", "var f = () => 0 + 1;"); } #[test] #[ignore] fn test_inline_into_arrow_function2() { test( "var x = 0; var f = () => { return x + 1; }", "var f = () => { return 0 + 1; }", ); } #[test] fn test_do_not_exit_conditional1() { test_same("if (true) { var x = 1; } var z = x;"); } #[test] fn test_do_not_exit_conditional2() { test_same("if (true) var x = 1; var z = x;"); } #[test] fn test_do_not_exit_conditional3() { test_same("var x; if (true) x=1; var z = x;"); } #[test] fn test_do_not_exit_loop() { test_same("while (z) { var x = 3; } var y = x;"); } #[test] #[ignore] fn orig_test_do_not_exit_for_loop() { test( "for (var i = 1; false; false) var z = i;", "for (;false;false) var z = 1;", ); test_same("for (; false; false) var i = 1; var z = i;"); test_same("for (var i in {}); var z = i;"); } #[test] fn test_do_not_exit_for_loop() { test( "for (var i = 1; false; false) var z = i;", "for (var i = 1;false;false) var z = i;", ); test_same("for (; false; false) var i = 1; var z = i;"); test_same("for (var i in {}); var z = i;"); } #[test] fn test_do_not_enter_subscope() { test_same(concat!( "var x = function() {", " var self = this; ", " return function() { var y = self; };", "}" )); test_same("var x = function() { var y = [1]; return function() { var z = y; }; }"); } #[test] fn test_do_not_exit_try() { test( "try { var x = y; } catch (e) {} var z = y; ", "try { var x = y; } catch (e) {} var z = y; ", ); test_same("try { throw e; var x = 1; } catch (e1) {} var z = x; "); } #[test] fn test_do_not_enter_catch() { test_same("try { } catch (e) { var z = e; } "); } #[test] fn test_do_not_enter_finally() { test_same("try { throw e; var x = 1; } catch (e1) {} finally { var z = x; } "); } #[test] #[ignore] fn orig_test_inside_if_conditional() { test( "var a = foo(); if (a) { alert(3); }", "var a; if (foo()) { alert(3); }", ); test( "var a; a = foo(); if (a) { alert(3); }", "var a; if (foo()) { alert(3); }", ); } #[test] fn test_inside_if_conditional() { test( "var a = foo(); if (a) { alert(3); }", "var a = foo(); if (a) { alert(3); }", ); test( "var a; a = foo(); if (a) { alert(3); }", "var a; a = foo(); if (a) { alert(3); }", ); } #[test] #[ignore] fn test_only_read_at_initialization() { test("var a; a = foo();", "foo();"); test( "var a; if (a = foo()) { alert(3); }", "if (foo()) { alert(3); }", ); test("var a; switch (a = foo()) {}", "switch(foo()) {}"); test( "var a; function f(){ return a = foo(); }", "function f(){ return foo(); }", ); test( "function f(){ var a; return a = foo(); }", "function f(){ return foo(); }", ); test( "var a; with (a = foo()) { alert(3); }", "with (foo()) { alert(3); }", ); test("var a; b = (a = foo());", "b = foo();"); test( "var a; while(a = foo()) { alert(3); }", "while(foo()) { alert(3); }", ); test( "var a; for(;a = foo();) { alert(3); }", "for(;foo();) { alert(3); }", ); test( "var a; do {} while(a = foo()) { alert(3); }", "do {} while(foo()) { alert(3); }", ); } #[test] #[ignore] fn test_immutable_with_single_reference_after_initialzation() { test("var a; a = 1;", "var a; a = 1;"); test("var a; if (a = 1) { alert(3); }", "if (1) { alert(3); }"); test("var a; switch (a = 1) {}", "switch(1) {}"); test( "var a; function f(){ return a = 1; }", "function f(){ return 1; }", ); test( "function f(){ var a; return a = 1; }", "function f(){ return 1; }", ); test( "var a; with (a = 1) { alert(3); }", "with (1) { alert(3); }", ); test("var a; b = (a = 1);", "b = 1;"); test( "var a; while(a = 1) { alert(3); }", "while(1) { alert(3); }", ); test( "var a; for(;a = 1;) { alert(3); }", "for(;1;) { alert(3); }", ); test( "var a; do {} while(a = 1) { alert(3); }", "do {} while(1) { alert(3); }", ); } #[test] #[ignore] fn test_single_reference_after_initialzation() { test("var a; a = foo();a;", "foo();"); test_same("var a; if (a = foo()) { alert(3); } a;"); test_same("var a; switch (a = foo()) {} a;"); test_same("var a; function f(){ return a = foo(); } a;"); test_same("function f(){ var a; return a = foo(); a;}"); test_same("var a; with (a = foo()) { alert(3); } a;"); test_same("var a; b = (a = foo()); a;"); test_same("var a; while(a = foo()) { alert(3); } a;"); test_same("var a; for(;a = foo();) { alert(3); } a;"); test_same("var a; do {} while(a = foo()) { alert(3); } a;"); } #[test] fn test_inside_if_branch() { test_same("var a = foo(); if (1) { alert(a); }"); } #[test] #[ignore] fn orig_test_inside_and_conditional() { test("var a = foo(); a && alert(3);", "foo() && alert(3);"); } #[test] fn test_inside_and_conditional() { test( "var a = foo(); a && alert(3);", "var a = foo(); a && alert(3);", ); } #[test] fn test_inside_and_branch() { test_same("var a = foo(); 1 && alert(a);"); } #[test] fn test_inside_or_branch() { test_same("var a = foo(); 1 || alert(a);"); } #[test] fn test_inside_hook_branch() { test_same("var a = foo(); 1 ? alert(a) : alert(3)"); } #[test] #[ignore] fn orig_test_inside_hook_conditional() { test( "var a = foo(); a ? alert(1) : alert(3)", "foo() ? alert(1) : alert(3)", ); } #[test] fn test_inside_hook_conditional() { test( "var a = foo(); a ? alert(1) : alert(3)", "var a = foo(); a ? alert(1) : alert(3)", ); } #[test] fn test_inside_or_branch_inside_if_conditional() { test_same("var a = foo(); if (x || a) {}"); } #[test] fn test_inside_or_branch_inside_if_conditional_with_constant() { // We don't inline non-immutable constants into branches. test_same("var a = [false]; if (x || a) {}"); } // Test movement of constant values #[test] #[ignore] fn test_do_cross_function() { // We know foo() does not affect x because we require that x is only // referenced twice. test("var x = 1; foo(); var z = x;", "foo(); var z = 1;"); } #[test] #[ignore] fn orig_test_do_not_cross_referencing_function() { test_same("var f = function() { var z = x; }; var x = 1; f(); var z = x; f();"); } #[test] fn test_do_not_cross_referencing_function() { test( "var f = function() { var z = foo(); }; var x = 1; f(); var z = x; f();", "var f = function() { var z = foo(); }; var x = 1; f(); var z = x; f();", ); } // Test tricky declarations and references #[test] fn test_chained_assignment() { test("var a = 2, b = 2; var c = b;", "var a, b; var c;"); test("var a = 2, b = 2; var c = a;", "var a, b; var c;"); test( "var a = b = 2; var f = 3; var c = a;", "var a; var f; var c = b = 2;", ); test_same("var a = b = 2; var c;"); } #[test] fn test_for_in() { test( "for (var i in j) { var c = i; }", "for (var i in j) { var c = i; }", ); test_same("var i = 0; for (i in j) ;"); test_same("var i = 0; for (i in j) { var c = i; }"); test_same("i = 0; for (var i in j) { var c = i; }"); test_same("var j = {'key':'value'}; for (var i in j) {print(i)};"); } // Test movement of values that have (may) side effects #[test] #[ignore] fn test_do_cross_new_variables() { test("var x = foo(); var z = x;", "var z = foo();"); } #[test] fn test_do_not_cross_function_calls() { test_same("var x = foo(); bar(); var z = x;"); } // Test movement of values that are complex but lack side effects #[test] fn test_do_not_cross_assignment() { test_same("var x = {}; var y = x.a; x.a = 1; var z = y;"); test_same("var a = this.id; foo(this.id = 3, a);"); } #[test] fn test_do_not_cross_delete() { test_same("var x = {}; var y = x.a; delete x.a; var z = y;"); } #[test] fn test_do_not_cross_assignment_plus() { test_same("var a = b; b += 2; var c = a;"); } #[test] fn test_do_not_cross_increment() { test_same("var a = b.c; b.c++; var d = a;"); } #[test] fn test_do_not_cross_constructor() { test_same("var a = b; new Foo(); var c = a;"); } #[test] #[ignore] fn test_do_cross_var() { // Assumes we do not rely on undefined variables (not technically correct!) test("var a = b; var b = 3; alert(a)", "alert(3);"); } #[test] #[ignore] fn test_overlapping_in_lines() { test( concat!( "a = function(el, x, opt_y) { ", " var cur = bar(el); ", " opt_y = x.y; ", " x = x.x; ", " var dx = x - cur.x; ", " var dy = opt_y - cur.y;", " foo(el, el.offsetLeft + dx, el.offsetTop + dy); ", "};" ), concat!( "a = function(el, x, opt_y) { ", " var cur = bar(el); ", " opt_y = x.y; ", " x = x.x; ", " foo(el, el.offsetLeft + (x - cur.x),", " el.offsetTop + (opt_y - cur.y)); ", "};" ), ); } #[test] #[ignore] fn test_inline_into_loops() { test( "var x = true; while (true) alert(x);", "var x; while (true) alert(true);", ); test( "var x = true; while (true) for (var i in {}) alert(x);", "var x; while (true) for (var i in {}) alert(true);", ); test_same("var x = [true]; while (true) alert(x);"); } #[test] #[ignore] fn test_inline_into_function() { test( "var x = false; var f = function() { alert(x); };", "var f = function() { alert(false); };", ); test_same("var x = [false]; var f = function() { alert(x); };"); } #[test] fn test_no_inline_into_named_function() { test_same("f(); var x = false; function f() { alert(x); };"); } #[test] #[ignore] fn test_inline_into_nested_non_hoisted_named_functions() { test( "f(); var x = false; if (false) function f() { alert(x); };", "f(); if (false) function f() { alert(false); };", ); } #[test] fn test_no_inline_into_nested_named_functions() { test_same("f(); var x = false; function f() { if (false) { alert(x); } };"); } #[test] fn test_no_inline_mutated_variable() { test_same("var x = false; if (true) { var y = x; x = true; }"); } #[test] fn test_inline_immutable_multiple_times() { test("var x = null; var y = x, z = x;", "var x; var y, z;"); test("var x = 3; var y = x, z = x;", "var x; var y, z;"); } #[test] fn test_inline_string_multiple_times_when_aliasing_all_strings() { test( "var x = 'abcdefghijklmnopqrstuvwxyz'; var y = x, z = x;", "var x; var y, z;", ); } #[test] fn test_no_inline_backwards() { test_same("var y = x; var x = foo();"); } #[test] fn test_no_inline_out_of_branch() { test_same("if (true) var x = foo(); var y = x;"); } #[test] #[ignore] fn orig_test_interfering_in_lines() { test( "var a = 3; var f = function() { var x = a; alert(x); };", "var a; var f = function() { var x; alert(3); };", ); } #[test] fn test_interfering_in_lines() { test( "var a = 3; var f = function() { var x = a; alert(x); };", "var a = 3; var f = function() { var x = a; alert(x); };", ); } #[test] #[ignore] fn test_inline_into_try_catch() { test( concat!( "var a = true; ", "try { var b = a; } ", "catch (e) { var c = a + b; var d = true; } ", "finally { var f = a + b + c + d; }" ), concat!( "try { var b = true; } ", "catch (e) { var c = true + b; var d = true; } ", "finally { var f = true + b + c + d; }" ), ); } // Make sure that we still inline constants that are not provably // written before they're read. #[test] fn test_inline_constants() { test( "function foo() { return XXX; } var XXX = true;", "function foo() { return XXX; } var XXX = true;", ); } #[test] fn test_inline_string_when_worthwhile() { test("var x = 'a'; foo(x, x, x);", "var x; foo('a', 'a', 'a');"); } #[test] fn test_inline_constant_alias() { test( "var XXX = new Foo(); q(XXX); var YYY = XXX; bar(YYY)", "var XXX = new Foo(); q(XXX); var YYY = XXX; bar(YYY)", ); } #[test] #[ignore] fn orig_test_inline_constant_alias_with_non_constant() { test( "var XXX = new Foo(); q(XXX); var y = XXX; bar(y); baz(y)", "var XXX = new Foo(); q(XXX); var y; bar(XXX); baz(XXX)", ); } #[test] fn test_inline_constant_alias_with_non_constant() { test( "var XXX = new Foo(); q(XXX); var y = XXX; bar(y); baz(y)", "var XXX = new Foo(); q(XXX); var y = XXX; bar(y); baz(y)", ); } #[test] #[ignore] fn orig_test_cascading_in_lines() { test( "var XXX = 4; function f() { var YYY = XXX; bar(YYY); baz(YYY); }", "var XXX; function f() { var YYY; bar(4); baz(4); }", ); } #[test] fn test_cascading_in_lines() { test( "var XXX = 4; function f() { var YYY = XXX; bar(YYY); baz(YYY); }", "var XXX = 4; function f() { var YYY = XXX; bar(YYY); baz(YYY); }", ); } #[test] fn test_no_inline_getprop_into_call_1() { test("var a = b; a();", "var a; b();"); } #[test] fn test_no_inline_getprop_into_call_2() { test("var a = b.c; f(a);", "var a; f(b.c);"); } #[test] fn test_no_inline_getprop_into_call_3() { test_same("var a = b.c; a();"); } #[test] #[ignore] fn test_inline_function_declaration() { test( "var f = function () {}; var a = f;", "var f; var a = function () {};", ); test( "var f = function () {}; foo(); var a = f;", "foo(); var a = function () {};", ); test("var f = function () {}; foo(f);", "foo(function () {});"); test_same("var f = function () {}; function g() {var a = f;}"); test_same("var f = function () {}; function g() {h(f);}"); } #[test] fn test_recursive_function1() { test( "var x = 0; (function x() { return x ? x() : 3; })();", "var x; (function x() { return x? x() : 3; })();", ); } #[test] fn test_recursive_function2() { test_same("function y() { return y(); }"); } #[test] fn test_unreferenced_bleeding_function() { test_same("var x = function y() {}"); } #[test] fn test_referenced_bleeding_function() { test_same("var x = function y() { return y(); }"); } #[test] #[ignore] fn test_inline_aliases1() { test( "var x = this.foo(); this.bar(); var y = x; this.baz(y);", "var x = this.foo(); this.bar(); var y; this.baz(x);", ); } #[test] #[ignore] fn test_inline_aliases1b() { test( "var x = this.foo(); this.bar(); var y; y = x; this.baz(y);", "var x = this.foo(); this.bar(); var y; x; this.baz(x);", ); } #[test] #[ignore] fn test_inline_aliases1c() { test( "var x; x = this.foo(); this.bar(); var y = x; this.baz(y);", "var x; x = this.foo(); this.bar(); var y; this.baz(x);", ); } #[test] #[ignore] fn test_inline_aliases1d() { test( "var x; x = this.foo(); this.bar(); var y; y = x; this.baz(y);", "var x; x = this.foo(); this.bar(); var y; x; this.baz(x);", ); } #[test] #[ignore] fn test_inline_aliases2() { test( "var x = this.foo(); this.bar(); function f() { var y = x; this.baz(y); }", "var x = this.foo(); this.bar(); function f() { var y; this.baz(x); }", ); } #[test] #[ignore] fn test_inline_aliases2b() { test( "var x = this.foo(); this.bar(); function f() { var y; y = x; this.baz(y); }", "var x = this.foo(); this.bar(); function f() { var y; x; this.baz(x); }", ); } #[test] #[ignore] fn test_inline_aliases2c() { test( "var x; x = this.foo(); this.bar(); function f() { var y = x; this.baz(y); }", "var x; x = this.foo(); this.bar(); function f() { var y = x; this.baz(x); }", ); } #[test] #[ignore] fn test_inline_aliases2d() { test( "var x; x = this.foo(); this.bar(); function f() { var y; y = x; this.baz(y); }", "var x; x = this.foo(); this.bar(); function f() { this.baz(x); }", ); } #[test] #[ignore] fn test_inline_aliases_in_loop() { test( concat!( "function f() { ", " var x = extern();", " for (var i = 0; i < 5; i++) {", " (function() {", " var y = x; window.setTimeout(function() { extern(y); }, 0);", " })();", " }", "}" ), concat!( "function f() { ", " var x = extern();", " for (var i = 0; i < 5; i++) {", " (function() {", " window.setTimeout(function() { extern(x); }, 0);", " })();", " }", "}" ), ); } #[test] fn test_no_inline_aliases_in_loop() { test_same(concat!( "function f() { ", " for (var i = 0; i < 5; i++) {", " var x = extern();", " (function() {", " var y = x; window.setTimeout(function() { extern(y); }, 0);", " })();", " }", "}" )); } #[test] fn modifier_test_no_inline_aliases1() { test( "var x = this.foo(); this.bar(); var y = x; x = 3; this.baz(y);", "var x = this.foo(); this.bar(); var y = x; x = 3; this.baz(y);", ); } #[test] fn test_no_inline_aliases1b() { test_same("var x = this.foo(); this.bar(); var y; y = x; x = 3; this.baz(y);"); } #[test] fn test_no_inline_aliases2() { test_same("var x = this.foo(); this.bar(); var y = x; y = 3; this.baz(y); "); } #[test] fn test_no_inline_aliases2b() { test_same("var x = this.foo(); this.bar(); var y; y = x; y = 3; this.baz(y); "); } #[test] fn test_no_inline_aliases3() { test_same(concat!( "var x = this.foo(); this.bar(); ", "function f() { var y = x; g(); this.baz(y); } ", "function g() { x = 3; }" )); } #[test] fn test_no_inline_aliases3b() { test_same(concat!( "var x = this.foo(); this.bar(); ", "function f() { var y; y = x; g(); this.baz(y); } ", "function g() { x = 3; }" )); } #[test] fn test_no_inline_aliases4() { test_same("var x = this.foo(); this.bar(); function f() { var y = x; y = 3; this.baz(y); }"); } #[test] fn test_no_inline_aliases4b() { test_same( "var x = this.foo(); this.bar(); function f() { var y; y = x; y = 3; this.baz(y); }", ); } #[test] fn test_no_inline_aliases5() { test_same("var x = this.foo(); this.bar(); var y = x; this.bing(); this.baz(y); x = 3;"); } #[test] fn test_no_inline_aliases5b() { test_same("var x = this.foo(); this.bar(); var y; y = x; this.bing(); this.baz(y); x = 3;"); } #[test] fn test_no_inline_aliases6() { test_same("var x = this.foo(); this.bar(); var y = x; this.bing(); this.baz(y); y = 3;"); } #[test] fn test_no_inline_aliases6b() { test_same("var x = this.foo(); this.bar(); var y; y = x; this.bing(); this.baz(y); y = 3;"); } #[test] fn test_no_inline_aliases7() { test_same(concat!( "var x = this.foo(); this.bar(); ", "function f() { var y = x; this.bing(); this.baz(y); x = 3; }" )); } #[test] fn test_no_inline_aliases7b() { test_same(concat!( "var x = this.foo(); this.bar(); ", "function f() { var y; y = x; this.bing(); this.baz(y); x = 3; }" )); } #[test] fn test_no_inline_aliases8() { test_same("var x = this.foo(); this.bar(); function f() { var y = x; this.baz(y); y = 3; }"); } #[test] fn test_no_inline_aliases8b() { test_same( "var x = this.foo(); this.bar(); function f() { var y; y = x; this.baz(y); y = 3; }", ); } #[test] fn test_inline_parameter_alias1() { test( "function f(x) { var y = x; g(); y;y; }", "function f(x) { var y; g(); x;x; }", ); } #[test] #[ignore] fn test_inline_parameter_alias2() { test( "function f(x) { var y; y = x; g(); y;y; }", "function f(x) { x; g(); x;x; }", ); } #[test] #[ignore] fn orig_test_inline_function_alias1a() { test( "function f(x) {} var y = f; g(); y();y();", "var y = function f(x) {}; g(); y();y();", ); } #[test] fn test_inline_function_alias1a() { test( "function f(x) {} var y = f; g(); y();y();", "function f(x) {} var y; g(); f();f();", ); } #[test] fn test_inline_function_alias1b() { test( "function f(x) {}; f;var y = f; g(); y();y();", "function f(x) {}; f; var y; g(); f();f();", ); } #[test] fn test_inline_function_alias2a() { test( "function f(x) {} var y; y = f; g(); y();y();", "function f(x) {} var y; y = f; g(); f();f();", ); } #[test] fn test_inline_function_alias2b() { test( "function f(x) {}; f; var y; y = f; g(); y();y();", "function f(x) {}; f; var y; y = f; g(); f();f();", ); } #[test] fn test_inline_switch_var() { test("var x = y; switch (x) {}", "var x; switch (y) {}"); } #[test] fn test_inline_switch_let() { test("let x = y; switch (x) {}", "let x; switch (y) {}"); } // Successfully inlines 'values' and 'e' #[test] #[ignore] fn test_inline_into_for_loop1() { test( concat!( "function calculate_hashCode() {", " var values = [1, 2, 3, 4, 5];", " var hashCode = 1;", " for (var $array = values, i = 0; i < $array.length; i++) {", " var e = $array[i];", " hashCode = 31 * hashCode + calculate_hashCode(e);", " }", " return hashCode;", "}", ), concat!( "function calculate_hashCode() {", " var hashCode = 1;", " var $array = [1, 2, 3, 4, 5];", " var i = 0;", " for (; i < $array.length; i++) {", " hashCode = 31 * hashCode + calculate_hashCode($array[i]);", " }", " return hashCode;", "}", ), ); } // Inlines 'e' but fails to inline 'values' // TODO(tbreisacher): Investigate and see if we can improve this. #[test] fn test_inline_into_for_loop2() { test( concat!( "function calculate_hashCode() {", " let values = [1, 2, 3, 4, 5];", " let hashCode = 1;", " for (let $array = values, i = 0; i < $array.length; i++) {", " let e = $array[i];", " hashCode = 31 * hashCode + calculate_hashCode(e);", " }", " return hashCode;", "}", ), concat!( "function calculate_hashCode() {", " let values = [1, 2, 3, 4, 5];", " let hashCode = 1;", " for (let $array = values, i = 0; i < $array.length; i++) {", " let e = $array[i];", " hashCode = 31 * hashCode + calculate_hashCode(e);", " }", " return hashCode;", "}", ), ); } // This used to be inlined, but regressed when we switched to the ES6 scope // creator. #[test] fn test_no_inline_catch_alias_var1() { test_same(concat!( "try {", "} catch (e) {", " var y = e;", " g();", " y;y;", "}", )); } // This used to be inlined, but regressed when we switched to the ES6 scope // creator. #[test] fn test_no_inline_catch_alias_var2() { test_same(concat!( "try {", "} catch (e) {", " var y; y = e;", " g();", " y;y;", "}", )); } #[test] #[ignore] fn test_inline_catch_alias_let1() { test( concat!( "try {", "} catch (e) {", " let y = e;", " g();", " y;y;", "}", ), concat!("try {", "} catch (e) {", " g();", " e;e;", "}"), ); } #[test] #[ignore] fn test_inline_catch_alias_let2() { test( concat!( "try {", "} catch (e) {", " let y; y = e;", " g();", " y;y;", "}", ), concat!("try {", "} catch (e) {", " e;", " g();", " e;e;", "}"), ); } #[test] #[ignore] fn test_inline_this() { test( concat!( "/** @constructor */", "function C() {}", "", "C.prototype.m = function() {", " var self = this;", " if (true) {", " alert(self);", " }", "};", ), concat!( "(/** @constructor */", "function C() {}).prototype.m = function() {", " if (true) {", " alert(this);", " }", "};", ), ); } #[test] fn test_var_in_block1() { test( "function f(x) { if (true) {var y = x; y; y;} }", "function f(x) { if (true) {var y; x; x;} }", ); } #[test] fn test_var_in_block2() { test( "function f(x) { switch (0) { case 0: { var y = x; y; y; } } }", "function f(x) { switch (0) { case 0: { var y; x; x; } } }", ); } #[test] fn test_inline_undefined1() { test("var x; x;", "var x; void 0;"); } #[test] fn test_inline_undefined2() { test_same("var x; x++;"); } #[test] fn test_inline_undefined3() { test_same("var x; var x;"); } #[test] fn test_inline_undefined4() { test("var x; x; x;", "var x; void 0; void 0;"); } #[test] fn test_inline_undefined5() { test_same("var x; for(x in a) {}"); } #[test] fn test_issue90() { test("var x; x && alert(1)", "var x; (void 0) && alert(1)"); } #[test] #[ignore] fn test_this_alias() { test( "function f() { var a = this; a.y(); a.z(); }", "function f() { this.y(); this.z(); }", ); } #[test] fn test_this_escaped_alias() { test_same("function f() { var a = this; var g = function() { a.y(); }; a.z(); }"); } #[test] #[ignore] fn test_inline_named_function() { test("function f() {} f();", "(function f(){})()"); } #[test] fn test_issue378_modified_arguments1() { test_same(concat!( "function g(callback) {\n", " var f = callback;\n", " arguments[0] = this;\n", " f.apply(this, arguments);\n", "}" )); } #[test] fn test_issue378_modified_arguments2() { test_same(concat!( "function g(callback) {\n", " /** @const */\n", " var f = callback;\n", " arguments[0] = this;\n", " f.apply(this, arguments);\n", "}" )); } #[test] fn test_issue378_escaped_arguments1() { test_same(concat!( "function g(callback) {\n", " var f = callback;\n", " h(arguments,this);\n", " f.apply(this, arguments);\n", "}\n", "function h(a,b) {\n", " a[0] = b;", "}" )); } #[test] fn test_issue378_escaped_arguments2() { test_same(concat!( "function g(callback) {\n", " /** @const */\n", " var f = callback;\n", " h(arguments,this);\n", " f.apply(this);\n", "}\n", "function h(a,b) {\n", " a[0] = b;", "}" )); } #[test] #[ignore] // We just give up optimization when arguments is used fn test_issue378_escaped_arguments3() { test( concat!( "function g(callback) {\n", " var f = callback;\n", " f.apply(this, arguments);\n", "}\n" ), "function g(callback) {\n callback.apply(this, arguments);\n }\n", ); } #[test] fn test_issue378_escaped_arguments4() { test_same(concat!( "function g(callback) {\n", " var f = callback;\n", " h(arguments[0],this);\n", " f.apply(this, arguments);\n", "}\n", "function h(a,b) {\n", " a[0] = b;", "}" )); } #[test] #[ignore] // We just give up optimization when arguments is used fn test_issue378_arguments_read1() { test( concat!( "function g(callback) {\n", " var f = callback;\n", " var g = arguments[0];\n", " f.apply(this, arguments);\n", "}" ), concat!( "function g(callback) {\n", " var g = arguments[0];\n", " callback.apply(this, arguments);\n", "}" ), ); } #[test] #[ignore] // We just give up optimization when arguments is used fn test_issue378_arguments_read2() { test( concat!( "function g(callback) {\n", " var f = callback;\n", " h(arguments[0],this);\n", " f.apply(this, arguments[0]);\n", "}\n", "function h(a,b) {\n", " a[0] = b;", "}" ), concat!( "function g(callback) {\n", " h(arguments[0],this);\n", " callback.apply(this, arguments[0]);\n", "}\n", "function h(a,b) {\n", " a[0] = b;", "}" ), ); } #[test] #[ignore] // We just give up optimization when arguments is used fn test_arguments_modified_in_outer_function() { test( concat!( "function g(callback) {\n", " var f = callback;\n", " arguments[0] = this;\n", " f.apply(this, arguments);\n", " function inner(callback) {", " var x = callback;\n", " x.apply(this);\n", " }", "}" ), concat!( "function g(callback) {\n", " var f = callback;\n", " arguments[0] = this;\n", " f.apply(this, arguments);\n", " function inner(callback) {", " callback.apply(this);\n", " }", "}" ), ); } #[test] #[ignore] // We just give up optimization when arguments is used fn test_arguments_modified_in_inner_function() { test( concat!( "function g(callback) {\n", " var f = callback;\n", " f.apply(this, arguments);\n", " function inner(callback) {", " var x = callback;\n", " arguments[0] = this;\n", " x.apply(this);\n", " }", "}" ), concat!( "function g(callback) {\n", " callback.apply(this, arguments);\n", " function inner(callback1) {", " var x = callback1;\n", " arguments[0] = this;\n", " x.apply(this);\n", " }", "}" ), ); } #[test] fn test_bug6598844() { test_same(concat!( "function F() { this.a = 0; }", "F.prototype.inc = function() { this.a++; return 10; };", "F.prototype.bar = function() { var x = this.inc(); this.a += x; };" )); } #[test] fn test_external_issue1053() { test_same("var u; function f() { u = Random(); var x = u; f(); alert(x===u)}"); } #[test] #[ignore] fn test_hoisted_function1() { test( "var x = 1; function f() { return x; }", "var x; function f() { return 1; }", ); } #[test] fn test_hoisted_function2() { test_same(concat!( "var impl_0;", "b(a());", "function a() { impl_0 = {}; }", "function b() { window['f'] = impl_0; }" )); } #[test] fn test_hoisted_function3() { test_same("var impl_0; b(); impl_0 = 1; function b() { window['f'] = impl_0; }"); } #[test] #[ignore] fn test_hoisted_function4() { test( "var impl_0; impl_0 = 1; b(); function b() { window['f'] = impl_0; }", "var impl_0; 1; b(); function b() { window['f'] = 1; }", ); } #[test] fn test_hoisted_function5() { test_same("a(); var debug = 1; function b() { return debug; } function a() { return b(); }"); } #[test] #[ignore] fn test_hoisted_function6() { test( concat!( "var debug = 1;", "a();", "function b() { return debug; }", "function a() { return b(); }" ), "var debug; a(); function b() { return 1; } function a() { return b(); }", ); } #[test] #[ignore] fn orig_test_issue354() { test( concat!( "var enabled = true;", "function Widget() {}", "Widget.prototype = {", " frob: function() {", " search();", " }", "};", "function search() {", " if (enabled)", " alert(1);", " else", " alert(2);", "}", "window.foo = new Widget();", "window.bar = search;" ), concat!( "var enabled;", "function Widget() {}", "Widget.prototype = {", " frob: function() {", " search();", " }", "};", "function search() {", " if (true)", " alert(1);", " else", " alert(2);", "}", "window.foo = new Widget();", "window.bar = search;" ), ); } #[test] fn test_issue354() { test( concat!( "var enabled = true;", "function Widget() {}", "Widget.prototype = {", " frob: function() {", " search();", " }", "};", "function search() {", " if (enabled)", " alert(1);", " else", " alert(2);", "}", "window.foo = new Widget();", "window.bar = search;" ), concat!( "var enabled = true;", "function Widget() {}", "Widget.prototype = {", " frob: function() {", " search();", " }", "};", "function search() {", " if (enabled)", " alert(1);", " else", " alert(2);", "}", "window.foo = new Widget();", "window.bar = search;" ), ); } // Test respect for scopes and blocks #[test] #[ignore] fn orig_test_issue1177() { test_same("function x_64(){var x_7;for(;;);var x_68=x_7=x_7;}"); test_same("function x_64(){var x_7;for(;;);var x_68=x_7=x_7++;}"); test_same("function x_64(){var x_7;for(;;);var x_68=x_7=x_7*2;}"); } // GitHub issue #1234: https://github.com/google/closure-compiler/issues/1234 #[test] fn test_switch_github_issue1234() { test_same(concat!( "var x;", "switch ('a') {", " case 'a':", " break;", " default:", " x = 1;", " break;", "}", "use(x);", )); } #[test] fn test_let_const() { test( concat!( "function f(x) {", " if (true) {", " let y = x; y; y;", " }", "}", ), concat!( "function f(x) {", " if (true) { ", " let y;", " x; x;", " }", "}" ), ); test( concat!( "function f(x) {", " if (true) {", " const y = x; y; y;", " }", " }", ), concat!( "function f(x) {", " if (true) {", " const y = x;", " x; x;", " }", "}" ), ); test( concat!( "function f(x) {", " let y;", " {", " let y = x; y;", " }", "}", ), concat!( "function f(x) {", " let y;", " { let y;", " x;", " }", "}" ), ); test( concat!( "function f(x) {", " let y = x; y; const g = 2; ", " {", " const g = 3; let y = g; y;", " }", "}", ), concat!( "function f(x) {", " let y; ", " x; const g = 2;", " { const g = 3; let y; 3;}", "}" ), ); } #[test] #[ignore] fn test_generators() { test( concat!("function* f() {", " let x = 1;", " yield x;", "}"), concat!("function* f() {", " let x;", " yield 1;", "}"), ); test( concat!("function* f(x) {", " let y = x++", " yield y;", "}"), concat!("function* f(x) {", " yield x++;", "}"), ); } #[test] fn test_template_strings() { test( " var name = 'Foo'; `Hello ${name}`", "var name;`Hello ${'Foo'}`", ); test( " var name = 'Foo'; var foo = name; `Hello ${foo}`", "var name; var foo; `Hello ${'Foo'}`", ); test(" var age = 3; `Age: ${age}`", "var age; `Age: ${3}`"); } #[test] #[ignore] fn test_tagged_template_literals() { test( concat!( "var name = 'Foo';", "function myTag(strings, nameExp, numExp) {", " var modStr;", " if (numExp > 2) {", " modStr = nameExp + 'Bar'", " } else { ", " modStr = nameExp + 'BarBar'", " }", "}", "var output = myTag`My name is ${name} ${3}`;", ), concat!( "var output = function myTag(strings, nameExp, numExp) {", " var modStr;", " if (numExp > 2) {", " modStr = nameExp + 'Bar'", " } else { ", " modStr = nameExp + 'BarBar'", " }", "}`My name is ${'Foo'} ${3}`;", ), ); test( concat!( "var name = 'Foo';", "function myTag(strings, nameExp, numExp) {", " var modStr;", " if (numExp > 2) {", " modStr = nameExp + 'Bar'", " } else { ", " modStr = nameExp + 'BarBar'", " }", "}", "var output = myTag`My name is ${name} ${3}`;", "output = myTag`My name is ${name} ${2}`;", ), concat!( "function myTag(strings, nameExp, numExp) {", " var modStr;", " if (numExp > 2) {", " modStr = nameExp + 'Bar'", " } else { ", " modStr = nameExp + 'BarBar'", " }", "}", "var output = myTag`My name is ${'Foo'} ${3}`;", "output = myTag`My name is ${'Foo'} ${2}`;", ), ); } test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::fresh(Mark::root()); ( resolver(unresolved_mark, top_level_mark, false), simple_strip(unresolved_mark, top_level_mark), class_properties( class_properties::Config { set_public_fields: true, ..Default::default() }, unresolved_mark, ), inlining(Default::default()), ) }, issue_1156_1, " export interface D { resolve: any; reject: any; } export function d(): D { let methods; const promise = new Promise((resolve, reject) => { methods = { resolve, reject }; }); return Object.assign(promise, methods); } " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), simple_strip(unresolved_mark, top_level_mark), class_properties( class_properties::Config { set_public_fields: true, ..Default::default() }, unresolved_mark, ), inlining(Default::default()), ) }, issue_1156_2, " interface D { resolve: any; reject: any; } function d(): D { let methods; const promise = new Promise((resolve, reject) => { methods = { resolve, reject }; }); return Object.assign(promise, methods); } class A { private s: D = d(); a() { this.s.resolve(); } b() { this.s = d(); } } new A(); " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), simple_strip(unresolved_mark, top_level_mark), inlining(Default::default()), ) }, deno_8180_1, r#" var Status; (function (Status) { Status[Status["Continue"] = 100] = "Continue"; Status[Status["SwitchingProtocols"] = 101] = "SwitchingProtocols"; })(Status || (Status = {})); const STATUS_TEXT = new Map([ [ Status.Continue, "Continue" ], [ Status.SwitchingProtocols, "Switching Protocols" ] ]); "# ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), simple_strip(unresolved_mark, top_level_mark), inlining(Default::default()), ) }, deno_8189_1, " let A, I = null; function g() { return null !== I && I.buffer === A.memory.buffer || (I = new \ Uint8Array(A.memory.buffer)), I } " );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_proposal/scripts/split-decorator-tests.mjs
JavaScript
import typescript from 'typescript' import fs from 'fs' import module from 'module' const require = module.createRequire(import.meta.url) const ts = fs.readFileSync('./tests/decorator-tests/decorator-tests.ts', 'utf8') // Convert TypeScript to JavaScript for testing JavaScript VMs console.log('Converting TypeScript to JavaScript...') const program = typescript.createProgram({ rootNames: ['./tests/decorator-tests/decorator-tests.ts'], options: { target: typescript.ScriptTarget.ESNext } }); // console.log('program', program) const mainFile = program.getSourceFile('./tests/decorator-tests/decorator-tests.ts') // console.log('mainFile', mainFile) const testVarStmt = mainFile.statements.find((s) => s.kind === typescript.SyntaxKind.VariableStatement) // console.log('testVarStmt', testVarStmt) const testVarDecl = testVarStmt.declarationList.declarations[0] // console.log('testVarDecl', testVarDecl) const properties = testVarDecl.initializer.properties // console.log('properties', properties) fs.rmdirSync(`tests/decorator-evanw-split`, { recursive: true }); fs.mkdirSync(`tests/decorator-evanw-split`, { recursive: true }); for (const property of properties) { let name = property.name.getText(mainFile) const value = property.initializer.getText(mainFile) name = name.replace(/['\(\)"']+/g, '').replace(/[\:; ]+/g, '-') // console.log('name', name) // console.log('value', value) const code = `(${value})()`; const transpiiled = typescript.transpile(code, { target: typescript.ScriptTarget.ESNext }) fs.writeFileSync(`tests/decorator-evanw-split/${name}.js`, transpiiled) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs
Rust
use swc_ecma_ast::Pass; use crate::{decorator_impl::decorator_impl, DecoratorVersion}; pub fn decorator_2022_03() -> impl Pass { decorator_impl(DecoratorVersion::V202203) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_proposal/src/decorator_impl.rs
Rust
use std::{collections::VecDeque, iter::once, mem::take}; use rustc_hash::FxHashMap; use swc_atoms::Atom; use swc_common::{util::take::Take, Mark, Spanned, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::{helper, helper_expr}; use swc_ecma_utils::{ alias_ident_for, constructor::inject_after_super, default_constructor_with_span, is_maybe_branch_directive, private_ident, prop_name_to_expr_value, quote_ident, replace_ident, stack_size::maybe_grow_default, ExprFactory, IdentRenamer, }; use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; use crate::DecoratorVersion; pub(crate) fn decorator_impl(version: DecoratorVersion) -> impl Pass { visit_mut_pass(DecoratorPass { version, ..Default::default() }) } #[derive(Default)] struct DecoratorPass { /// Variables without initializer. extra_vars: Vec<VarDeclarator>, extra_lets: Vec<VarDeclarator>, state: ClassState, /// Prepended before the class pre_class_inits: Vec<Box<Expr>>, rename_map: FxHashMap<Id, Id>, extra_exports: Vec<ExportSpecifier>, #[allow(unused)] version: DecoratorVersion, } #[derive(Default)] struct ClassState { private_id_index: u32, static_lhs: Vec<Ident>, proto_lhs: Vec<Ident>, /// If not empty, `initProto` should be injected to the constructor. init_proto: Option<Ident>, init_proto_args: Vec<Option<ExprOrSpread>>, init_static: Option<Ident>, init_static_args: Vec<Option<ExprOrSpread>>, /// Injected into static blocks. extra_stmts: Vec<Stmt>, class_lhs: Vec<Option<Pat>>, class_decorators: Vec<Option<ExprOrSpread>>, super_class: Option<Ident>, } impl DecoratorPass { fn preserve_side_effect_of_decorators( &mut self, decorators: Vec<Decorator>, ) -> Vec<Option<ExprOrSpread>> { decorators .into_iter() .map(|e| Some(self.preserve_side_effect_of_decorator(e.expr).as_arg())) .collect() } fn preserve_side_effect_of_decorator(&mut self, dec: Box<Expr>) -> Box<Expr> { if dec.is_ident() || dec.is_arrow() || dec.is_fn_expr() { return dec; } let ident = private_ident!("_dec"); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: ident.clone().into(), init: None, definite: false, }); self.pre_class_inits.push( AssignExpr { span: DUMMY_SP, op: op!("="), left: ident.clone().into(), right: dec, } .into(), ); ident.into() } /// Moves `cur_inits` to `extra_stmts`. fn consume_inits(&mut self) { if self.state.init_proto_args.is_empty() && self.state.init_static_args.is_empty() && self.state.init_proto.is_none() && self.state.init_static.is_none() && self.state.class_decorators.is_empty() { return; } let mut e_lhs = Vec::new(); let mut combined_args = vec![ThisExpr { span: DUMMY_SP }.as_arg()]; for id in self .state .static_lhs .drain(..) .chain(self.state.proto_lhs.drain(..)) { e_lhs.push(Some(id.into())); } if let Some(init) = self.state.init_proto.clone() { self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: init.clone().into(), init: None, definite: false, }); e_lhs.push(Some(init.into())); } if let Some(init) = self.state.init_static.clone() { self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: init.clone().into(), init: None, definite: false, }); e_lhs.push(Some(init.into())); } combined_args.push( ArrayLit { span: DUMMY_SP, elems: self .state .init_static_args .drain(..) .chain(self.state.init_proto_args.drain(..)) .collect(), } .as_arg(), ); combined_args.push( ArrayLit { span: DUMMY_SP, elems: self.state.class_decorators.take(), } .as_arg(), ); if let Some(super_class) = self.state.super_class.as_ref() { combined_args.push(super_class.clone().as_arg()); } let e_pat = if e_lhs.is_empty() { None } else { Some(ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident("e".into()), value: ArrayPat { span: DUMMY_SP, elems: e_lhs, type_ann: Default::default(), optional: false, } .into(), })) }; let c_pat = if self.state.class_lhs.is_empty() { None } else { Some(ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident("c".into()), value: ArrayPat { span: DUMMY_SP, elems: self.state.class_lhs.take(), type_ann: Default::default(), optional: false, } .into(), })) }; let expr = AssignExpr { span: DUMMY_SP, op: op!("="), left: ObjectPat { span: DUMMY_SP, props: e_pat.into_iter().chain(c_pat).collect(), optional: false, type_ann: None, } .into(), right: Box::new( CallExpr { span: DUMMY_SP, callee: helper!(apply_decs_2203_r), args: combined_args, ..Default::default() } .into(), ), } .into(); self.state.extra_stmts.push( ExprStmt { span: DUMMY_SP, expr, } .into(), ); if let Some(init) = self.state.init_static.take() { self.state.extra_stmts.push( ExprStmt { span: DUMMY_SP, expr: CallExpr { span: DUMMY_SP, callee: init.as_callee(), args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], ..Default::default() } .into(), } .into(), ); } } /// Returns (name, initilaizer_name) fn initializer_name(&mut self, name: &mut PropName, prefix: &str) -> (Box<Expr>, Ident) { match name { PropName::Ident(i) => ( Lit::Str(Str { span: i.span, value: i.sym.clone(), raw: None, }) .into(), Ident::new( format!("_{prefix}_{}", i.sym).into(), i.span, SyntaxContext::empty().apply_mark(Mark::new()), ), ), PropName::Computed(c) if c.expr.is_ident() => match &*c.expr { Expr::Ident(i) => ( i.clone().into(), Ident::new( format!("_{prefix}_{}", i.sym).into(), i.span, SyntaxContext::empty().apply_mark(Mark::new()), ), ), _ => { unreachable!() } }, _ => { let key_ident = private_ident!(name.span(), "_computedKey"); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: key_ident.clone().into(), init: None, definite: false, }); self.pre_class_inits.push( AssignExpr { span: DUMMY_SP, op: op!("="), left: key_ident.clone().into(), right: Box::new(prop_name_to_expr_value(name.take())), } .into(), ); *name = PropName::Computed(ComputedPropName { span: DUMMY_SP, expr: key_ident.clone().into(), }); let init = Ident::new( format!("_{prefix}_computedKey").into(), key_ident.span, SyntaxContext::empty().apply_mark(Mark::new()), ); (key_ident.into(), init) } } } fn ensure_constructor<'a>(&mut self, c: &'a mut Class) -> &'a mut Constructor { let mut insert_index = 0; for (i, member) in c.body.iter().enumerate() { if let ClassMember::Constructor(constructor) = member { // decorators occur before typescript's type strip, so skip ctor overloads if constructor.body.is_some() { if let Some(ClassMember::Constructor(c)) = c.body.get_mut(i) { return c; } else { unreachable!() } } else { insert_index = i + 1; } } } c.body.insert( insert_index, default_constructor_with_span(c.super_class.is_some(), c.span).into(), ); if let Some(ClassMember::Constructor(c)) = c.body.get_mut(insert_index) { c } else { unreachable!() } } fn ensure_identity_constructor<'a>(&mut self, c: &'a mut Class) -> &'a mut Constructor { let mut insert_index = 0; for (i, member) in c.body.iter().enumerate() { if let ClassMember::Constructor(constructor) = member { // decorators occur before typescript's type strip, so skip ctor overloads if constructor.body.is_some() { if let Some(ClassMember::Constructor(c)) = c.body.get_mut(i) { return c; } else { unreachable!() } } else { insert_index = i + 1; } } } c.body.insert( insert_index, ClassMember::Constructor(Constructor { span: DUMMY_SP, key: PropName::Ident("constructor".into()), params: Vec::new(), body: Some(BlockStmt { span: DUMMY_SP, stmts: Vec::new(), ..Default::default() }), ..Default::default() }), ); if let Some(ClassMember::Constructor(c)) = c.body.get_mut(insert_index) { c } else { unreachable!() } } fn handle_super_class(&mut self, class: &mut Class) { if let Some(super_class) = class.super_class.take() { let id = alias_ident_for(&super_class, "_super"); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: id.clone().into(), init: None, definite: false, }); class.super_class = Some( AssignExpr { span: DUMMY_SP, op: AssignOp::Assign, left: id.clone().into(), right: super_class, } .into(), ); self.state.super_class = Some(id); } } fn handle_class_expr(&mut self, class: &mut Class, ident: Option<&Ident>) -> Ident { debug_assert!( !class.decorators.is_empty(), "handle_class_decorator should be called only when decorators are present" ); let init_class = private_ident!("_initClass"); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: init_class.clone().into(), init: None, definite: false, }); let new_class_name = ident.as_ref().map_or_else( || private_ident!("_class"), |i| private_ident!(format!("_{}", i.sym)), ); if let Some(ident) = ident { replace_ident(&mut class.body, ident.to_id(), &new_class_name); } self.state .class_lhs .push(Some(new_class_name.clone().into())); self.state.class_lhs.push(Some(init_class.clone().into())); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: new_class_name.clone().into(), init: None, definite: false, }); let decorators = self.preserve_side_effect_of_decorators(class.decorators.take()); self.state.class_decorators.extend(decorators); self.handle_super_class(class); { let call_stmt = CallExpr { span: DUMMY_SP, callee: init_class.as_callee(), args: Vec::new(), ..Default::default() } .into_stmt(); class.body.push(ClassMember::StaticBlock(StaticBlock { span: DUMMY_SP, body: BlockStmt { span: DUMMY_SP, stmts: vec![call_stmt], ..Default::default() }, })); } new_class_name } // This function will call `visit` internally. fn handle_class_decl(&mut self, c: &mut ClassDecl) -> Stmt { let old_state = take(&mut self.state); let decorators = self.preserve_side_effect_of_decorators(c.class.decorators.take()); let init_class = private_ident!("_initClass"); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: init_class.clone().into(), init: None, definite: false, }); let preserved_class_name = c.ident.clone().into_private(); let new_class_name = private_ident!(format!("_{}", c.ident.sym)); self.extra_lets.push(VarDeclarator { span: DUMMY_SP, name: new_class_name.clone().into(), init: None, definite: false, }); self.rename_map .insert(c.ident.to_id(), new_class_name.to_id()); self.state .class_lhs .push(Some(new_class_name.clone().into())); self.state.class_lhs.push(Some(init_class.clone().into())); self.state.class_decorators.extend(decorators); self.handle_super_class(&mut c.class); let mut body = c.class.body.take(); let has_static_member = body.iter().any(|m| match m { ClassMember::Method(m) => m.is_static, ClassMember::PrivateMethod(m) => m.is_static, ClassMember::AutoAccessor(m) => m.is_static, ClassMember::ClassProp(ClassProp { is_static, .. }) | ClassMember::PrivateProp(PrivateProp { is_static, .. }) => *is_static, ClassMember::StaticBlock(_) => true, _ => false, }); if has_static_member { let mut last_static_block = None; self.process_decorators_of_class_members(&mut body); // Move static blocks into property initializers for m in body.iter_mut() { match m { ClassMember::ClassProp(ClassProp { value, .. }) | ClassMember::PrivateProp(PrivateProp { value, .. }) => { if let Some(value) = value { if let Some(last_static_block) = last_static_block.take() { **value = SeqExpr { span: DUMMY_SP, exprs: vec![ Box::new(Expr::Call(CallExpr { span: DUMMY_SP, callee: ArrowExpr { span: DUMMY_SP, params: Vec::new(), body: Box::new(BlockStmtOrExpr::BlockStmt( BlockStmt { span: DUMMY_SP, stmts: last_static_block, ..Default::default() }, )), is_async: false, is_generator: false, ..Default::default() } .as_callee(), args: Vec::new(), ..Default::default() })), value.take(), ], } .into() } } } ClassMember::StaticBlock(s) => match &mut last_static_block { None => { last_static_block = Some(s.body.stmts.take()); } Some(v) => { v.append(&mut s.body.stmts); } }, _ => {} } } // Drop static blocks body.retain(|m| !matches!(m, ClassMember::StaticBlock(..) | ClassMember::Empty(..))); for m in body.iter_mut() { match m { ClassMember::ClassProp(..) | ClassMember::PrivateProp(..) | ClassMember::AutoAccessor(..) => { replace_ident(m, c.ident.to_id(), &new_class_name); } _ => {} } } let mut inner_class = ClassDecl { ident: c.ident.clone(), declare: Default::default(), class: Box::new(Class { span: DUMMY_SP, decorators: Vec::new(), body, super_class: c.class.super_class.take(), ..Default::default() }), }; inner_class.class.visit_mut_with(self); for m in inner_class.class.body.iter_mut() { let mut should_move = false; match m { ClassMember::PrivateProp(p) => { if p.is_static { should_move = true; p.is_static = false; } } ClassMember::PrivateMethod(p) => { if p.is_static { should_move = true; p.is_static = false; } } ClassMember::AutoAccessor(p) => { if p.is_static { should_move = true; p.is_static = false; } } _ => (), } if should_move { c.class.body.push(m.take()) } } c.class.body.insert( 0, ClassMember::StaticBlock(StaticBlock { span: DUMMY_SP, body: BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::Decl(Decl::Class(inner_class))], ..Default::default() }, }), ); replace_ident(&mut c.class, c.ident.to_id(), &preserved_class_name); { let constructor = self.ensure_identity_constructor(&mut c.class); let super_call = CallExpr { span: DUMMY_SP, callee: Callee::Super(Super { span: DUMMY_SP }), args: vec![c.ident.clone().as_arg()], ..Default::default() } .into(); let static_call = last_static_block.map(|last| { CallExpr { span: DUMMY_SP, callee: ArrowExpr { span: DUMMY_SP, params: Vec::new(), body: Box::new(BlockStmtOrExpr::BlockStmt(BlockStmt { span: DUMMY_SP, stmts: last, ..Default::default() })), is_async: false, is_generator: false, ..Default::default() } .as_callee(), args: Vec::new(), ..Default::default() } .into() }); let init_class_call = CallExpr { span: DUMMY_SP, callee: init_class.as_callee(), args: Vec::new(), ..Default::default() } .into(); constructor.body.as_mut().unwrap().stmts.insert( 0, SeqExpr { span: DUMMY_SP, exprs: once(super_call) .chain(static_call) .chain(once(init_class_call)) .collect(), } .into_stmt(), ); } let class = Box::new(Class { span: DUMMY_SP, decorators: Vec::new(), body: c.class.body.take(), super_class: Some(Box::new(helper_expr!(identity))), ..Default::default() }); self.state = old_state; return NewExpr { span: DUMMY_SP, callee: ClassExpr { ident: None, class }.into(), args: Some(Vec::new()), ..Default::default() } .into_stmt(); } for m in body.iter_mut() { if let ClassMember::Constructor(..) = m { c.class.body.push(m.take()); } } body.visit_mut_with(self); c.ident = preserved_class_name.clone(); replace_ident(&mut c.class, c.ident.to_id(), &preserved_class_name); c.class.body.extend(body); c.visit_mut_with(self); c.class.body.push(ClassMember::StaticBlock(StaticBlock { span: DUMMY_SP, body: BlockStmt { span: DUMMY_SP, stmts: vec![CallExpr { span: DUMMY_SP, callee: init_class.as_callee(), args: Vec::new(), ..Default::default() } .into_stmt()], ..Default::default() }, })); self.state = old_state; c.take().into() } fn process_decorators(&mut self, decorators: &mut [Decorator]) { decorators.iter_mut().for_each(|dec| { let e = self.preserve_side_effect_of_decorator(dec.expr.take()); dec.expr = e; }) } fn process_prop_name(&mut self, name: &mut PropName) { match name { PropName::Ident(..) => {} PropName::Computed(c) if c.expr.is_ident() => {} _ => { let ident = private_ident!("_computedKey"); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: ident.clone().into(), init: None, definite: false, }); self.pre_class_inits.push( AssignExpr { span: DUMMY_SP, op: op!("="), left: ident.clone().into(), right: Box::new(prop_name_to_expr_value(name.take())), } .into(), ); *name = PropName::Computed(ComputedPropName { span: DUMMY_SP, expr: ident.into(), }); } } } fn process_decorators_of_class_members(&mut self, members: &mut [ClassMember]) { for mut m in members { match &mut m { ClassMember::Method(m) if m.function.body.is_some() => { self.process_decorators(&mut m.function.decorators); self.process_prop_name(&mut m.key); } ClassMember::PrivateMethod(m) if m.function.body.is_some() => { self.process_decorators(&mut m.function.decorators); } ClassMember::ClassProp(m) if !m.declare => { self.process_decorators(&mut m.decorators); self.process_prop_name(&mut m.key); } ClassMember::PrivateProp(m) => { self.process_decorators(&mut m.decorators); } ClassMember::AutoAccessor(m) => { self.process_decorators(&mut m.decorators); } _ => {} } } } } impl VisitMut for DecoratorPass { noop_visit_mut_type!(); fn visit_mut_class(&mut self, n: &mut Class) { let old_stmts = self.state.extra_stmts.take(); n.visit_mut_children_with(self); if let Some(init_proto) = self.state.init_proto.clone() { let init_proto_expr = CallExpr { span: DUMMY_SP, callee: init_proto.clone().as_callee(), args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], ..Default::default() }; let mut proto_inited = false; for member in n.body.iter_mut() { if let ClassMember::ClassProp(prop) = member { if prop.is_static { continue; } if let Some(value) = prop.value.clone() { prop.value = Some(Expr::from_exprs(vec![ init_proto_expr.clone().into(), value, ])); proto_inited = true; break; } } else if let ClassMember::PrivateProp(prop) = member { if prop.is_static { continue; } if let Some(value) = prop.value.clone() { prop.value = Some(Expr::from_exprs(vec![ init_proto_expr.clone().into(), value, ])); proto_inited = true; break; } } } if !proto_inited { let c = self.ensure_constructor(n); inject_after_super(c, vec![Box::new(init_proto_expr.into())]) } } self.consume_inits(); if !self.state.extra_stmts.is_empty() { n.body.insert( 0, ClassMember::StaticBlock(StaticBlock { span: DUMMY_SP, body: BlockStmt { span: DUMMY_SP, stmts: self.state.extra_stmts.take(), ..Default::default() }, }), ); } self.state.init_proto = None; self.state.extra_stmts = old_stmts; } fn visit_mut_class_member(&mut self, n: &mut ClassMember) { n.visit_mut_children_with(self); if let ClassMember::PrivateMethod(p) = n { if p.function.decorators.is_empty() { return; } let decorators = self.preserve_side_effect_of_decorators(p.function.decorators.take()); let dec = merge_decorators(decorators); let init = private_ident!(format!("_call_{}", p.key.name)); self.extra_vars.push(VarDeclarator { span: p.span, name: init.clone().into(), init: None, definite: false, }); if p.is_static { self.state .init_static .get_or_insert_with(|| private_ident!("_initStatic")); } else { self.state .init_proto .get_or_insert_with(|| private_ident!("_initProto")); } let caller = FnExpr { ident: None, function: p.function.clone(), }; let arg = Some( ArrayLit { span: DUMMY_SP, elems: vec![ dec, Some( if p.is_static { match p.kind { MethodKind::Method => 7, MethodKind::Setter => 9, MethodKind::Getter => 8, } } else { match p.kind { MethodKind::Method => 2, MethodKind::Setter => 4, MethodKind::Getter => 3, } } .as_arg(), ), Some(p.key.name.clone().as_arg()), Some(caller.as_arg()), ], } .as_arg(), ); if p.is_static { self.state.init_static_args.push(arg); } else { self.state.init_proto_args.push(arg); } if p.is_static { self.state.static_lhs.push(init.clone()); } else { self.state.proto_lhs.push(init.clone()); } match p.kind { MethodKind::Method => { let call_stmt = ReturnStmt { span: DUMMY_SP, arg: Some(init.into()), } .into(); p.kind = MethodKind::Getter; p.function.body = Some(BlockStmt { span: DUMMY_SP, stmts: vec![call_stmt], ..Default::default() }); } MethodKind::Getter => { let call_stmt = ReturnStmt { span: DUMMY_SP, arg: Some( CallExpr { span: DUMMY_SP, callee: init.as_callee(), args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], ..Default::default() } .into(), ), } .into(); p.function.body = Some(BlockStmt { span: DUMMY_SP, stmts: vec![call_stmt], ..Default::default() }); } MethodKind::Setter => { let call_stmt = ReturnStmt { span: DUMMY_SP, arg: Some( CallExpr { span: DUMMY_SP, callee: init.as_callee(), args: vec![ ThisExpr { span: DUMMY_SP }.as_arg(), Ident::from(p.function.params[0].pat.as_ident().unwrap()) .as_arg(), ], ..Default::default() } .into(), ), } .into(); p.function.body = Some(BlockStmt { span: DUMMY_SP, stmts: vec![call_stmt], ..Default::default() }); } } } } fn visit_mut_class_members(&mut self, members: &mut Vec<ClassMember>) { let mut new = Vec::with_capacity(members.len()); self.process_decorators_of_class_members(members); for mut m in members.take() { match m { ClassMember::AutoAccessor(mut accessor) => { accessor.value.visit_mut_with(self); let name; let init; let field_name_like: Atom; let private_field = PrivateProp { span: DUMMY_SP, key: match &mut accessor.key { Key::Private(k) => { name = Lit::Str(Str { span: DUMMY_SP, value: k.name.clone(), raw: None, }) .into(); init = private_ident!(format!("_init_{}", k.name)); field_name_like = format!("__{}", k.name).into(); self.state.private_id_index += 1; PrivateName { span: k.span, name: format!("__{}_{}", k.name, self.state.private_id_index) .into(), } } Key::Public(k) => { (name, init) = self.initializer_name(k, "init"); field_name_like = format!("__{}", init.sym) .replacen("init", "private", 1) .into(); self.state.private_id_index += 1; PrivateName { span: init.span, name: format!( "{field_name_like}_{}", self.state.private_id_index ) .into(), } } }, value: if accessor.decorators.is_empty() { accessor.value } else { let init_call = CallExpr { span: DUMMY_SP, callee: init.clone().as_callee(), args: once(ThisExpr { span: DUMMY_SP }.as_arg()) .chain(accessor.value.take().map(|v| v.as_arg())) .collect(), ..Default::default() } .into(); Some(init_call) }, type_ann: None, is_static: accessor.is_static, decorators: Default::default(), accessibility: Default::default(), is_optional: false, is_override: false, readonly: false, definite: false, ctxt: Default::default(), }; let mut getter_function = Box::new(Function { params: Default::default(), decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::Return(ReturnStmt { span: DUMMY_SP, arg: Some(Box::new(Expr::Member(MemberExpr { span: DUMMY_SP, obj: ThisExpr { span: DUMMY_SP }.into(), prop: MemberProp::PrivateName(private_field.key.clone()), }))), })], ..Default::default() }), is_generator: false, is_async: false, ..Default::default() }); let mut setter_function = { let param = private_ident!("_v"); Box::new(Function { params: vec![Param { span: DUMMY_SP, decorators: Default::default(), pat: param.clone().into(), }], decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::Expr(ExprStmt { span: DUMMY_SP, expr: Box::new(Expr::Assign(AssignExpr { span: DUMMY_SP, op: op!("="), left: MemberExpr { span: DUMMY_SP, obj: ThisExpr { span: DUMMY_SP }.into(), prop: MemberProp::PrivateName( private_field.key.clone(), ), } .into(), right: param.clone().into(), })), })], ..Default::default() }), is_generator: false, is_async: false, ..Default::default() }) }; if !accessor.decorators.is_empty() { let decorators = self.preserve_side_effect_of_decorators(accessor.decorators.take()); let dec = merge_decorators(decorators); self.extra_vars.push(VarDeclarator { span: accessor.span, name: init.clone().into(), init: None, definite: false, }); let (getter_var, setter_var) = match &accessor.key { Key::Private(_) => ( Some(private_ident!(format!("_get_{}", field_name_like))), Some(private_ident!(format!("_set_{}", field_name_like))), ), Key::Public(_) => Default::default(), }; let initialize_init = { ArrayLit { span: DUMMY_SP, elems: match &accessor.key { Key::Private(_) => { let data = vec![ dec, Some(if accessor.is_static { 6.as_arg() } else { 1.as_arg() }), Some(name.as_arg()), Some( FnExpr { ident: None, function: getter_function, } .as_arg(), ), Some( FnExpr { ident: None, function: setter_function, } .as_arg(), ), ]; self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: getter_var.clone().unwrap().into(), init: None, definite: false, }); self.extra_vars.push(VarDeclarator { span: DUMMY_SP, name: setter_var.clone().unwrap().into(), init: None, definite: false, }); getter_function = Box::new(Function { params: Vec::new(), span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::Return(ReturnStmt { span: DUMMY_SP, arg: Some(Box::new(Expr::Call(CallExpr { span: DUMMY_SP, callee: getter_var .clone() .unwrap() .as_callee(), args: vec![ ThisExpr { span: DUMMY_SP }.as_arg() ], ..Default::default() }))), })], ..Default::default() }), is_generator: false, is_async: false, ..Default::default() }); let param = private_ident!("_v"); setter_function = Box::new(Function { params: vec![Param { span: DUMMY_SP, decorators: Default::default(), pat: param.clone().into(), }], decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::Expr(ExprStmt { span: DUMMY_SP, expr: Box::new(Expr::Call(CallExpr { span: DUMMY_SP, callee: setter_var .clone() .unwrap() .as_callee(), args: vec![ ThisExpr { span: DUMMY_SP }.as_arg(), param.as_arg(), ], ..Default::default() })), })], ..Default::default() }), is_generator: false, is_async: false, ..Default::default() }); data } Key::Public(_) => { vec![ dec, Some(if accessor.is_static { 6.as_arg() } else { 1.as_arg() }), Some(name.as_arg()), ] } }, } .as_arg() }; if accessor.is_static { self.state.static_lhs.push(init); self.state.init_static_args.push(Some(initialize_init)); self.state .static_lhs .extend(getter_var.into_iter().chain(setter_var)); } else { self.state.proto_lhs.push(init); self.state.init_proto_args.push(Some(initialize_init)); self.state .proto_lhs .extend(getter_var.into_iter().chain(setter_var)); } if accessor.is_static { self.state .init_static .get_or_insert_with(|| private_ident!("_initStatic")); } else { self.state .init_proto .get_or_insert_with(|| private_ident!("_initProto")); } } match accessor.key { Key::Private(key) => { let getter = PrivateMethod { span: DUMMY_SP, key: key.clone(), function: getter_function, kind: MethodKind::Getter, is_static: accessor.is_static, accessibility: None, is_abstract: false, is_optional: false, is_override: false, }; let setter = PrivateMethod { span: DUMMY_SP, key: key.clone(), function: setter_function, kind: MethodKind::Setter, is_static: accessor.is_static, accessibility: None, is_abstract: false, is_optional: false, is_override: false, }; new.push(ClassMember::PrivateProp(private_field)); new.push(ClassMember::PrivateMethod(getter)); new.push(ClassMember::PrivateMethod(setter)); } Key::Public(key) => { let getter = ClassMethod { span: DUMMY_SP, key: key.clone(), function: getter_function, kind: MethodKind::Getter, is_static: accessor.is_static, accessibility: None, is_abstract: false, is_optional: false, is_override: false, }; let setter = ClassMethod { span: DUMMY_SP, key: key.clone(), function: setter_function, kind: MethodKind::Setter, is_static: accessor.is_static, accessibility: None, is_abstract: false, is_optional: false, is_override: false, }; new.push(ClassMember::PrivateProp(private_field)); new.push(ClassMember::Method(getter)); new.push(ClassMember::Method(setter)); } } continue; } ClassMember::Method(..) | ClassMember::PrivateMethod(..) => { m.visit_mut_with(self); } _ => {} } new.push(m); } for mut m in new.take() { match m { ClassMember::Method(..) | ClassMember::PrivateMethod(..) | ClassMember::AutoAccessor(..) => {} _ => { if !m.span().is_dummy() { m.visit_mut_with(self); } } } new.push(m); } *members = new; } fn visit_mut_class_method(&mut self, n: &mut ClassMethod) { // method without body is TypeScript's method declaration. if n.function.body.is_none() { return; } n.visit_mut_children_with(self); if n.function.decorators.is_empty() { return; } let decorators = self.preserve_side_effect_of_decorators(n.function.decorators.take()); let dec = merge_decorators(decorators); let (name, _init) = self.initializer_name(&mut n.key, "call"); if n.is_static { self.state .init_static .get_or_insert_with(|| private_ident!("_initStatic")); } else { self.state .init_proto .get_or_insert_with(|| private_ident!("_initProto")); } let arg = Some( ArrayLit { span: DUMMY_SP, elems: vec![ dec, Some( match (n.is_static, n.kind) { (true, MethodKind::Method) => 7, (false, MethodKind::Method) => 2, (true, MethodKind::Setter) => 9, (false, MethodKind::Setter) => 4, (true, MethodKind::Getter) => 8, (false, MethodKind::Getter) => 3, } .as_arg(), ), Some(name.as_arg()), ], } .as_arg(), ); if n.is_static { self.state.init_static_args.push(arg); } else { self.state.init_proto_args.push(arg); } } fn visit_mut_class_prop(&mut self, p: &mut ClassProp) { if p.declare { return; } p.visit_mut_children_with(self); if p.decorators.is_empty() { return; } let decorators = self.preserve_side_effect_of_decorators(p.decorators.take()); let dec = merge_decorators(decorators); let (name, init) = self.initializer_name(&mut p.key, "init"); self.extra_vars.push(VarDeclarator { span: p.span, name: init.clone().into(), init: None, definite: false, }); p.value = Some( CallExpr { span: DUMMY_SP, callee: init.clone().as_callee(), args: once(ThisExpr { span: DUMMY_SP }.as_arg()) .chain(p.value.take().map(|v| v.as_arg())) .collect(), ..Default::default() } .into(), ); let initialize_init = { Some( ArrayLit { span: DUMMY_SP, elems: vec![ dec, Some(if p.is_static { 5.as_arg() } else { 0.as_arg() }), Some(name.as_arg()), ], } .as_arg(), ) }; if p.is_static { self.state.static_lhs.push(init); self.state.init_static_args.push(initialize_init); } else { self.state.proto_lhs.push(init); self.state.init_proto_args.push(initialize_init); } } fn visit_mut_expr(&mut self, e: &mut Expr) { if let Expr::Class(c) = e { if !c.class.decorators.is_empty() { let new = self.handle_class_expr(&mut c.class, c.ident.as_ref()); c.visit_mut_with(self); *e = SeqExpr { span: DUMMY_SP, exprs: vec![Box::new(e.take()), Box::new(Expr::Ident(new))], } .into(); return; } } maybe_grow_default(|| e.visit_mut_children_with(self)); } fn visit_mut_module_item(&mut self, s: &mut ModuleItem) { match s { ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { span, decl: Decl::Class(c), })) if !c.class.decorators.is_empty() => { let ident = c.ident.clone(); let span = *span; let new_stmt = self.handle_class_decl(c); *s = new_stmt.into(); self.extra_exports .push(ExportSpecifier::Named(ExportNamedSpecifier { span, orig: ModuleExportName::Ident(ident), exported: None, is_type_only: false, })); } ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(ExportDefaultDecl { span, decl: DefaultDecl::Class(c), })) if !c.class.decorators.is_empty() => { let ident = c .ident .get_or_insert_with(|| private_ident!("_default")) .clone(); let mut class_decl = c.take().as_class_decl().unwrap(); let new_stmt = self.handle_class_decl(&mut class_decl); self.extra_exports .push(ExportSpecifier::Named(ExportNamedSpecifier { span: *span, orig: ModuleExportName::Ident(ident), exported: Some(quote_ident!("default").into()), is_type_only: false, })); *s = new_stmt.into(); } _ => { s.visit_mut_children_with(self); } } } fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) { let extra_vars = self.extra_vars.take(); let extra_lets = self.extra_lets.take(); let pre_class_inits = self.pre_class_inits.take(); let extra_exports = self.extra_exports.take(); let mut insert_builder = InsertPassBuilder::new(); for (index, n) in n.iter_mut().enumerate() { n.visit_mut_with(self); if !self.extra_lets.is_empty() { insert_builder.push_back( index, VarDecl { span: DUMMY_SP, kind: VarDeclKind::Let, decls: self.extra_lets.take(), declare: false, ..Default::default() } .into(), ); } if !self.pre_class_inits.is_empty() { insert_builder.push_back( index, ExprStmt { span: DUMMY_SP, expr: Expr::from_exprs(self.pre_class_inits.take()), } .into(), ); } } if !self.extra_vars.is_empty() { let insert_pos = n .iter() .position(|module_item| match module_item { ModuleItem::Stmt(stmt) => !is_maybe_branch_directive(stmt), ModuleItem::ModuleDecl(_) => true, }) .unwrap_or(0); insert_builder.push_front( insert_pos, VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, decls: self.extra_vars.take(), declare: false, ..Default::default() } .into(), ); } if !self.extra_exports.is_empty() { insert_builder.push_back( n.len() + 1, NamedExport { span: DUMMY_SP, specifiers: self.extra_exports.take(), src: None, type_only: false, with: None, } .into(), ); } *n = insert_builder.build(n.take()); if !self.rename_map.is_empty() { n.visit_mut_with(&mut IdentRenamer::new(&self.rename_map)); } self.extra_vars = extra_vars; self.extra_lets = extra_lets; self.pre_class_inits = pre_class_inits; self.extra_exports = extra_exports; } fn visit_mut_private_prop(&mut self, p: &mut PrivateProp) { p.visit_mut_children_with(self); if p.decorators.is_empty() { return; } let decorators = self.preserve_side_effect_of_decorators(p.decorators.take()); let dec = merge_decorators(decorators); let init = private_ident!(format!("_init_{}", p.key.name)); self.extra_vars.push(VarDeclarator { span: p.span, name: init.clone().into(), init: None, definite: false, }); p.value = Some( CallExpr { span: DUMMY_SP, callee: init.clone().as_callee(), args: once(ThisExpr { span: DUMMY_SP }.as_arg()) .chain(p.value.take().map(|v| v.as_arg())) .collect(), ..Default::default() } .into(), ); let initialize_init = { let access_expr = MemberExpr { span: DUMMY_SP, obj: ThisExpr { span: DUMMY_SP }.into(), prop: MemberProp::PrivateName(p.key.clone()), }; let getter = Box::new(Function { span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::Return(ReturnStmt { span: DUMMY_SP, arg: Some(access_expr.clone().into()), })], ..Default::default() }), is_async: false, is_generator: false, ..Default::default() }); let settter_arg = private_ident!("value"); let setter = Box::new(Function { span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::Expr(ExprStmt { span: DUMMY_SP, expr: Box::new(Expr::Assign(AssignExpr { span: DUMMY_SP, op: op!("="), left: access_expr.into(), right: Box::new(Expr::Ident(settter_arg.clone())), })), })], ..Default::default() }), is_async: false, is_generator: false, decorators: Default::default(), params: vec![Param { span: DUMMY_SP, decorators: Default::default(), pat: Pat::Ident(settter_arg.into()), }], ..Default::default() }); ArrayLit { span: DUMMY_SP, elems: vec![ dec, Some(if p.is_static { 5.as_arg() } else { 0.as_arg() }), Some((&*p.key.name).as_arg()), Some( FnExpr { ident: None, function: getter, } .as_arg(), ), Some( FnExpr { ident: None, function: setter, } .as_arg(), ), ], } .as_arg() }; if p.is_static { self.state.static_lhs.push(init); self.state.init_static_args.push(Some(initialize_init)); } else { self.state.proto_lhs.push(init); self.state.init_proto_args.push(Some(initialize_init)); } } fn visit_mut_stmt(&mut self, s: &mut Stmt) { match s { Stmt::Decl(Decl::Class(c)) if !c.class.decorators.is_empty() => { *s = self.handle_class_decl(c); } _ => { s.visit_mut_children_with(self); } } } fn visit_mut_stmts(&mut self, n: &mut Vec<Stmt>) { let old_state = take(&mut self.state); let old_pre_class_inits = self.pre_class_inits.take(); let old_extra_lets = self.extra_lets.take(); let old_extra_vars = self.extra_vars.take(); let mut insert_builder = InsertPassBuilder::new(); for (index, n) in n.iter_mut().enumerate() { n.visit_mut_with(self); if !self.extra_lets.is_empty() { insert_builder.push_back( index, VarDecl { span: DUMMY_SP, kind: VarDeclKind::Let, decls: self.extra_lets.take(), declare: false, ..Default::default() } .into(), ); } if !self.pre_class_inits.is_empty() { insert_builder.push_back( index, ExprStmt { span: DUMMY_SP, expr: Expr::from_exprs(self.pre_class_inits.take()), } .into(), ); } } if !self.extra_vars.is_empty() { let insert_pos = n .iter() .position(|stmt| !is_maybe_branch_directive(stmt)) .unwrap_or(0); insert_builder.push_front( insert_pos, VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, decls: self.extra_vars.take(), declare: false, ..Default::default() } .into(), ); } *n = insert_builder.build(n.take()); self.extra_vars = old_extra_vars; self.extra_lets = old_extra_lets; self.pre_class_inits = old_pre_class_inits; self.state = old_state; } } /// Inserts into a vector on `build()` setting the correct /// capacity. This is useful in scenarios where you're iterating /// a vector to insert and all the inserts are in the order of /// the iteration. struct InsertPassBuilder<T> { inserts: VecDeque<(usize, T)>, } impl<T> InsertPassBuilder<T> { pub fn new() -> Self { Self { inserts: Default::default(), } } pub fn push_front(&mut self, index: usize, item: T) { if cfg!(debug_assertions) { if let Some(past) = self.inserts.front() { debug_assert!(past.0 >= index, "{} {}", past.0, index); } } self.inserts.push_front((index, item)); } pub fn push_back(&mut self, index: usize, item: T) { if cfg!(debug_assertions) { if let Some(past) = self.inserts.back() { debug_assert!(past.0 <= index, "{} {}", past.0, index); } } self.inserts.push_back((index, item)); } pub fn build(mut self, original: Vec<T>) -> Vec<T> { let capacity = original.len() + self.inserts.len(); let mut new = Vec::with_capacity(capacity); for (index, item) in original.into_iter().enumerate() { while self .inserts .front() .map(|(item_index, _)| *item_index == index) .unwrap_or(false) { new.push(self.inserts.pop_front().unwrap().1); } new.push(item); } new.extend(self.inserts.into_iter().map(|v| v.1)); debug_assert!(new.len() == capacity, "len: {} / {}", new.len(), capacity); new } } fn merge_decorators(decorators: Vec<Option<ExprOrSpread>>) -> Option<ExprOrSpread> { if decorators.len() == 1 { return decorators.into_iter().next().unwrap(); } Some( ArrayLit { span: DUMMY_SP, elems: decorators, } .as_arg(), ) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_proposal/src/decorators/legacy/metadata.rs
Rust
use std::ops::Deref; use rustc_hash::FxHashMap; use swc_atoms::Atom; use swc_common::{ util::{move_map::MoveMap, take::Take}, BytePos, Spanned, DUMMY_SP, }; use swc_ecma_ast::*; use swc_ecma_transforms_base::helper; use swc_ecma_utils::{quote_ident, ExprFactory}; use swc_ecma_visit::{VisitMut, VisitMutWith}; use super::EnumKind; /// https://github.com/leonardfactory/babel-plugin-transform-typescript-metadata/blob/master/src/parameter/parameterVisitor.ts pub(super) struct ParamMetadata; impl VisitMut for ParamMetadata { fn visit_mut_class(&mut self, cls: &mut Class) { cls.visit_mut_children_with(self); let mut decorators = cls.decorators.take(); cls.body = cls.body.take().move_map(|m| match m { ClassMember::Constructor(mut c) => { for (idx, param) in c.params.iter_mut().enumerate() { // match param { ParamOrTsParamProp::TsParamProp(p) => { for decorator in p.decorators.drain(..) { let new_dec = self.create_param_decorator(idx, decorator.expr); decorators.push(new_dec); } } ParamOrTsParamProp::Param(param) => { for decorator in param.decorators.drain(..) { let new_dec = self.create_param_decorator(idx, decorator.expr); decorators.push(new_dec); } } } } ClassMember::Constructor(c) } _ => m, }); cls.decorators = decorators; } fn visit_mut_class_method(&mut self, m: &mut ClassMethod) { for (idx, param) in m.function.params.iter_mut().enumerate() { for decorator in param.decorators.drain(..) { let new_dec = self.create_param_decorator(idx, decorator.expr); m.function.decorators.push(new_dec); } } } } impl ParamMetadata { fn create_param_decorator( &self, param_index: usize, mut decorator_expr: Box<Expr>, ) -> Decorator { remove_span(&mut decorator_expr); Decorator { span: DUMMY_SP, expr: CallExpr { span: DUMMY_SP, callee: helper!(ts, ts_param), args: vec![param_index.as_arg(), decorator_expr.as_arg()], ..Default::default() } .into(), } } } pub(super) fn remove_span(e: &mut Expr) { match e { Expr::Member(m) => { m.span = DUMMY_SP; remove_span(&mut m.obj); } Expr::Call(c) => { c.span = DUMMY_SP; if let Callee::Expr(e) = &mut c.callee { remove_span(e); } for arg in &mut c.args { remove_span(&mut arg.expr); } } _ => { e.set_span(DUMMY_SP); } } } type EnumMapType = FxHashMap<Atom, EnumKind>; pub(super) struct EnumMap<'a>(&'a EnumMapType); impl Deref for EnumMap<'_> { type Target = EnumMapType; fn deref(&self) -> &Self::Target { self.0 } } impl EnumMap<'_> { fn get_kind_as_str(&self, param: Option<&TsTypeAnn>) -> Option<&'static str> { param .and_then(|t| t.type_ann.as_ts_type_ref()) .and_then(|t| t.type_name.as_ident()) .and_then(|t| self.get(&t.sym)) .map(|kind| match kind { EnumKind::Mixed => "Object", EnumKind::Str => "String", EnumKind::Num => "Number", }) } } /// https://github.com/leonardfactory/babel-plugin-transform-typescript-metadata/blob/master/src/metadata/metadataVisitor.ts pub(super) struct Metadata<'a> { pub(super) enums: EnumMap<'a>, pub(super) class_name: Option<&'a Ident>, } impl VisitMut for Metadata<'_> { fn visit_mut_class(&mut self, c: &mut Class) { c.visit_mut_children_with(self); if c.decorators.is_empty() { return; } let constructor = c.body.iter().find_map(|m| match m { ClassMember::Constructor(c) => Some(c), _ => None, }); if constructor.is_none() { return; } { let dec = self .create_metadata_design_decorator("design:type", quote_ident!("Function").as_arg()); c.decorators.push(dec); } { let dec = self.create_metadata_design_decorator( "design:paramtypes", ArrayLit { span: DUMMY_SP, elems: constructor .as_ref() .unwrap() .params .iter() .map(|v| match v { ParamOrTsParamProp::TsParamProp(p) => { let ann = match &p.param { TsParamPropParam::Ident(i) => i.type_ann.as_deref(), TsParamPropParam::Assign(a) => get_type_ann_of_pat(&a.left), }; Some(serialize_type(self.class_name, ann).as_arg()) } ParamOrTsParamProp::Param(p) => Some( serialize_type(self.class_name, get_type_ann_of_pat(&p.pat)) .as_arg(), ), }) .collect(), } .as_arg(), ); c.decorators.push(dec); } } fn visit_mut_class_method(&mut self, m: &mut ClassMethod) { if m.function.decorators.is_empty() { return; } { let type_arg = match m.kind { MethodKind::Method => quote_ident!("Function").as_arg(), MethodKind::Getter => { let return_type = m.function.return_type.as_deref(); if let Some(kind) = self.enums.get_kind_as_str(return_type) { quote_ident!(kind).as_arg() } else { serialize_type(self.class_name, return_type).as_arg() } } MethodKind::Setter => serialize_type( self.class_name, get_type_ann_of_pat(&m.function.params[0].pat), ) .as_arg(), }; let dec = self.create_metadata_design_decorator("design:type", type_arg); m.function.decorators.push(dec); } { let dec = self.create_metadata_design_decorator( "design:paramtypes", ArrayLit { span: DUMMY_SP, elems: m .function .params .iter() .map(|v| { Some( serialize_type(self.class_name, get_type_ann_of_pat(&v.pat)) .as_arg(), ) }) .collect(), } .as_arg(), ); m.function.decorators.push(dec); } // https://github.com/microsoft/TypeScript/blob/2a8865e6ba95c9bdcdb9e2c9c08f10c5f5c75391/src/compiler/transformers/ts.ts#L1180 if m.kind == MethodKind::Method { // Copy tsc behaviour // https://github.com/microsoft/TypeScript/blob/5e8c261b6ab746213f19ee3501eb8c48a6215dd7/src/compiler/transformers/typeSerializer.ts#L242 let dec = self.create_metadata_design_decorator( "design:returntype", if m.function.is_async { quote_ident!("Promise").as_arg() } else { let return_type = m.function.return_type.as_deref(); if let Some(kind) = self.enums.get_kind_as_str(return_type) { quote_ident!(kind).as_arg() } else { serialize_type(self.class_name, return_type).as_arg() } }, ); m.function.decorators.push(dec); } } fn visit_mut_class_prop(&mut self, p: &mut ClassProp) { if p.decorators.is_empty() || p.type_ann.is_none() { return; } let dec = self.create_metadata_design_decorator("design:type", { let prop_type = p.type_ann.as_deref(); if let Some(kind) = self.enums.get_kind_as_str(prop_type) { quote_ident!(kind).as_arg() } else { serialize_type(self.class_name, prop_type).as_arg() } }); p.decorators.push(dec); } } impl<'a> Metadata<'a> { pub(super) fn new(enums: &'a EnumMapType, class_name: Option<&'a Ident>) -> Self { Self { enums: EnumMap(enums), class_name, } } fn create_metadata_design_decorator(&self, design: &str, type_arg: ExprOrSpread) -> Decorator { Decorator { span: DUMMY_SP, expr: CallExpr { span: DUMMY_SP, callee: helper!(ts, ts_metadata), args: vec![design.as_arg(), type_arg], ..Default::default() } .into(), } } } fn serialize_type(class_name: Option<&Ident>, param: Option<&TsTypeAnn>) -> Expr { fn check_object_existed(expr: Box<Expr>) -> Box<Expr> { match *expr { Expr::Member(ref member_expr) => { let obj_expr = member_expr.obj.clone(); BinExpr { span: DUMMY_SP, left: check_object_existed(obj_expr), op: op!("||"), right: Box::new( BinExpr { span: DUMMY_SP, left: Box::new(Expr::Unary(UnaryExpr { span: DUMMY_SP, op: op!("typeof"), arg: expr, })), op: op!("==="), right: Box::new(Expr::Lit(Lit::Str(Str { span: DUMMY_SP, value: "undefined".into(), raw: None, }))), } .into(), ), } .into() } _ => BinExpr { span: DUMMY_SP, left: Box::new( UnaryExpr { span: DUMMY_SP, op: op!("typeof"), arg: expr, } .into(), ), op: op!("==="), right: Box::new( Lit::Str(Str { span: DUMMY_SP, value: "undefined".into(), raw: None, }) .into(), ), } .into(), } } fn serialize_type_ref(class_name: &str, ty: &TsTypeRef) -> Expr { match &ty.type_name { // We should omit references to self (class) since it will throw a ReferenceError at // runtime due to babel transpile output. TsEntityName::Ident(i) if &*i.sym == class_name => { return quote_ident!("Object").into() } _ => {} } let member_expr = ts_entity_to_member_expr(&ty.type_name); // We don't know if type is just a type (interface, etc.) or a concrete value // (class, etc.) // // `typeof` operator allows us to use the expression even if it is not defined, // fallback is just `Object`. CondExpr { span: DUMMY_SP, test: check_object_existed(Box::new(member_expr.clone())), cons: Box::new(quote_ident!("Object").into()), alt: Box::new(member_expr), } .into() } fn serialize_type_list(class_name: &str, types: &[Box<TsType>]) -> Expr { let mut u = None; for ty in types { // Skip parens if need be let ty = match &**ty { TsType::TsParenthesizedType(ty) => &ty.type_ann, _ => ty, }; match &**ty { // Always elide `never` from the union/intersection if possible TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsNeverKeyword, .. }) => { continue; } // Elide null and undefined from unions for metadata, just like what we did prior to // the implementation of strict null checks TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsNullKeyword, .. }) | TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsUndefinedKeyword, .. }) => { return quote_ident!("Object").into(); } _ => {} } let item = serialize_type_node(class_name, ty); // One of the individual is global object, return immediately if item.is_ident_ref_to("Object") { return item; } // If there exists union that is not void 0 expression, check if the // the common type is identifier. anything more complex // and we will just default to Object // match &u { None => { u = Some(item); } Some(prev) => { // Check for different types match prev { Expr::Ident(prev) => match &item { Expr::Ident(item) if prev.sym == item.sym => {} _ => return quote_ident!("Object").into(), }, _ => return quote_ident!("Object").into(), } } } } match u { Some(i) => i, _ => quote_ident!("Object").into(), } } fn serialize_type_node(class_name: &str, ty: &TsType) -> Expr { let span = ty.span(); match ty { TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsVoidKeyword, .. }) | TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsUndefinedKeyword, .. }) | TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsNullKeyword, .. }) | TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsNeverKeyword, .. }) => *Expr::undefined(span), TsType::TsParenthesizedType(ty) => serialize_type_node(class_name, &ty.type_ann), TsType::TsFnOrConstructorType(_) => quote_ident!("Function").into(), TsType::TsArrayType(_) | TsType::TsTupleType(_) => quote_ident!("Array").into(), TsType::TsLitType(TsLitType { lit: TsLit::Bool(..), .. }) | TsType::TsTypePredicate(_) | TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsBooleanKeyword, .. }) => quote_ident!("Boolean").into(), ty if is_str(ty) => quote_ident!("String").into(), TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsObjectKeyword, .. }) => quote_ident!("Object").into(), TsType::TsLitType(TsLitType { lit: TsLit::Number(..), .. }) | TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsNumberKeyword, .. }) => quote_ident!("Number").into(), TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsBigIntKeyword, .. }) => CondExpr { span: DUMMY_SP, test: check_object_existed(quote_ident!("BigInt").into()), cons: quote_ident!("Object").into(), alt: quote_ident!("BigInt").into(), } .into(), TsType::TsLitType(ty) => { // TODO: Proper error reporting panic!("Bad type for decoration: {:?}", ty); } TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsSymbolKeyword, .. }) => quote_ident!("Symbol").into(), TsType::TsTypeQuery(_) | TsType::TsTypeOperator(_) | TsType::TsIndexedAccessType(_) | TsType::TsTypeLit(_) | TsType::TsMappedType(_) | TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsAnyKeyword, .. }) | TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsUnknownKeyword, .. }) | TsType::TsThisType(..) => quote_ident!("Object").into(), TsType::TsUnionOrIntersectionType(ty) => match ty { TsUnionOrIntersectionType::TsUnionType(ty) => { serialize_type_list(class_name, &ty.types) } TsUnionOrIntersectionType::TsIntersectionType(ty) => { serialize_type_list(class_name, &ty.types) } }, TsType::TsConditionalType(ty) => { serialize_type_list(class_name, &[ty.true_type.clone(), ty.false_type.clone()]) } TsType::TsTypeRef(ty) => serialize_type_ref(class_name, ty), _ => panic!("Bad type for decorator: {:?}", ty), } } let param = match param { Some(v) => &v.type_ann, None => return *Expr::undefined(DUMMY_SP), }; serialize_type_node(class_name.map(|v| &*v.sym).unwrap_or(""), param) } fn ts_entity_to_member_expr(type_name: &TsEntityName) -> Expr { match type_name { TsEntityName::TsQualifiedName(q) => { let obj = ts_entity_to_member_expr(&q.left); MemberExpr { span: DUMMY_SP, obj: obj.into(), prop: MemberProp::Ident(q.right.clone()), } .into() } TsEntityName::Ident(i) => i.clone().with_pos(BytePos::DUMMY, BytePos::DUMMY).into(), } } fn get_type_ann_of_pat(p: &Pat) -> Option<&TsTypeAnn> { match p { Pat::Ident(p) => p.type_ann.as_deref(), Pat::Array(p) => p.type_ann.as_deref(), Pat::Rest(p) => p.type_ann.as_deref(), Pat::Object(p) => p.type_ann.as_deref(), Pat::Assign(p) => get_type_ann_of_pat(&p.left), Pat::Invalid(_) => None, Pat::Expr(_) => None, } } fn is_str(ty: &TsType) -> bool { match ty { TsType::TsLitType(TsLitType { lit: TsLit::Str(..) | TsLit::Tpl(..), .. }) | TsType::TsKeywordType(TsKeywordType { kind: TsKeywordTypeKind::TsStringKeyword, .. }) => true, TsType::TsUnionOrIntersectionType(TsUnionOrIntersectionType::TsUnionType(u)) => { u.types.iter().all(|ty| is_str(ty)) } _ => false, } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs
Rust
use std::{iter, mem}; use metadata::remove_span; use rustc_hash::FxHashMap; use swc_atoms::Atom; use swc_common::{util::take::Take, BytePos, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::helper; use swc_ecma_utils::{private_ident, prop_name_to_expr_value, quote_ident, ExprFactory, StmtLike}; use swc_ecma_visit::{Visit, VisitMut, VisitMutWith, VisitWith}; use self::metadata::{Metadata, ParamMetadata}; use super::contains_decorator; mod metadata; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum EnumKind { Mixed, Str, Num, } pub(super) fn new(metadata: bool) -> TscDecorator { TscDecorator { metadata, enums: Default::default(), vars: Default::default(), appended_exprs: Default::default(), appended_private_access_exprs: Default::default(), prepended_exprs: Default::default(), class_name: Default::default(), assign_class_expr_to: Default::default(), } } pub(super) struct TscDecorator { metadata: bool, enums: FxHashMap<Atom, EnumKind>, /// Used for computed keys, and this variables are not initialized. vars: Vec<VarDeclarator>, appended_exprs: Vec<Box<Expr>>, appended_private_access_exprs: Vec<Box<Expr>>, prepended_exprs: Vec<Box<Expr>>, class_name: Option<Ident>, assign_class_expr_to: Option<Ident>, } impl TscDecorator { fn visit_mut_stmt_likes<T>(&mut self, stmts: &mut Vec<T>) where T: StmtLike + VisitMutWith<Self>, { let old_vars = self.vars.take(); let old_appended_exprs = self.appended_exprs.take(); let old_prepended_exprs = self.prepended_exprs.take(); let mut new = Vec::new(); for mut s in stmts.take() { debug_assert!(self.appended_exprs.is_empty()); s.visit_mut_with(self); if !self.vars.is_empty() { new.push(T::from( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, declare: Default::default(), decls: self.vars.take(), ..Default::default() } .into(), )); } new.extend( self.prepended_exprs .drain(..) .map(|expr| { ExprStmt { span: DUMMY_SP, expr, } .into() }) .map(T::from), ); new.push(s); new.extend( self.appended_exprs .drain(..) .map(|expr| { ExprStmt { span: DUMMY_SP, expr, } .into() }) .map(T::from), ); } *stmts = new; self.prepended_exprs = old_prepended_exprs; self.appended_exprs = old_appended_exprs; self.vars = old_vars; } fn key(&mut self, k: &mut PropName) -> Expr { match k { PropName::Computed(k) if !k.expr.is_lit() => { let var_name = private_ident!(k.span, "_key"); // Declare var self.vars.push(VarDeclarator { span: DUMMY_SP, name: var_name.clone().into(), init: None, definite: Default::default(), }); // Initialize var self.prepended_exprs.push( AssignExpr { span: DUMMY_SP, op: op!("="), left: var_name.clone().into(), right: k.expr.take(), } .into(), ); k.expr = var_name.clone().into(); return var_name.into(); } PropName::Ident(i) => { return Lit::Str(Str { span: DUMMY_SP, raw: None, value: i.sym.clone(), }) .into() } _ => {} } prop_name_to_expr_value(k.clone()) } fn has_private_access(mut expr: &Expr) -> bool { while let Some(MemberExpr { obj, prop, .. }) = expr.as_member() { if prop.is_private_name() { return true; } expr = obj; } false } /// Creates `__decorate` calls. fn add_decorate_call( &mut self, decorators: impl IntoIterator<Item = Box<Expr>>, mut target: ExprOrSpread, key: ExprOrSpread, mut desc: ExprOrSpread, ) { let mut has_private_access = false; let decorators = ArrayLit { span: DUMMY_SP, elems: decorators .into_iter() .inspect(|e| { if has_private_access { return; } has_private_access = Self::has_private_access(e); }) .map(|mut v| { remove_span(&mut v); v.as_arg() }) .map(Some) .collect(), } .as_arg(); remove_span(&mut target.expr); remove_span(&mut desc.expr); let expr = CallExpr { callee: helper!(ts, ts_decorate), args: vec![decorators, target, key, desc], ..Default::default() } .into(); if has_private_access { self.appended_private_access_exprs.push(expr); } else { self.appended_exprs.push(expr); } } } impl Visit for TscDecorator { fn visit_ts_enum_decl(&mut self, e: &TsEnumDecl) { let enum_kind = e .members .iter() .map(|member| member.init.as_ref()) .map(|init| match init { Some(e) => match &**e { Expr::Unary(UnaryExpr { op: op!(unary, "-"), .. }) => EnumKind::Num, Expr::Lit(lit) => match lit { Lit::Str(_) => EnumKind::Str, Lit::Num(_) => EnumKind::Num, _ => EnumKind::Mixed, }, _ => EnumKind::Mixed, }, None => EnumKind::Num, }) .fold(None, |opt: Option<EnumKind>, item| { // let a = match item { EnumKind::Mixed => return Some(EnumKind::Mixed), _ => item, }; let b = match opt { Some(EnumKind::Mixed) => return Some(EnumKind::Mixed), Some(v) => v, None => return Some(item), }; if a == b { Some(a) } else { Some(EnumKind::Mixed) } }); if let Some(kind) = enum_kind { self.enums.insert(e.id.sym.clone(), kind); } } } impl VisitMut for TscDecorator { fn visit_mut_class(&mut self, n: &mut Class) { let appended_private = self.appended_private_access_exprs.take(); n.visit_mut_with(&mut ParamMetadata); if self.metadata { let i = self.class_name.clone(); n.visit_mut_with(&mut Metadata::new(&self.enums, i.as_ref())); } n.visit_mut_children_with(self); let appended_private = mem::replace(&mut self.appended_private_access_exprs, appended_private); if !appended_private.is_empty() { let expr = if appended_private.len() == 1 { *appended_private.into_iter().next().unwrap() } else { SeqExpr { exprs: appended_private, ..Default::default() } .into() }; n.body.push( StaticBlock { body: BlockStmt { stmts: vec![expr.into_stmt()], ..Default::default() }, ..Default::default() } .into(), ) } if let Some(class_name) = self.class_name.clone() { if !n.decorators.is_empty() { let decorators = ArrayLit { span: DUMMY_SP, elems: n .decorators .take() .into_iter() .map(|mut v| { remove_span(&mut v.expr); v.expr.as_arg() }) .map(Some) .collect(), } .as_arg(); let decorated = CallExpr { span: DUMMY_SP, callee: helper!(ts, ts_decorate), args: vec![ decorators, class_name .clone() .with_pos(BytePos::DUMMY, BytePos::DUMMY) .as_arg(), ], ..Default::default() } .into(); self.appended_exprs.push( AssignExpr { span: DUMMY_SP, op: op!("="), left: class_name.with_pos(BytePos::DUMMY, BytePos::DUMMY).into(), right: decorated, } .into(), ); } } } fn visit_mut_class_decl(&mut self, n: &mut ClassDecl) { let old = mem::replace(&mut self.class_name, Some(n.ident.clone())); n.visit_mut_children_with(self); self.class_name = old; } fn visit_mut_expr(&mut self, e: &mut Expr) { let appended_exprs = mem::take(&mut self.appended_exprs); e.visit_mut_children_with(self); let appended_exprs = mem::replace(&mut self.appended_exprs, appended_exprs); if let Some(var_name) = self.assign_class_expr_to.take() { self.vars.push(VarDeclarator { span: DUMMY_SP, name: var_name.clone().into(), init: None, definite: Default::default(), }); *e = SeqExpr { span: DUMMY_SP, exprs: iter::once(AssignExpr { span: DUMMY_SP, op: op!("="), left: var_name.clone().into(), right: Box::new(e.take()), }) .map(Into::into) .chain(appended_exprs) .chain(iter::once(var_name.into())) .collect(), } .into(); } } fn visit_mut_class_expr(&mut self, n: &mut ClassExpr) { if !contains_decorator(n) { return; } let ident = n .ident .get_or_insert_with(|| private_ident!("_class")) .clone(); let old = mem::replace(&mut self.class_name, Some(ident.clone())); n.visit_mut_children_with(self); self.assign_class_expr_to = Some(ident); self.class_name = old; } fn visit_mut_export_default_decl(&mut self, n: &mut ExportDefaultDecl) { n.visit_mut_children_with(self); // `export default class` is not expr self.assign_class_expr_to = None; } fn visit_mut_class_method(&mut self, c: &mut ClassMethod) { c.visit_mut_children_with(self); if let Some(class_name) = self.class_name.clone() { if !c.function.decorators.is_empty() { let key = self.key(&mut c.key); let target = if c.is_static { class_name.as_arg() } else { class_name.make_member(quote_ident!("prototype")).as_arg() }; self.add_decorate_call( c.function.decorators.drain(..).map(|d| d.expr), target, key.as_arg(), Lit::Null(Null::dummy()).as_arg(), ); } } } fn visit_mut_class_prop(&mut self, c: &mut ClassProp) { c.visit_mut_children_with(self); if let Some(class_name) = self.class_name.clone() { if !c.decorators.is_empty() { let key = self.key(&mut c.key); let target = if c.is_static { class_name.as_arg() } else { class_name.make_member(quote_ident!("prototype")).as_arg() }; self.add_decorate_call( c.decorators.drain(..).map(|d| d.expr), target, key.as_arg(), Expr::undefined(DUMMY_SP).as_arg(), ); } } } fn visit_mut_module(&mut self, n: &mut Module) { n.visit_with(self); n.visit_mut_children_with(self); } fn visit_mut_module_items(&mut self, s: &mut Vec<ModuleItem>) { self.visit_mut_stmt_likes(s); } fn visit_mut_script(&mut self, n: &mut Script) { n.visit_with(self); n.visit_mut_children_with(self); } fn visit_mut_stmts(&mut self, s: &mut Vec<Stmt>) { self.visit_mut_stmt_likes(s) } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_proposal/src/decorators/mod.rs
Rust
use std::{iter, mem::take}; use either::Either; use serde::Deserialize; use swc_common::{Spanned, DUMMY_SP}; use swc_ecma_ast::{Pass, *}; use swc_ecma_transforms_base::helper; use swc_ecma_transforms_classes::super_field::SuperFieldAccessFolder; use swc_ecma_utils::{ alias_ident_for, constructor::inject_after_super, default_constructor_with_span, prepend_stmt, private_ident, prop_name_to_expr, prop_name_to_expr_value, quote_ident, quote_str, ExprFactory, }; use swc_ecma_visit::{ fold_pass, noop_fold_type, visit_mut_pass, Fold, FoldWith, Visit, VisitMutWith, VisitWith, }; mod legacy; /// ## Simple class decorator /// /// ```js /// /// @annotation /// class MyClass { } /// /// function annotation(target) { /// target.annotated = true; /// } /// ``` /// /// ## Class decorator /// /// ```js /// @isTestable(true) /// class MyClass { } /// /// function isTestable(value) { /// return function decorator(target) { /// target.isTestable = value; /// } /// } /// ``` /// /// ## Class method decorator /// /// ```js /// class C { /// @enumerable(false) /// method() { } /// } /// /// function enumerable(value) { /// return function (target, key, descriptor) { /// descriptor.enumerable = value; /// return descriptor; /// } /// } /// ``` pub fn decorators(c: Config) -> impl Pass { if c.legacy { Either::Left(visit_mut_pass(self::legacy::new(c.emit_metadata))) } else { if c.emit_metadata { unimplemented!("emitting decorator metadata while using new proposal") } Either::Right(fold_pass(Decorators { is_in_strict: false, vars: Default::default(), })) } } #[derive(Debug, Default, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Config { pub legacy: bool, #[serde(default)] pub emit_metadata: bool, pub use_define_for_class_fields: bool, } #[derive(Debug, Default)] struct Decorators { is_in_strict: bool, vars: Vec<VarDeclarator>, } /// TODO: VisitMut impl Fold for Decorators { noop_fold_type!(); fn fold_decl(&mut self, decl: Decl) -> Decl { let decl = decl.fold_children_with(self); match decl { Decl::Class(ClassDecl { ident, declare: false, class, }) => { if !contains_decorator(&class) { return ClassDecl { ident, declare: false, class, } .into(); } let decorate_call = Box::new(self.fold_class_inner(ident.clone(), class)); VarDecl { kind: VarDeclKind::Let, decls: vec![VarDeclarator { span: DUMMY_SP, name: ident.into(), definite: false, init: Some(decorate_call), }], ..Default::default() } .into() } _ => decl, } } fn fold_expr(&mut self, expr: Expr) -> Expr { let expr = expr.fold_children_with(self); match expr { Expr::Class(ClassExpr { ident, class }) => { if !contains_decorator(&class) { return ClassExpr { ident, class }.into(); } self.fold_class_inner( ident.unwrap_or_else(|| quote_ident!("_class").into()), class, ) } _ => expr, } } fn fold_module_decl(&mut self, decl: ModuleDecl) -> ModuleDecl { let decl = decl.fold_children_with(self); match decl { ModuleDecl::ExportDefaultDecl(ExportDefaultDecl { span, decl: DefaultDecl::Class(ClassExpr { ident, class }), .. }) => { let decorate_call = Box::new(self.fold_class_inner( ident.unwrap_or_else(|| quote_ident!("_class").into()), class, )); ExportDefaultExpr { span, expr: decorate_call, } .into() } _ => decl, } } fn fold_module_items(&mut self, items: Vec<ModuleItem>) -> Vec<ModuleItem> { if !contains_decorator(&items) { return items; } let old_strict = self.is_in_strict; self.is_in_strict = true; let mut buf = Vec::with_capacity(items.len() + 4); items.into_iter().for_each(|item| { if !contains_decorator(&item) { buf.push(item); return; } macro_rules! handle_class { ($cls:expr, $ident:expr) => {{ let class = $cls; let ident = $ident; let decorate_call = Box::new(self.fold_class_inner(ident.clone(), class)); buf.push( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Let, declare: false, decls: vec![VarDeclarator { span: DUMMY_SP, name: ident.clone().into(), init: Some(decorate_call), definite: false, }], ..Default::default() } .into(), ); // export { Foo as default } buf.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( NamedExport { span: DUMMY_SP, specifiers: vec![ExportNamedSpecifier { span: DUMMY_SP, orig: ModuleExportName::Ident(ident), exported: Some(ModuleExportName::Ident( quote_ident!("default").into(), )), is_type_only: false, } .into()], src: None, type_only: false, with: None, }, ))); }}; } // match item { ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(ExportDefaultDecl { decl: DefaultDecl::Class(ClassExpr { ident: Some(ident), class, }), .. })) => handle_class!(class, ident), ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(ExportDefaultExpr { span, expr, .. })) => match *expr { Expr::Class(ClassExpr { ident: Some(ident), class, }) => handle_class!(class, ident), _ => { let item: ModuleItem = ExportDefaultExpr { span, expr }.into(); buf.push(item.fold_with(self)); } }, _ => { buf.push(item.fold_with(self)); } } }); self.is_in_strict = old_strict; if !self.vars.is_empty() { prepend_stmt( &mut buf, VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, declare: false, decls: take(&mut self.vars), ..Default::default() } .into(), ) } buf } } impl Decorators { #[allow(clippy::boxed_local)] fn fold_class_inner(&mut self, ident: Ident, mut class: Box<Class>) -> Expr { let initialize = private_ident!("_initialize"); let super_class_ident = class .super_class .as_ref() .map(|expr| alias_ident_for(expr, "_super")); let super_class_expr = class.super_class; class.super_class = super_class_ident.clone().map(|i| i.into()); let constructor = { let initialize_call = CallExpr { span: DUMMY_SP, callee: initialize.clone().as_callee(), args: vec![ThisExpr { span: DUMMY_SP }.as_arg()], ..Default::default() } .into(); // Inject initialize let pos = class.body.iter().position(|member| { matches!( *member, ClassMember::Constructor(Constructor { body: Some(..), .. }) ) }); match pos { Some(pos) => { let mut c = match class.body.remove(pos) { ClassMember::Constructor(c) => c, _ => unreachable!(), }; inject_after_super(&mut c, vec![initialize_call]); ClassMember::Constructor(c) } None => { let mut c = default_constructor_with_span(super_class_ident.is_some(), class.span); c.body .as_mut() .unwrap() .stmts .push(initialize_call.into_stmt()); ClassMember::Constructor(c) } } }; macro_rules! fold_method { ($method:expr, $fn_name:expr, $key_prop_value:expr) => {{ let fn_name = $fn_name; let mut method = $method; let mut folder = SuperFieldAccessFolder { class_name: &ident, constructor_this_mark: None, is_static: method.is_static, folding_constructor: false, in_nested_scope: false, in_injected_define_property_call: false, this_alias_mark: None, // TODO: loose mode constant_super: false, super_class: &None, in_pat: false, }; method.visit_mut_with(&mut folder); // kind: "method", // key: getKeyJ(), // value: function () { // return 2; // } Some( ObjectLit { span: DUMMY_SP, props: iter::once(PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("kind")), value: Box::new(Expr::Lit(Lit::Str(quote_str!( match method.kind { MethodKind::Method => "method", MethodKind::Getter => "get", MethodKind::Setter => "set", } )))), }, )))) .chain(if method.is_static { Some(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(quote_ident!("static")), value: true.into(), })))) } else { None }) .chain({ // if method.function.decorators.is_empty() { None } else { Some(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(quote_ident!("decorators")), value: Box::new(Expr::Array(ArrayLit { span: DUMMY_SP, elems: method .function .decorators .into_iter() .map(|dec| dec.expr.as_arg()) .map(Some) .collect(), })), })))) } }) .chain(iter::once(PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("key")), value: $key_prop_value, }, ))))) .chain(iter::once(PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("value")), value: Box::new( FnExpr { ident: fn_name.map(Ident::from).map(Ident::into_private), function: Function { decorators: Vec::new(), ..*method.function } .into(), } .into(), ), }, ))))) .collect(), } .as_arg(), ) }}; } let descriptors = class .body .into_iter() .filter_map(|member| { // match member { ClassMember::Constructor(_) => unreachable!("multiple constructor?"), ClassMember::TsIndexSignature(_) => None, ClassMember::Method(method) => { let fn_name = match method.key { PropName::Ident(ref i) => Some(i.clone()), PropName::Str(ref s) => Some(IdentName::new(s.value.clone(), s.span)), _ => None, }; let key_prop_value = Box::new(prop_name_to_expr_value(method.key.clone())); fold_method!(method, fn_name, key_prop_value) } ClassMember::PrivateMethod(method) => { let fn_name = Ident::new_no_ctxt( format!("_{}", method.key.name).into(), method.key.span, ); let key_prop_value = Lit::Str(Str { span: method.key.span, raw: None, value: method.key.name.clone(), }) .into(); fold_method!(method, Some(fn_name), key_prop_value) } ClassMember::ClassProp(prop) => { let prop_span = prop.span(); let key_prop_value = match prop.key { PropName::Ident(i) => Lit::Str(Str { span: i.span, raw: None, value: i.sym, }) .into(), _ => prop_name_to_expr(prop.key).into(), }; // Some( ObjectLit { span: prop_span, props: iter::once(PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("kind")), value: Lit::Str(quote_str!("field")).into(), }, )))) .chain(if prop.is_static { Some(PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("static")), value: true.into(), }, )))) } else { None }) .chain({ // if prop.decorators.is_empty() { None } else { Some(PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("decorators")), value: ArrayLit { span: DUMMY_SP, elems: prop .decorators .into_iter() .map(|dec| dec.expr.as_arg()) .map(Some) .collect(), } .into(), }, )))) } }) .chain(iter::once(PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("key")), value: key_prop_value, }, ))))) .chain(iter::once(PropOrSpread::Prop(Box::new(match prop.value { Some(value) => Prop::Method(MethodProp { key: PropName::Ident(quote_ident!("value")), function: Function { span: DUMMY_SP, is_async: false, is_generator: false, decorators: Vec::new(), params: Vec::new(), body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::Return(ReturnStmt { span: DUMMY_SP, arg: Some(value), })], ..Default::default() }), ..Default::default() } .into(), }), _ => Prop::KeyValue(KeyValueProp { key: PropName::Ident(quote_ident!("value")), value: Expr::undefined(DUMMY_SP), }), })))) .collect(), } .as_arg(), ) } _ => unimplemented!("ClassMember::{:?}", member,), } }) .map(Some) .collect(); make_decorate_call( class.decorators, iter::once({ // function(_initialize) {} Function { span: DUMMY_SP, params: iter::once(initialize.into()) .chain(super_class_ident.map(Pat::from)) .map(|pat| Param { span: DUMMY_SP, decorators: Vec::new(), pat, }) .collect(), decorators: Default::default(), is_async: false, is_generator: false, body: Some(BlockStmt { span: DUMMY_SP, stmts: if !self.is_in_strict { // 'use strict'; Some(Lit::Str(quote_str!("use strict")).into_stmt()) } else { None } .into_iter() .chain(iter::once( ClassDecl { ident: ident.clone(), class: Class { decorators: Default::default(), body: vec![constructor], ..*class } .into(), declare: false, } .into(), )) .chain(iter::once( ReturnStmt { span: DUMMY_SP, arg: Some( ObjectLit { span: DUMMY_SP, props: vec![ PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("F")), value: Box::new(Expr::Ident(ident)), }, ))), PropOrSpread::Prop(Box::new(Prop::KeyValue( KeyValueProp { key: PropName::Ident(quote_ident!("d")), value: Box::new(Expr::Array(ArrayLit { span: DUMMY_SP, elems: descriptors, })), }, ))), ], } .into(), ), } .into(), )) .collect(), ..Default::default() }), ..Default::default() } .as_arg() }) .chain(super_class_expr.map(|e| e.as_arg())), ) .into() } } fn make_decorate_call( decorators: Vec<Decorator>, args: impl Iterator<Item = ExprOrSpread>, ) -> CallExpr { CallExpr { span: DUMMY_SP, callee: helper!(decorate), args: iter::once( ArrayLit { span: DUMMY_SP, elems: decorators .into_iter() .map(|dec| Some(dec.expr.as_arg())) .collect(), } .as_arg(), ) .chain(args) .collect(), ..Default::default() } } struct DecoratorFinder { found: bool, } impl Visit for DecoratorFinder { fn visit_decorator(&mut self, _: &Decorator) { self.found = true } } fn contains_decorator<N>(node: &N) -> bool where N: VisitWith<DecoratorFinder>, { let mut v = DecoratorFinder { found: false }; node.visit_with(&mut v); v.found }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs
Rust
use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::helper; use swc_ecma_utils::{ private_ident, quote_ident, stack_size::maybe_grow_default, ExprFactory, ModuleItemLike, StmtLike, }; use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; pub fn explicit_resource_management() -> impl Pass { visit_mut_pass(ExplicitResourceManagement::default()) } #[derive(Default)] struct ExplicitResourceManagement { state: Option<State>, is_not_top_level: bool, } struct State { env: Ident, has_await: bool, vars: Vec<(Pat, Box<Expr>)>, } impl Default for State { fn default() -> Self { Self { env: private_ident!("env"), has_await: false, vars: Vec::new(), } } } impl ExplicitResourceManagement { fn visit_mut_stmt_likes<T>(&mut self, stmts: &mut Vec<T>) where T: StmtLike + ModuleItemLike, Vec<T>: VisitMutWith<Self>, { let old_state = self.state.take(); stmts.visit_mut_children_with(self); if let Some(state) = self.state.take() { self.wrap_with_try(state, stmts); } self.state = old_state; } fn wrap_with_try<T>(&mut self, state: State, stmts: &mut Vec<T>) where T: StmtLike + ModuleItemLike, { let mut new = Vec::new(); let mut extras = Vec::new(); let env = state.env; let catch_e = private_ident!("e"); let is_async = state.has_await; // const env_1 = { stack: [], error: void 0, hasError: false }; new.push(T::from(Stmt::Decl(Decl::Var(Box::new(VarDecl { span: DUMMY_SP, kind: VarDeclKind::Const, declare: false, decls: vec![VarDeclarator { span: DUMMY_SP, name: Pat::Ident(env.clone().into()), init: Some(Box::new(Expr::Object(ObjectLit { span: DUMMY_SP, props: vec![ PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(quote_ident!("stack")), value: Box::new(Expr::Array(ArrayLit { span: DUMMY_SP, elems: vec![], })), }))), PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(quote_ident!("error")), value: Expr::undefined(DUMMY_SP), }))), PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(quote_ident!("hasError")), value: Box::new(Expr::Lit(Lit::Bool(Bool { span: DUMMY_SP, value: false, }))), }))), ], }))), definite: false, }], ..Default::default() }))))); let mut try_block = BlockStmt { stmts: vec![], ..Default::default() }; for (name, disposable) in state.vars { let init_var_decl = Stmt::Decl(Decl::Var(Box::new(VarDecl { span: DUMMY_SP, kind: VarDeclKind::Const, declare: false, decls: vec![VarDeclarator { span: DUMMY_SP, name, init: Some( CallExpr { callee: helper!(ts, ts_add_disposable_resource), args: vec![ env.clone().as_arg(), disposable.as_arg(), is_async.as_arg(), ], ..Default::default() } .into(), ), definite: false, }], ..Default::default() }))); try_block.stmts.push(init_var_decl); } for stmt in stmts.take() { match stmt.try_into_stmt() { Ok(stmt) => try_block.stmts.push(stmt), Err(t) => extras.push(t), } } let catch_clause = CatchClause { span: DUMMY_SP, param: Some(Pat::Ident(catch_e.clone().into())), body: BlockStmt { span: DUMMY_SP, stmts: vec![ // env.e = e; AssignExpr { span: DUMMY_SP, left: MemberExpr { span: DUMMY_SP, obj: Box::new(env.clone().into()), prop: MemberProp::Ident(quote_ident!("error")), } .into(), op: op!("="), right: Box::new(catch_e.clone().into()), } .into_stmt(), // env.hasError = true; AssignExpr { span: DUMMY_SP, left: MemberExpr { span: DUMMY_SP, obj: Box::new(env.clone().into()), prop: MemberProp::Ident(quote_ident!("hasError")), } .into(), op: op!("="), right: Box::new(Expr::Lit(Lit::Bool(Bool { span: DUMMY_SP, value: true, }))), } .into_stmt(), ], ..Default::default() }, }; let finally_block = if is_async { // Code: // const result_1 = _ts_dispose_resources(env_1); // if (result_1) // await result_1; let result = private_ident!("result"); let var_decl = Stmt::Decl(Decl::Var(Box::new(VarDecl { kind: VarDeclKind::Const, decls: vec![VarDeclarator { span: DUMMY_SP, name: Pat::Ident(result.clone().into()), init: Some( CallExpr { callee: helper!(ts, ts_dispose_resources), args: vec![env.clone().as_arg()], ..Default::default() } .into(), ), definite: false, }], ..Default::default() }))); let if_stmt = Stmt::If(IfStmt { span: DUMMY_SP, test: result.clone().into(), // Code: // await result_1; cons: Stmt::Expr(ExprStmt { expr: Box::new(Expr::Await(AwaitExpr { arg: result.clone().into(), ..Default::default() })), ..Default::default() }) .into(), ..Default::default() }); vec![var_decl, if_stmt] } else { // Code: // _ts_dispose_resources(env_1); vec![CallExpr { callee: helper!(ts, ts_dispose_resources), args: vec![env.clone().as_arg()], ..Default::default() } .into_stmt()] }; let try_stmt = TryStmt { span: DUMMY_SP, block: try_block, handler: Some(catch_clause), finalizer: Some(BlockStmt { stmts: finally_block, ..Default::default() }), }; new.push(T::from(try_stmt.into())); new.extend(extras); *stmts = new; } } impl VisitMut for ExplicitResourceManagement { noop_visit_mut_type!(); fn visit_mut_expr(&mut self, n: &mut Expr) { maybe_grow_default(|| n.visit_mut_children_with(self)); } fn visit_mut_for_of_stmt(&mut self, n: &mut ForOfStmt) { n.visit_mut_children_with(self); if let ForHead::UsingDecl(using) = &mut n.left { let mut state = State::default(); state.has_await |= using.is_await; let mut inner_var_decl = VarDecl { kind: VarDeclKind::Const, ..Default::default() }; for decl in &mut using.decls { let new_var = private_ident!("_"); inner_var_decl.decls.push(VarDeclarator { span: DUMMY_SP, name: decl.name.take(), init: Some( CallExpr { callee: helper!(ts, ts_add_disposable_resource), args: vec![ state.env.clone().as_arg(), new_var.clone().as_arg(), using.is_await.as_arg(), ], ..Default::default() } .into(), ), definite: false, }); decl.name = Pat::Ident(new_var.clone().into()); } let var_decl = Box::new(VarDecl { span: DUMMY_SP, kind: VarDeclKind::Const, declare: false, decls: using.decls.take(), ..Default::default() }); let mut body = vec![ Stmt::Decl(Decl::Var(Box::new(inner_var_decl))), *n.body.take(), ]; self.wrap_with_try(state, &mut body); n.left = ForHead::VarDecl(var_decl); n.body = Box::new( BlockStmt { span: DUMMY_SP, stmts: body, ..Default::default() } .into(), ) } } fn visit_mut_module_items(&mut self, stmts: &mut Vec<ModuleItem>) { self.visit_mut_stmt_likes(stmts) } fn visit_mut_stmt(&mut self, s: &mut Stmt) { maybe_grow_default(|| s.visit_mut_children_with(self)); if let Stmt::Decl(Decl::Using(using)) = s { let state = self.state.get_or_insert_with(Default::default); let decl = handle_using_decl(using, state); if decl.decls.is_empty() { s.take(); return; } *s = Stmt::Decl(Decl::Var(decl)); } } fn visit_mut_stmts(&mut self, stmts: &mut Vec<Stmt>) { let old_is_not_top_level = self.is_not_top_level; self.is_not_top_level = true; self.visit_mut_stmt_likes(stmts); self.is_not_top_level = old_is_not_top_level; } } fn handle_using_decl(using: &mut UsingDecl, state: &mut State) -> Box<VarDecl> { state.has_await |= using.is_await; for decl in &mut using.decls { decl.init = Some( CallExpr { callee: helper!(ts, ts_add_disposable_resource), args: vec![ state.env.clone().as_arg(), decl.init.take().unwrap().as_arg(), using.is_await.as_arg(), ], ..Default::default() } .into(), ); } Box::new(VarDecl { span: DUMMY_SP, kind: VarDeclKind::Const, declare: false, decls: using.decls.take(), ..Default::default() }) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University