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_module/tests/fixture/systemjs/export-named-7/output.mjs
JavaScript
System.register([], function (_export, _context) { "use strict"; function foo2(bar) {} _export("foo2", foo2); return { setters: [], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/export-named-8/input.mjs
JavaScript
export {};
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/export-named-8/output.mjs
JavaScript
System.register([], function (_export, _context) { "use strict"; return { setters: [], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/export-named-alongside-with-export-star/input.mjs
JavaScript
export { default } from "foo"; export * from "foo"; export { a, b } from "bar"; export * from "bar";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/export-named-alongside-with-export-star/output.mjs
JavaScript
System.register([ "foo", "bar" ], function(_export, _context) { "use strict"; return { setters: [ function(_foo) { var exportObj = {}; for(var key in _foo){ if (key !== "default" && key !== "__esModule") { exportObj[key] = _foo[key]; } } exportObj.default = _foo.default; _export(exportObj); }, function(_bar) { var exportObj = {}; for(var key in _bar){ if (key !== "default" && key !== "__esModule") { exportObj[key] = _bar[key]; } } exportObj.a = _bar.a; exportObj.b = _bar.b; _export(exportObj); } ], execute: function() {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/export-named/input.mjs
JavaScript
export { foo }; var foo;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/export-named/output.mjs
JavaScript
System.register([], function (_export, _context) { "use strict"; var foo; _export("foo", void 0); return { setters: [], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/export-uninitialized/input.mjs
JavaScript
export var m;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/export-uninitialized/output.mjs
JavaScript
System.register([], function (_export, _context) { "use strict"; var m; _export("m", void 0); return { setters: [], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/exports-variable/input.mjs
JavaScript
export var foo = 1; export var foo2 = function () {}; export var foo3; export let foo4 = 2; export let foo5; export const foo6 = 3; export function foo7() {} export class foo8 {} foo3 = 5;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/exports-variable/output.mjs
JavaScript
System.register([], function(_export, _context) { "use strict"; var foo8, foo, foo2, foo3, foo4, foo5, foo6; function foo7() {} _export({ foo7: foo7, foo8: void 0, foo3: void 0, foo5: void 0 }); return { setters: [], execute: function() { _export("foo", foo = 1); _export("foo2", foo2 = function() {}); _export("foo4", foo4 = 2); _export("foo6", foo6 = 3); _export("foo8", foo8 = class foo8 { }); _export("foo3", foo3 = 5); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/hoist-function-class/input.mjs
JavaScript
export function hoisted() { return HoistedClass, HoistedClassExport, HoistedClassDefaultExport; } class HoistedClass {} export class HoistedClassExport {} export default class HoistedClassDefaultExport {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/hoist-function-class/output.mjs
JavaScript
System.register([], function(_export, _context) { "use strict"; var HoistedClass, HoistedClassExport, HoistedClassDefaultExport; function hoisted() { return HoistedClass, HoistedClassExport, HoistedClassDefaultExport; } _export({ hoisted: hoisted, HoistedClassExport: void 0, "default": void 0 }); return { setters: [], execute: function() { HoistedClass = class HoistedClass { }; _export("HoistedClassExport", HoistedClassExport = class HoistedClassExport { }); _export("default", HoistedClassDefaultExport = class HoistedClassDefaultExport { }); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/hoist-function-exports/input.mjs
JavaScript
import { isEven } from "./evens"; export function nextOdd(n) { return (p = isEven(n) ? n + 1 : n + 2); } export var p = 5; for (var a in b); for (var i = 0, j = 0; ; ); export var isOdd = (function (isEven) { return function (n) { return !isEven(n); }; })(isEven);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/hoist-function-exports/output.mjs
JavaScript
System.register([ "./evens" ], function(_export, _context) { "use strict"; var isEven, p, a, i, j, isOdd; function nextOdd(n) { return _export("p", p = isEven(n) ? n + 1 : n + 2); } _export("nextOdd", nextOdd); return { setters: [ function(_evens) { isEven = _evens.isEven; } ], execute: function() { _export("p", p = 5); for(a in b); for(i = 0, j = 0;;); _export("isOdd", isOdd = function(isEven) { return function(n) { return !isEven(n); }; }(isEven)); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/hoisting-bindings/input.mjs
JavaScript
export function a() { alert("a"); c++; } export var c = 5; function b() { a(); } b(); function foo(c) { alert("a"); c++; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/hoisting-bindings/output.mjs
JavaScript
System.register([], function(_export, _context) { "use strict"; var c; function a() { alert("a"); _export("c", +c + 1), c++; } function b() { a(); } function foo(c) { alert("a"); c++; } _export("a", a); return { setters: [], execute: function() { _export("c", c = 5); b(); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/import-meta/input.mjs
JavaScript
console.log(import.meta.url);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/import-meta/output.mjs
JavaScript
System.register([], function (_export, _context) { "use strict"; return { setters: [], execute: function () { console.log(_context.meta.url); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports-default/input.mjs
JavaScript
import foo from "foo"; import { default as foo2 } from "foo";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports-default/output.mjs
JavaScript
System.register(["foo"], function (_export, _context) { "use strict"; var foo, foo2; return { setters: [function (_foo) { foo = _foo.default; foo2 = _foo.default; }], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports-glob/input.mjs
JavaScript
import * as foo from "foo";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports-glob/output.mjs
JavaScript
System.register(["foo"], function (_export, _context) { "use strict"; var foo; return { setters: [function (_foo) { foo = _foo; }], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports-mixing/input.mjs
JavaScript
import foo, { baz as xyz } from "foo";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports-mixing/output.mjs
JavaScript
System.register(["foo"], function (_export, _context) { "use strict"; var foo, xyz; return { setters: [function (_foo) { foo = _foo.default; xyz = _foo.baz; }], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports-named/input.mjs
JavaScript
import { bar } from "foo"; import { bar2, baz } from "foo"; import { bar as baz2 } from "foo"; import { bar as baz3, xyz } from "foo";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports-named/output.mjs
JavaScript
System.register(["foo"], function (_export, _context) { "use strict"; var bar, bar2, baz, baz2, baz3, xyz; return { setters: [function (_foo) { bar = _foo.bar; bar2 = _foo.bar2; baz = _foo.baz; baz2 = _foo.bar; baz3 = _foo.bar; xyz = _foo.xyz; }], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports-numbered/input.mjs
JavaScript
import "2"; import "1";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports-numbered/output.mjs
JavaScript
System.register([ "2", "1" ], function(_export, _context) { "use strict"; return { setters: [ function(_2) {}, function(_1) {} ], execute: function() {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports/input.mjs
JavaScript
import "foo"; import "foo-bar"; import "./directory/foo-bar";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/imports/output.mjs
JavaScript
System.register([ "foo", "foo-bar", "./directory/foo-bar" ], function(_export, _context) { "use strict"; return { setters: [ function(_foo) {}, function(_foobar) {}, function(_foobar) {} ], execute: function() {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/export-from-string-as-string/input.mjs
JavaScript
export { "some imports" as "some exports" } from "foo";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/export-from-string-as-string/output.mjs
JavaScript
System.register(["foo"], function (_export, _context) { "use strict"; return { setters: [function (_foo) { _export("some exports", _foo["some imports"]); }], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/export-from-string/input.mjs
JavaScript
export { "some exports" } from "foo";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/export-from-string/output.mjs
JavaScript
System.register(["foo"], function (_export, _context) { "use strict"; return { setters: [function (_foo) { _export("some exports", _foo["some exports"]); }], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/export-from/input.mjs
JavaScript
export { foo as "some exports" } from "foo";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/export-from/output.mjs
JavaScript
System.register(["foo"], function (_export, _context) { "use strict"; return { setters: [function (_foo) { _export("some exports", _foo.foo); }], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/export-named-string-can-be-identifier/input.mjs
JavaScript
var foo, bar; export { foo as "defaultExports", bar };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/export-named-string-can-be-identifier/output.mjs
JavaScript
System.register([], function (_export, _context) { "use strict"; var foo, bar; _export({ defaultExports: void 0, bar: void 0 }); return { setters: [], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/export-named/input.mjs
JavaScript
var foo, bar; export { foo as "default exports", bar };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/export-named/output.mjs
JavaScript
System.register([], function (_export, _context) { "use strict"; var foo, bar; _export({ "default exports": void 0, bar: void 0 }); return { setters: [], execute: function () {} }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/import-named-string-can-be-identifier/input.mjs
JavaScript
import { "defaultImports" as bar } from "foo"; bar;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/import-named-string-can-be-identifier/output.mjs
JavaScript
System.register(["foo"], function (_export, _context) { "use strict"; var bar; return { setters: [function (_foo) { bar = _foo["defaultImports"]; }], execute: function () { bar; } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/import-named/input.mjs
JavaScript
import { "default imports" as bar } from "foo"; bar;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/interop-module-string-names/import-named/output.mjs
JavaScript
System.register(["foo"], function (_export, _context) { "use strict"; var bar; return { setters: [function (_foo) { bar = _foo["default imports"]; }], execute: function () { bar; } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/module-name/input.mjs
JavaScript
export var name = __moduleName;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/module-name/output.mjs
JavaScript
System.register([], function (_export, _context) { "use strict"; var name; return { setters: [], execute: function () { _export("name", name = _context.id); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/overview/input.mjs
JavaScript
import "foo"; import "foo-bar"; import "./directory/foo-bar"; import foo from "foo"; import * as foo2 from "foo"; import { bar } from "foo"; import { foo as bar2 } from "foo"; export { foo }; export var test2 = 5; export default foo;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/overview/output.mjs
JavaScript
System.register([ "foo", "foo-bar", "./directory/foo-bar" ], function(_export, _context) { "use strict"; var foo, foo2, bar, bar2, test2; return { setters: [ function(_foo) { foo = _foo.default; foo2 = _foo; bar = _foo.bar; bar2 = _foo.foo; }, function(_foobar) {}, function(_foobar) {} ], execute: function() { _export("foo", foo); _export("test2", test2 = 5); _export("default", foo); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/regression/input.mjs
JavaScript
let Vec3; export class Light { _color = Vec3; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/regression/output.mjs
JavaScript
System.register([], function(_export, _context) { "use strict"; var Light, Vec3; _export("Light", void 0); return { setters: [], execute: function() { _export("Light", Light = class Light { _color = Vec3; }); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/remap/input.mjs
JavaScript
export var test = 2; test = 5; test++; (function () { var test = 2; test = 3; test++; })(); var a = 2; export { a }; a = 3; var b = 2; export { b as c }; b = 3; var d = 3; export { d as e, d as f }; d = 4;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/remap/output.mjs
JavaScript
System.register([], function(_export, _context) { "use strict"; var test, a, b, d; return { setters: [], execute: function() { _export("test", test = 2); _export("test", test = 5); _export("test", +test + 1), test++; (function() { var test = 2; test = 3; test++; })(); _export("a", a = 2); _export("a", a = 3); _export("c", b = 2); _export("c", b = 3); _export("f", _export("e", d = 3)); _export("f", _export("e", d = 4)); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/tla/not-tla/input.mjs
JavaScript
async () => await test;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/tla/not-tla/output.mjs
JavaScript
System.register([], function(_export, _context) { "use strict"; return { setters: [], execute: async function() { async ()=>await test ; } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/tla/tla-block/input.mjs
JavaScript
if (maybe) { await test; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/systemjs/tla/tla-block/output.mjs
JavaScript
System.register([], function (_export, _context) { "use strict"; return { setters: [], execute: async function () { if (maybe) { await test; } } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/path_node.rs
Rust
use std::{ path::{Path, PathBuf}, sync::Arc, }; use indexmap::IndexMap; use serde::Deserialize; use swc_common::FileName; use swc_ecma_loader::resolvers::{node::NodeModulesResolver, tsc::TsConfigResolver}; use swc_ecma_parser::Syntax; use swc_ecma_transforms_module::{ path::{ImportResolver, NodeImportResolver}, rewriter::import_rewriter, }; use swc_ecma_transforms_testing::{test_fixture, FixtureTestConfig}; use testing::run_test2; type TestProvider = NodeImportResolver<NodeModulesResolver>; #[test] fn node_modules() { let provider = TestProvider::default(); run_test2(false, |cm, _| { let fm = cm.new_source_file(FileName::Real("foo".into()).into(), "".into()); let resolved = provider .resolve_import(&fm.name, "core-js") .expect("should success"); assert_eq!(&*resolved, "core-js"); Ok(()) }) .unwrap(); } #[test] fn issue_4730() { let dir = Path::new("tests/fixture-manual/issue-4730") .canonicalize() .unwrap(); let input_dir = dir.join("input"); let output_dir = dir.join("output"); test_fixture( Syntax::default(), &|_| { let mut paths = IndexMap::new(); paths.insert( "@print/a".into(), vec![dir .join("input") .join("packages") .join("a") .join("src") .join("index.js") .display() .to_string()], ); paths.insert( "@print/b".into(), vec![dir .join("input") .join("packages") .join("b") .join("src") .join("index.js") .display() .to_string()], ); let rules = paths.into_iter().collect(); let resolver = paths_resolver(&input_dir, rules); import_rewriter( FileName::Real(input_dir.join("src").join("index.js")), Arc::new(resolver), ) }, &input_dir.join("src").join("index.js"), &output_dir.join("index.js"), FixtureTestConfig { module: Some(true), ..Default::default() }, ); } type JscPathsProvider = NodeImportResolver<TsConfigResolver<NodeModulesResolver>>; fn paths_resolver(base_dir: &Path, rules: Vec<(String, Vec<String>)>) -> JscPathsProvider { let base_dir = base_dir .to_path_buf() .canonicalize() .expect("failed to canonicalize"); dbg!(&base_dir); NodeImportResolver::with_config( TsConfigResolver::new( NodeModulesResolver::new(swc_ecma_loader::TargetEnv::Node, Default::default(), true), base_dir.clone(), rules, ), swc_ecma_transforms_module::path::Config { base_dir: Some(base_dir), resolve_fully: true, file_extension: swc_ecma_transforms_module::util::Config::default_js_ext(), }, ) } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct TestConfig { #[serde(default)] base_url: Option<PathBuf>, #[serde(default)] input_file: Option<String>, #[serde(default)] paths: IndexMap<String, Vec<String>>, } #[testing::fixture("tests/paths/**/input")] fn fixture(input_dir: PathBuf) { let output_dir = input_dir.parent().unwrap().join("output"); let paths_json_path = input_dir.join("config.json"); let paths_json = std::fs::read_to_string(paths_json_path).unwrap(); let config = serde_json::from_str::<TestConfig>(&paths_json).unwrap(); let index_path = input_dir.join(config.input_file.as_deref().unwrap_or("index.ts")); dbg!(&index_path); let base_dir = input_dir .join(config.base_url.clone().unwrap_or(input_dir.clone())) .canonicalize() .unwrap(); dbg!(&base_dir); test_fixture( Syntax::default(), &|_| { let rules = config.paths.clone().into_iter().collect(); let resolver = paths_resolver(&base_dir, rules); import_rewriter(FileName::Real(index_path.clone()), Arc::new(resolver)) }, &index_path, &output_dir.join("index.ts"), FixtureTestConfig { module: Some(true), ..Default::default() }, ); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/.issue-6530/1-respect-base-url/input/src/folder/file1.ts
TypeScript
import jq from "jquery"; import file from "folder/file2"; console.log(jq, file);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/.issue-6530/1-respect-base-url/input/src/folder/file2.ts
TypeScript
export default 'used'
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/.issue-6530/1-respect-base-url/input/src/index.ts
TypeScript
import jq from "jquery"; import file from "./folder/file2"; console.log(jq, file);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/.issue-6530/2-check-file-existence/input/src/folder/file1.ts
TypeScript
import jq from "../jquery"; import file from "./file2"; console.log(jq, file);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/.issue-6530/2-check-file-existence/input/src/folder/file2.ts
TypeScript
export default 'used'
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/.issue-6530/2-check-file-existence/input/src/index.ts
TypeScript
import jq from "./jquery"; import file from "./folder/file2"; console.log(jq, file);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/.issue-6530/3-exact-pattern/input/src/index.ts
TypeScript
import jq from 'jquery'; import file from "folder/file2"; console.log(jq, file)
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4532/input/index.ts
TypeScript
import "@src/rel.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4532/output/index.ts
TypeScript
import "./rel.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4585/input/index.ts
TypeScript
import "@lib/feat.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4585/output/index.ts
TypeScript
import "./src/feat.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4605/1/input/index.ts
TypeScript
import "@src/rel.decorator.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4605/1/output/index.ts
TypeScript
import "./src/rel.decorator.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4605/2/input/index.ts
TypeScript
import "@src/rel.decorator";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4605/2/output/index.ts
TypeScript
import "./src/rel.decorator.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4607/input/index.ts
TypeScript
import boo from "utils/shared/foo/boo"; console.log(boo());
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4607/input/src/utils/shared/foo/boo.ts
TypeScript
export { }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4607/output/index.ts
TypeScript
import boo from "./src/utils/shared/foo/boo.js"; console.log(boo());
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4619/1/input/index.ts
TypeScript
import "@src/rel.decorator.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4619/1/output/index.ts
TypeScript
import "./src/rel.decorator.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4619/2/input/index.ts
TypeScript
import "@src/rel.decorator";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-4619/2/output/index.ts
TypeScript
import "./src/rel.decorator.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-6159/input/index.ts
TypeScript
import "@/a.js"; export {} from "@/a.js"; export * from "@/a.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-6159/input/src/a.js
JavaScript
export { }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-6159/output/index.ts
TypeScript
import "./src/a.js"; export { } from "./src/a.js"; export * from "./src/a.js";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-6779/1/input/index.ts
TypeScript
async function main() { const addFunction = (await import('@/utils/add')).default // This doesn't work console.log('2 + 3 =', addFunction(2, 3)) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-6779/1/output/index.ts
TypeScript
async function main() { const addFunction = (await import("./add.js")).default // This doesn't work ; console.log('2 + 3 =', addFunction(2, 3)); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-6779/2/input/index.ts
TypeScript
import addFunction from '@/utils/add' async function main() { console.log('2 + 3 =', addFunction(2, 3)) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-6779/2/output/index.ts
TypeScript
import addFunction from "./add.js"; async function main() { console.log('2 + 3 =', addFunction(2, 3)); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-7417/input/src/index.ts
TypeScript
async function main() { import('./lib/foo') } main()
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-7417/input/src/lib/foo.ts
TypeScript
import o from '.' export default function bar() { console.log(o) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-7417/input/src/lib/index.ts
TypeScript
export default {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/issue-7417/output/index.ts
TypeScript
import o from "./index.js"; export default function bar() { console.log(o); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/pack-1682/1/input/db/PrismaClientProvider.js
JavaScript
import { PrismaClient } from "@/db/client"; class PrismaClientProvider { prisma; constructor() { this.prisma = new PrismaClient({ datasources: { db: { url: "", }, }, }); } } export default new PrismaClientProvider();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/pack-1682/1/input/db/client/index-browser.js
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/pack-1682/1/input/utils/test.js
JavaScript
import PrismaClientProvider from "@/db/PrismaClientProvider"; export default function setupTests() { const context = {}; beforeEach(() => { context.prisma = PrismaClientProvider.prisma; }); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/paths/pack-1682/1/output/index.ts
TypeScript
import PrismaClientProvider from "../db/PrismaClientProvider.js"; export default function setupTests() { const context = {}; beforeEach(()=>{ context.prisma = PrismaClientProvider.prisma; }); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/system_js.rs
Rust
#![deny(warnings)] use std::path::PathBuf; use swc_common::Mark; use swc_ecma_ast::Pass; use swc_ecma_parser::Syntax; use swc_ecma_transforms_base::resolver; use swc_ecma_transforms_module::system_js::{system_js, Config}; use swc_ecma_transforms_testing::{test, test_fixture, FixtureTestConfig, Tester}; fn syntax() -> Syntax { Syntax::Es(Default::default()) } fn tr(_tester: &mut Tester<'_>, config: Config) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), system_js(Default::default(), unresolved_mark, config), ) } test!( module, syntax(), |tester| tr(tester, Default::default()), allow_continuous_assignment, r#"var e = {}; e.a = e.b = e.c = e.d = e.e = e.f = e.g = e.h = e.i = e.j = e.k = e.l = e.m = e.n = e.o = e.p = e.q = e.r = e.s = e.t = e.u = e.v = e.w = e.x = e.y = e.z = e.A = e.B = e.C = e.D = e.E = e.F = e.G = e.H = e.I = e.J = e.K = e.L = e.M = e.N = e.O = e.P = e.Q = e.R = e.S = void 0;"# ); test!( module, syntax(), |tester| tr( tester, Config { allow_top_level_this: true, ..Default::default() } ), allow_top_level_this_true, r#"export var v = this;"# ); test!( module, syntax(), |tester| tr( tester, Config { allow_top_level_this: false, ..Default::default() } ), iife, r#" (function(a) { this.foo = a; })(this); "# ); test!( module, syntax(), |tester| tr( tester, Config { allow_top_level_this: false, ..Default::default() } ), top_level_this_false_class, r#" const a = this; class A { constructor() { this.a = 1; } test() { this.a = 2; } }"# ); test!( module, syntax(), |tester| tr( tester, Config { allow_top_level_this: false, ..Default::default() } ), allow_top_level_this_false, r#"export var v = this; function a() { function d () {} var b = this; } "# ); test!( module, syntax(), |tester| tr(tester, Default::default()), imports, r#" import.meta.url; import.meta.fn(); await import('./test2'); "# ); // TODO: test get-module-name-option, tla #[testing::fixture("tests/fixture/systemjs/**/input.mjs")] fn fixture(input: PathBuf) { let dir = input.parent().unwrap().to_path_buf(); let output = dir.join("output.mjs"); test_fixture( syntax(), &|tester| tr(tester, Default::default()), &input, &output, FixtureTestConfig { module: Some(true), ..Default::default() }, ); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/umd.rs
Rust
use std::{fs::File, path::PathBuf}; use swc_common::Mark; use swc_ecma_ast::Pass; use swc_ecma_parser::{Syntax, TsSyntax}; use swc_ecma_transforms_base::{feature::FeatureFlag, resolver}; use swc_ecma_transforms_module::umd::{umd, Config}; use swc_ecma_transforms_testing::{test_fixture, FixtureTestConfig, Tester}; use swc_ecma_transforms_typescript::typescript; fn syntax() -> Syntax { Default::default() } fn ts_syntax() -> Syntax { Syntax::Typescript(TsSyntax::default()) } fn tr(tester: &mut Tester<'_>, config: Config, typescript: bool) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); let avalible_set = FeatureFlag::all(); ( resolver(unresolved_mark, top_level_mark, typescript), typescript::typescript(Default::default(), unresolved_mark, top_level_mark), umd( tester.cm.clone(), Default::default(), unresolved_mark, config, avalible_set, ), ) } #[testing::fixture("tests/fixture/common/**/input.js")] #[testing::fixture("tests/fixture/common/**/input.ts")] #[testing::fixture("tests/fixture/common/**/input.cts")] fn esm_to_umd(input: PathBuf) { let is_ts = input .file_name() .map(|x| x.to_string_lossy()) .map(|x| x.ends_with(".ts") || x.ends_with(".mts") || x.ends_with(".cts")) .unwrap_or_default(); let dir = input.parent().unwrap().to_path_buf(); let output = dir .join("output.umd.js") .with_extension(if is_ts { "ts" } else { "js" }); let umd_config_path = dir.join("module.umd.json"); let config_path = dir.join("module.json"); let config: Config = match File::open(umd_config_path).or_else(|_| File::open(config_path)) { Ok(file) => serde_json::from_reader(file).unwrap(), Err(..) => Default::default(), }; test_fixture( if is_ts { ts_syntax() } else { syntax() }, &|tester| tr(tester, config.clone(), is_ts), &input, &output, FixtureTestConfig { module: Some(true), ..Default::default() }, ); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/src/const_modules.rs
Rust
use std::{ collections::{HashMap, HashSet}, sync::Arc, }; use dashmap::DashMap; use once_cell::sync::Lazy; use rustc_hash::{FxBuildHasher, FxHashMap}; use swc_atoms::{atom, Atom}; use swc_common::{ errors::HANDLER, sync::Lrc, util::{move_map::MoveMap, take::Take}, FileName, SourceMap, }; use swc_ecma_ast::*; use swc_ecma_parser::parse_file_as_expr; use swc_ecma_utils::drop_span; use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; pub fn const_modules( cm: Lrc<SourceMap>, globals: FxHashMap<Atom, FxHashMap<Atom, String>>, ) -> impl Pass { visit_mut_pass(ConstModules { globals: globals .into_iter() .map(|(src, map)| { let map = map .into_iter() .map(|(key, value)| { let value = parse_option(&cm, &key, value); (key, value) }) .collect(); (src, map) }) .collect(), scope: Default::default(), }) } fn parse_option(cm: &SourceMap, name: &str, src: String) -> Arc<Expr> { static CACHE: Lazy<DashMap<String, Arc<Expr>, FxBuildHasher>> = Lazy::new(DashMap::default); let fm = cm.new_source_file( FileName::Internal(format!("<const-module-{}.js>", name)).into(), src, ); if let Some(expr) = CACHE.get(&**fm.src) { return expr.clone(); } let expr = parse_file_as_expr( &fm, Default::default(), Default::default(), None, &mut Vec::new(), ) .map_err(|e| { if HANDLER.is_set() { HANDLER.with(|h| e.into_diagnostic(h).emit()) } }) .map(drop_span) .unwrap_or_else(|()| { panic!( "failed to parse jsx option {}: '{}' is not an expression", name, fm.src, ) }); let expr = Arc::new(*expr); CACHE.insert((*fm.src).clone(), expr.clone()); expr } struct ConstModules { globals: HashMap<Atom, HashMap<Atom, Arc<Expr>>>, scope: Scope, } #[derive(Default)] struct Scope { namespace: HashSet<Id>, imported: HashMap<Atom, Arc<Expr>>, } impl VisitMut for ConstModules { noop_visit_mut_type!(fail); fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) { *n = n.take().move_flat_map(|item| match item { ModuleItem::ModuleDecl(ModuleDecl::Import(import)) => { let entry = self.globals.get(&import.src.value); if let Some(entry) = entry { for s in &import.specifiers { match *s { ImportSpecifier::Named(ref s) => { let imported = s .imported .as_ref() .map(|m| match m { ModuleExportName::Ident(id) => &id.sym, ModuleExportName::Str(s) => &s.value, }) .unwrap_or(&s.local.sym); let value = entry.get(imported).cloned().unwrap_or_else(|| { panic!( "The requested const_module `{}` does not provide an \ export named `{}`", import.src.value, imported ) }); self.scope.imported.insert(imported.clone(), value); } ImportSpecifier::Namespace(ref s) => { self.scope.namespace.insert(s.local.to_id()); } ImportSpecifier::Default(ref s) => { let imported = &s.local.sym; let default_import_key = atom!("default"); let value = entry.get(&default_import_key).cloned().unwrap_or_else(|| { panic!( "The requested const_module `{}` does not provide \ default export", import.src.value ) }); self.scope.imported.insert(imported.clone(), value); } }; } None } else { Some(import.into()) } } _ => Some(item), }); if self.scope.imported.is_empty() && self.scope.namespace.is_empty() { return; } n.visit_mut_children_with(self); } fn visit_mut_expr(&mut self, n: &mut Expr) { match n { Expr::Ident(ref id @ Ident { ref sym, .. }) => { if let Some(value) = self.scope.imported.get(sym) { *n = (**value).clone(); return; } if self.scope.namespace.contains(&id.to_id()) { panic!( "The const_module namespace `{}` cannot be used without member accessor", sym ) } } Expr::Member(MemberExpr { obj, prop, .. }) if obj.is_ident() => { if let Some(module_name) = obj .as_ident() .filter(|member_obj| self.scope.namespace.contains(&member_obj.to_id())) .map(|member_obj| &member_obj.sym) { let imported_name = match prop { MemberProp::Ident(ref id) => &id.sym, MemberProp::Computed(ref p) => match &*p.expr { Expr::Lit(Lit::Str(s)) => &s.value, _ => return, }, MemberProp::PrivateName(..) => return, }; let value = self .globals .get(module_name) .and_then(|entry| entry.get(imported_name)) .unwrap_or_else(|| { panic!( "The requested const_module `{}` does not provide an export named \ `{}`", module_name, imported_name ) }); *n = (**value).clone(); } else { n.visit_mut_children_with(self); } } _ => { n.visit_mut_children_with(self); } }; } fn visit_mut_prop(&mut self, n: &mut Prop) { match n { Prop::Shorthand(id) => { if let Some(value) = self.scope.imported.get(&id.sym) { *n = Prop::KeyValue(KeyValueProp { key: id.take().into(), value: Box::new((**value).clone()), }); return; } if self.scope.namespace.contains(&id.to_id()) { panic!( "The const_module namespace `{}` cannot be used without member accessor", id.sym ) } } _ => n.visit_mut_children_with(self), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/src/debug.rs
Rust
#![allow(unused)] use std::{fmt::Debug, mem::forget}; use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; /// Assert in debug mode. This is noop in release build. #[cfg_attr(not(debug_assertions), inline(always))] pub fn debug_assert_valid<N>(node: &N) where N: VisitWith<AssertValid>, { #[cfg(debug_assertions)] node.visit_with(&mut AssertValid); } #[cfg(debug_assertions)] struct Ctx<'a> { v: &'a dyn Debug, } #[cfg(debug_assertions)] impl Drop for Ctx<'_> { fn drop(&mut self) { eprintln!("Context: {:?}", self.v); } } pub struct AssertValid; impl Visit for AssertValid { noop_visit_type!(fail); #[cfg(debug_assertions)] fn visit_expr(&mut self, n: &Expr) { let ctx = Ctx { v: n }; n.visit_children_with(self); forget(ctx); } #[cfg(debug_assertions)] fn visit_invalid(&mut self, _: &Invalid) { panic!("Invalid node found"); } #[cfg(debug_assertions)] fn visit_number(&mut self, n: &Number) { assert!(!n.value.is_nan(), "NaN should be an identifier"); } #[cfg(debug_assertions)] fn visit_setter_prop(&mut self, p: &SetterProp) { p.body.visit_with(self); } #[cfg(debug_assertions)] fn visit_stmt(&mut self, n: &Stmt) { let ctx = Ctx { v: n }; n.visit_children_with(self); forget(ctx); } #[cfg(debug_assertions)] fn visit_tpl(&mut self, l: &Tpl) { l.visit_children_with(self); assert_eq!(l.exprs.len() + 1, l.quasis.len()); } #[cfg(debug_assertions)] fn visit_var_declarators(&mut self, v: &[VarDeclarator]) { v.visit_children_with(self); if v.is_empty() { panic!("Found empty var declarators"); } } #[cfg(debug_assertions)] fn visit_seq_expr(&mut self, v: &SeqExpr) { v.visit_children_with(self); // TODO(kdy1): Make parser does not create invalid sequential // expressions and uncomment this // assert!( // v.exprs.len() >= 2, // "SeqExpr(len = {}) is invalid", // v.exprs.len() // ); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_optimization/src/inline_globals.rs
Rust
use rustc_hash::{FxHashMap, FxHashSet}; use swc_atoms::Atom; use swc_common::sync::Lrc; use swc_ecma_ast::*; use swc_ecma_transforms_base::perf::{ParVisitMut, Parallel}; use swc_ecma_utils::{collect_decls, parallel::cpu_count, NodeIgnoringSpan}; use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; /// The key will be compared using [EqIgnoreSpan::eq_ignore_span], and matched /// expressions will be replaced with the value. pub type GlobalExprMap = Lrc<FxHashMap<NodeIgnoringSpan<'static, Expr>, Expr>>; /// Create a global inlining pass, which replaces expressions with the specified /// value. pub fn inline_globals( envs: Lrc<FxHashMap<Atom, Expr>>, globals: Lrc<FxHashMap<Atom, Expr>>, typeofs: Lrc<FxHashMap<Atom, Atom>>, ) -> impl Pass { inline_globals2(envs, globals, Default::default(), typeofs) } /// Create a global inlining pass, which replaces expressions with the specified /// value. /// /// See [GlobalExprMap] for description. /// /// Note: Values specified in `global_exprs` have higher precedence than pub fn inline_globals2( envs: Lrc<FxHashMap<Atom, Expr>>, globals: Lrc<FxHashMap<Atom, Expr>>, global_exprs: GlobalExprMap, typeofs: Lrc<FxHashMap<Atom, Atom>>, ) -> impl Pass { visit_mut_pass(InlineGlobals { envs, globals, global_exprs, typeofs, bindings: Default::default(), }) } #[derive(Clone)] struct InlineGlobals { envs: Lrc<FxHashMap<Atom, Expr>>, globals: Lrc<FxHashMap<Atom, Expr>>, global_exprs: Lrc<FxHashMap<NodeIgnoringSpan<'static, Expr>, Expr>>, typeofs: Lrc<FxHashMap<Atom, Atom>>, bindings: Lrc<FxHashSet<Id>>, } impl Parallel for InlineGlobals { fn create(&self) -> Self { self.clone() } fn merge(&mut self, _: Self) {} } impl VisitMut for InlineGlobals { noop_visit_mut_type!(fail); fn visit_mut_class_members(&mut self, members: &mut Vec<ClassMember>) { self.visit_mut_par(cpu_count(), members); } fn visit_mut_expr(&mut self, expr: &mut Expr) { if let Expr::Ident(Ident { ref sym, ctxt, .. }) = expr { if self.bindings.contains(&(sym.clone(), *ctxt)) { return; } } if let Some(value) = Ident::within_ignored_ctxt(|| self.global_exprs.get(&NodeIgnoringSpan::borrowed(expr))) { *expr = value.clone(); expr.visit_mut_with(self); return; } expr.visit_mut_children_with(self); match expr { Expr::Ident(Ident { ref sym, .. }) => { // It's ok because we don't recurse into member expressions. if let Some(value) = self.globals.get(sym) { let mut value = value.clone(); value.visit_mut_with(self); *expr = value; } } Expr::Unary(UnaryExpr { span, op: op!("typeof"), arg, .. }) => { if let Expr::Ident(Ident { ref sym, ctxt: arg_ctxt, .. }) = &**arg { if self.bindings.contains(&(sym.clone(), *arg_ctxt)) { return; } // It's ok because we don't recurse into member expressions. if let Some(value) = self.typeofs.get(sym).cloned() { *expr = Lit::Str(Str { span: *span, raw: None, value, }) .into(); } } } Expr::Member(MemberExpr { obj, prop, .. }) => match &**obj { Expr::Member(MemberExpr { obj: first_obj, prop: inner_prop, .. }) if inner_prop.is_ident_with("env") => { if first_obj.is_ident_ref_to("process") { match prop { MemberProp::Computed(ComputedPropName { expr: c, .. }) => { if let Expr::Lit(Lit::Str(Str { value: sym, .. })) = &**c { if let Some(env) = self.envs.get(sym) { *expr = env.clone(); } } } MemberProp::Ident(IdentName { sym, .. }) => { if let Some(env) = self.envs.get(sym) { *expr = env.clone(); } } _ => {} } } } _ => (), }, _ => {} } } fn visit_mut_expr_or_spreads(&mut self, n: &mut Vec<ExprOrSpread>) { self.visit_mut_par(cpu_count(), n); } fn visit_mut_exprs(&mut self, n: &mut Vec<Box<Expr>>) { self.visit_mut_par(cpu_count(), n); } fn visit_mut_module(&mut self, module: &mut Module) { self.bindings = Lrc::new(collect_decls(&*module)); module.visit_mut_children_with(self); } fn visit_mut_opt_vec_expr_or_spreads(&mut self, n: &mut Vec<Option<ExprOrSpread>>) { self.visit_mut_par(cpu_count(), n); } fn visit_mut_prop(&mut self, p: &mut Prop) { p.visit_mut_children_with(self); if let Prop::Shorthand(i) = p { if self.bindings.contains(&i.to_id()) { return; } // It's ok because we don't recurse into member expressions. if let Some(mut value) = self.globals.get(&i.sym).cloned().map(Box::new) { value.visit_mut_with(self); *p = Prop::KeyValue(KeyValueProp { key: PropName::Ident(i.clone().into()), value, }); } } } fn visit_mut_prop_or_spreads(&mut self, n: &mut Vec<PropOrSpread>) { self.visit_mut_par(cpu_count(), n); } fn visit_mut_script(&mut self, script: &mut Script) { self.bindings = Lrc::new(collect_decls(&*script)); script.visit_mut_children_with(self); } } #[cfg(test)] mod tests { use swc_ecma_transforms_testing::{test, Tester}; use swc_ecma_utils::{DropSpan, StmtOrModuleItem}; use super::*; fn mk_map( tester: &mut Tester<'_>, values: &[(&str, &str)], is_env: bool, ) -> FxHashMap<Atom, Expr> { let mut m = FxHashMap::default(); for (k, v) in values { let v = if is_env { format!("'{}'", v) } else { (*v).into() }; let v = tester .apply_transform( visit_mut_pass(DropSpan), "global.js", ::swc_ecma_parser::Syntax::default(), None, &v, ) .unwrap(); let v = match v { Program::Module(mut m) => m.body.pop().and_then(|x| x.into_stmt().ok()), Program::Script(mut s) => s.body.pop(), }; assert!(v.is_some()); let v = match v.unwrap() { Stmt::Expr(ExprStmt { expr, .. }) => *expr, _ => unreachable!(), }; m.insert((*k).into(), v); } m } fn envs(tester: &mut Tester<'_>, values: &[(&str, &str)]) -> Lrc<FxHashMap<Atom, Expr>> { Lrc::new(mk_map(tester, values, true)) } fn globals(tester: &mut Tester<'_>, values: &[(&str, &str)]) -> Lrc<FxHashMap<Atom, Expr>> { Lrc::new(mk_map(tester, values, false)) } test!( ::swc_ecma_parser::Syntax::default(), |tester| inline_globals(envs(tester, &[]), globals(tester, &[]), Default::default(),), issue_215, r#"if (process.env.x === 'development') {}"# ); test!( ::swc_ecma_parser::Syntax::default(), |tester| inline_globals( envs(tester, &[("NODE_ENV", "development")]), globals(tester, &[]), Default::default(), ), node_env, r#"if (process.env.NODE_ENV === 'development') {}"# ); test!( ::swc_ecma_parser::Syntax::default(), |tester| inline_globals( envs(tester, &[]), globals(tester, &[("__DEBUG__", "true")]), Default::default(), ), globals_simple, r#"if (__DEBUG__) {}"# ); test!( ::swc_ecma_parser::Syntax::default(), |tester| inline_globals( envs(tester, &[]), globals(tester, &[("debug", "true")]), Default::default(), ), non_global, r#"if (foo.debug) {}"# ); test!( Default::default(), |tester| inline_globals(envs(tester, &[]), globals(tester, &[]), Default::default(),), issue_417_1, "const test = process.env['x']" ); test!( Default::default(), |tester| inline_globals( envs(tester, &[("x", "FOO")]), globals(tester, &[]), Default::default(), ), issue_417_2, "const test = process.env['x']" ); test!( Default::default(), |tester| inline_globals( envs(tester, &[("x", "BAR")]), globals(tester, &[]), Default::default(), ), issue_2499_1, "process.env.x = 'foo'" ); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University