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_react/tests/jsx/fixture/react/should-not-strip-tags-with-a-single-child-of-nbsp/input.js
JavaScript
<div>&nbsp;</div>;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-not-strip-tags-with-a-single-child-of-nbsp/output.js
JavaScript
/*#__PURE__*/ React.createElement("div", null, " ");
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-properly-handle-comments-between-props/input.js
JavaScript
var x = ( <div /* a multi-line comment */ attr1="foo" > <span // a double-slash comment attr2="bar" /> </div> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-properly-handle-comments-between-props/output.js
JavaScript
var x = /*#__PURE__*/ React.createElement("div", { /* a multi-line comment */ attr1: "foo" }, /*#__PURE__*/ React.createElement("span" // a double-slash comment , { attr2: "bar" }));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-quote-jsx-attributes/input.js
JavaScript
<button data-value="a value">Button</button>;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-quote-jsx-attributes/output.js
JavaScript
/*#__PURE__*/ React.createElement("button", { "data-value": "a value" }, "Button");
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-support-xml-namespaces-if-flag/input.js
JavaScript
<f:image n:attr />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-support-xml-namespaces-if-flag/output.js
JavaScript
/*#__PURE__*/ h("f:image", { "n:attr": true });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-throw-error-namespaces-if-not-flag/input.js
JavaScript
<f:image />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-throw-error-namespaces-if-not-flag/output.mjs
JavaScript
/*#__PURE__*/ h("f:image", null);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-transform-known-hyphenated-tags/input.js
JavaScript
<font-face />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/should-transform-known-hyphenated-tags/output.js
JavaScript
/*#__PURE__*/ React.createElement("font-face", null);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/this-tag-name/input.js
JavaScript
var div = <this.foo>test</this.foo>;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/this-tag-name/output.js
JavaScript
var div = /*#__PURE__*/React.createElement(this.foo, null, "test");
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/weird-symbols/input.js
JavaScript
/** @jsxRuntime classic */ class MobileHomeActivityTaskPriorityIcon extends React.PureComponent { render() { return <Text>&nbsp;{this.props.value}&nbsp;</Text>; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/weird-symbols/output.js
JavaScript
/** @jsxRuntime classic */ class MobileHomeActivityTaskPriorityIcon extends React.PureComponent { render() { return /*#__PURE__*/ React.createElement(Text, null, " ", this.props.value, " "); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/wraps-props-in-react-spread-for-first-spread-attributes/input.js
JavaScript
<Component {...x} y={2} z />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/wraps-props-in-react-spread-for-first-spread-attributes/output.js
JavaScript
/*#__PURE__*/ React.createElement(Component, { ...x, y: 2, z: true });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/wraps-props-in-react-spread-for-last-spread-attributes/input.js
JavaScript
<Component y={2} z {...x} />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/wraps-props-in-react-spread-for-last-spread-attributes/output.js
JavaScript
/*#__PURE__*/ React.createElement(Component, { y: 2, z: true, ...x });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/wraps-props-in-react-spread-for-middle-spread-attributes/input.js
JavaScript
<Component y={2} {...x} z />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/react/wraps-props-in-react-spread-for-middle-spread-attributes/output.js
JavaScript
/*#__PURE__*/ React.createElement(Component, { y: 2, ...x, z: true });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/regression/.issue-12478-automatic/input.js
JavaScript
const foo = 2;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/regression/.issue-12478-automatic/output.js
JavaScript
var _reactJsxRuntime = require("react/jsx-runtime"); const foo = /*#__PURE__*/_reactJsxRuntime.jsx("p", {});
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/regression/.issue-12478-automatic/plugin.js
JavaScript
module.exports = ({ types: t }) => ({ visitor: { NumericLiteral(path) { path.replaceWith( t.jsxElement( t.jsxOpeningElement(t.jsxIdentifier("p"), []), t.jsxClosingElement(t.jsxIdentifier("p")), [] ) ); }, }, });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/regression/.issue-12478-classic/input.js
JavaScript
const foo = 2;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/regression/.issue-12478-classic/output.js
JavaScript
const foo = /*#__PURE__*/React.createElement("p", null);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/regression/.issue-12478-classic/plugin.js
JavaScript
module.exports = ({ types: t }) => ({ visitor: { NumericLiteral(path) { path.replaceWith( t.jsxElement( t.jsxOpeningElement(t.jsxIdentifier("p"), []), t.jsxClosingElement(t.jsxIdentifier("p")), [] ) ); }, }, });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/regression/pragma-frag-set-default-classic-runtime/input.js
JavaScript
/* @jsxFrag React.Fragment */ /* @jsx h */ <>Test</>;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/regression/pragma-frag-set-default-classic-runtime/output.js
JavaScript
/* @jsxFrag React.Fragment */ /* @jsx h */ /*#__PURE__*/ h(React.Fragment, null, "Test");
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/removed-options/.invalid-use-builtins-false/input.js
JavaScript
var div = <Component {...props} foo="bar" />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/removed-options/.invalid-use-builtins-true/input.js
JavaScript
var div = <Component {...props} foo="bar" />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/removed-options/.invalid-use-spread-false/input.js
JavaScript
var div = <Component {...props} foo="bar" />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/removed-options/.invalid-use-spread-true/input.js
JavaScript
var div = <Component {...props} foo="bar" />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/.defaults-to-automatic/input.js
JavaScript
var x = ( <div> <span /> </div> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/.defaults-to-automatic/output.js
JavaScript
import { jsx as _jsx } from "react/jsx-runtime"; var x = _jsx("div", { children: _jsx("span", { }) });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/.invalid-runtime/input.js
JavaScript
var x = ( <div> <span /> </div> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/.runtime-automatic/input.js
JavaScript
var x = ( <div> <span /> </div> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/.runtime-automatic/output.js
JavaScript
var _reactJsxRuntime = require("react/jsx-runtime"); var x = /*#__PURE__*/_reactJsxRuntime.jsx("div", { children: /*#__PURE__*/_reactJsxRuntime.jsx("span", {}) });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/classic/input.js
JavaScript
var x = ( <div> <span /> </div> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/classic/output.js
JavaScript
var x = /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", null));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/defaults-to-classis-babel-7/input.js
JavaScript
var x = ( <div> <span /> </div> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/defaults-to-classis-babel-7/output.js
JavaScript
var x = /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", null));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/pragma-runtime-classsic/input.js
JavaScript
/** @jsxRuntime classic */ var x = ( <div> <span /> </div> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/runtime/pragma-runtime-classsic/output.js
JavaScript
/** @jsxRuntime classic */ var x = /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", null));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/spread-transform/.transform-to-babel-extend/input.js
JavaScript
var div = <Component {...props} foo="bar" />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/spread-transform/.transform-to-babel-extend/output.js
JavaScript
var div = React.createElement(Component, _extends({ }, props, { foo: "bar" }));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/spread-transform/.transform-to-object-assign/input.js
JavaScript
var div = <Component {...props} foo="bar" />;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/spread-transform/.transform-to-object-assign/output.js
JavaScript
var _reactJsxRuntime = require("react/jsx-runtime"); var div = /*#__PURE__*/_reactJsxRuntime.jsx(Component, Object.assign({}, props, { foo: "bar" }));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/vercel/1/input.js
JavaScript
export default ( <A className={b} header="C" subheader="D E" /> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/vercel/1/output.mjs
JavaScript
export default /*#__PURE__*/ React.createElement(A, { className: b, header: "C", subheader: "D E" });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/vercel/2/input.js
JavaScript
export default () => { return <Input pattern=".*\S+.*" />; };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/jsx/fixture/vercel/2/output.mjs
JavaScript
export default (()=>{ return /*#__PURE__*/ React.createElement(Input, { pattern: ".*\\S+.*" }); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/integration/jsx-dev-transform/input.js
JavaScript
const App = ( <div> <div /> <> <div key={1}>hoge</div> </> </div> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/integration/jsx-dev-transform/output.js
JavaScript
const { jsxDEV: _jsxDEV, Fragment: _Fragment } = require("react/jsx-dev-runtime"); const App = /*#__PURE__*/ _jsxDEV("div", { children: [ /*#__PURE__*/ _jsxDEV("div", {}, void 0, false, { fileName: "input.js", lineNumber: 3, columnNumber: 9 }, this), /*#__PURE__*/ _jsxDEV(_Fragment, { children: /*#__PURE__*/ _jsxDEV("div", { children: "hoge" }, 1, false, { fileName: "input.js", lineNumber: 5, columnNumber: 13 }, this) }, void 0, false) ] }, void 0, true, { fileName: "input.js", lineNumber: 2, columnNumber: 5 }, this);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/integration/jsx-transform/input.js
JavaScript
const App = ( <div> <div /> <> <div key={1}>hoge</div> </> </div> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/integration/jsx-transform/output.js
JavaScript
const { jsx: _jsx, jsxs: _jsxs, Fragment: _Fragment } = require("react/jsx-runtime"); const App = /*#__PURE__*/ _jsxs("div", { children: [ /*#__PURE__*/ _jsx("div", {}), /*#__PURE__*/ _jsx(_Fragment, { children: /*#__PURE__*/ _jsx("div", { children: "hoge" }, 1) }) ] });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/integration/jsxdev-args-with-fragment/input.js
JavaScript
var x = ( <> <div>hoge</div> <div>fuga</div> </> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/integration/jsxdev-args-with-fragment/output.js
JavaScript
const { jsxDEV: _jsxDEV, Fragment: _Fragment } = require("react/jsx-dev-runtime"); var x = /*#__PURE__*/ _jsxDEV(_Fragment, { children: [ /*#__PURE__*/ _jsxDEV("div", { children: "hoge" }, void 0, false, { fileName: "input.js", lineNumber: 3, columnNumber: 9 }, this), /*#__PURE__*/ _jsxDEV("div", { children: "fuga" }, void 0, false, { fileName: "input.js", lineNumber: 4, columnNumber: 9 }, this) ] }, void 0, true);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/integration/jsxdev-fragment/input.js
JavaScript
const App = ( <> <div>hoge</div> <div>fuga</div> </> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/integration/jsxdev-fragment/output.js
JavaScript
const { jsxDEV: _jsxDEV, Fragment: _Fragment } = require("react/jsx-dev-runtime"); const App = /*#__PURE__*/ _jsxDEV(_Fragment, { children: [ /*#__PURE__*/ _jsxDEV("div", { children: "hoge" }, void 0, false, { fileName: "input.js", lineNumber: 3, columnNumber: 9 }, this), /*#__PURE__*/ _jsxDEV("div", { children: "fuga" }, void 0, false, { fileName: "input.js", lineNumber: 4, columnNumber: 9 }, this) ] }, void 0, true);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/integration/with-pragma/input.js
JavaScript
/**@jsxRuntime automatic */ const App = ( <div> <div /> <> <div>hoge</div> </> </div> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/integration/with-pragma/output.js
JavaScript
/**@jsxRuntime automatic */ const { jsxDEV: _jsxDEV, Fragment: _Fragment } = require("react/jsx-dev-runtime"); const App = /*#__PURE__*/ _jsxDEV("div", { children: [ /*#__PURE__*/ _jsxDEV("div", {}, void 0, false, { fileName: "input.js", lineNumber: 4, columnNumber: 9 }, this), /*#__PURE__*/ _jsxDEV(_Fragment, { children: /*#__PURE__*/ _jsxDEV("div", { children: "hoge" }, void 0, false, { fileName: "input.js", lineNumber: 6, columnNumber: 13 }, this) }, void 0, false) ] }, void 0, true, { fileName: "input.js", lineNumber: 3, columnNumber: 5 }, this);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/jsx/fixture/autoImport/after-polyfills-script/input.js
JavaScript
// https://github.com/babel/babel/issues/12522 require("react-app-polyfill/ie11"); require("react-app-polyfill/stable"); const ReactDOM = require("react-dom"); ReactDOM.render(<p>Hello, World!</p>, document.getElementById("root"));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/jsx/fixture/autoImport/after-polyfills-script/output.js
JavaScript
// https://github.com/babel/babel/issues/12522 const { jsx: _jsx } = require("react/jsx-runtime"); require("react-app-polyfill/ie11"); require("react-app-polyfill/stable"); const ReactDOM = require("react-dom"); ReactDOM.render(/*#__PURE__*/ _jsx("p", { children: "Hello, World!" }), document.getElementById("root"));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/jsx/fixture/autoImport/auto-import-runtime-source-type-script/input.js
JavaScript
var x = ( <> <div> <div key="1" /> <div key="2" meow="wolf" /> <div key="3" /> <div {...props} key="4" /> </div> </> );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/jsx/fixture/autoImport/auto-import-runtime-source-type-script/output.js
JavaScript
const { jsx: _jsx, jsxs: _jsxs, Fragment: _Fragment } = require("react/jsx-runtime"); const { createElement: _createElement } = require("react"); var x = /*#__PURE__*/ _jsx(_Fragment, { children: /*#__PURE__*/ _jsxs("div", { children: [ /*#__PURE__*/ _jsx("div", {}, "1"), /*#__PURE__*/ _jsx("div", { meow: "wolf" }, "2"), /*#__PURE__*/ _jsx("div", {}, "3"), /*#__PURE__*/ _createElement("div", { ...props, key: "4" }) ] }) });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/jsx/fixture/autoImport/complicated-scope-script/input.js
JavaScript
const Bar = () => { const Foo = () => { const Component = ({ thing, ..._react }) => { if (!thing) { var _react2 = "something useless"; var b = _react3(); var c = _react5(); var jsx = 1; var _jsx = 2; return <div />; } return <span />; }; }; };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_react/tests/script/jsx/fixture/autoImport/complicated-scope-script/output.js
JavaScript
const { jsx: _jsx } = require("react/jsx-runtime"); const Bar = ()=>{ const Foo = ()=>{ const Component = ({ thing, ..._react })=>{ if (!thing) { var _react2 = "something useless"; var b = _react3(); var c = _react5(); var jsx = 1; var _jsx1 = 2; return /*#__PURE__*/ _jsx("div", {}); } return /*#__PURE__*/ _jsx("span", {}); }; }; };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_testing/src/babel_like.rs
Rust
use std::{fs::read_to_string, path::Path}; use ansi_term::Color; use serde::Deserialize; use serde_json::Value; use swc_common::{comments::SingleThreadedComments, sync::Lrc, Mark, SourceMap}; use swc_ecma_ast::{EsVersion, Pass, Program}; use swc_ecma_codegen::Emitter; use swc_ecma_parser::{parse_file_as_program, Syntax}; use swc_ecma_transforms_base::{ assumptions::Assumptions, fixer::fixer, helpers::{inject_helpers, Helpers, HELPERS}, hygiene::hygiene, resolver, }; use testing::NormalizedOutput; use crate::{exec_with_node_test_runner, parse_options, stdout_of}; pub type PassFactory<'a> = Box<dyn 'a + FnMut(&PassContext, &str, Option<Value>) -> Option<Box<dyn 'static + Pass>>>; /// These tests use `options.json`. /// /// /// Note: You should **not** use [resolver] by yourself. pub struct BabelLikeFixtureTest<'a> { input: &'a Path, /// Default to [`Syntax::default`] syntax: Syntax, factories: Vec<Box<dyn 'a + FnOnce() -> PassFactory<'a>>>, source_map: bool, allow_error: bool, } impl<'a> BabelLikeFixtureTest<'a> { pub fn new(input: &'a Path) -> Self { Self { input, syntax: Default::default(), factories: Default::default(), source_map: false, allow_error: false, } } pub fn syntax(mut self, syntax: Syntax) -> Self { self.syntax = syntax; self } pub fn source_map(mut self) -> Self { self.source_map = true; self } pub fn allow_error(mut self) -> Self { self.source_map = true; self } /// This takes a closure which returns a [PassFactory]. This is because you /// may need to create [Mark], which requires [swc_common::GLOBALS] to be /// configured. pub fn add_factory(mut self, factory: impl 'a + FnOnce() -> PassFactory<'a>) -> Self { self.factories.push(Box::new(factory)); self } fn run(self, output_path: Option<&Path>, compare_stdout: bool) { let err = testing::run_test(false, |cm, handler| { let mut factories = self.factories.into_iter().map(|f| f()).collect::<Vec<_>>(); let options = parse_options::<BabelOptions>(self.input.parent().unwrap()); let comments = SingleThreadedComments::default(); let mut builder = PassContext { cm: cm.clone(), assumptions: options.assumptions, unresolved_mark: Mark::new(), top_level_mark: Mark::new(), comments: comments.clone(), }; let mut pass: Box<dyn Pass> = Box::new(resolver( builder.unresolved_mark, builder.top_level_mark, self.syntax.typescript(), )); // Build pass using babel options // for plugin in options.plugins { let (name, options) = match plugin { BabelPluginEntry::NameOnly(name) => (name, None), BabelPluginEntry::WithConfig(name, options) => (name, Some(options)), }; let mut done = false; for factory in &mut factories { if let Some(built) = factory(&builder, &name, options.clone()) { pass = Box::new((pass, built)); done = true; break; } } if !done { panic!("Unknown plugin: {}", name); } } pass = Box::new((pass, hygiene(), fixer(Some(&comments)))); // Run pass let src = read_to_string(self.input).expect("failed to read file"); let src = if output_path.is_none() && !compare_stdout { format!( "it('should work', async function () {{ {src} }})", ) } else { src }; let fm = cm.new_source_file( swc_common::FileName::Real(self.input.to_path_buf()).into(), src, ); let mut errors = Vec::new(); let input_program = parse_file_as_program( &fm, self.syntax, EsVersion::latest(), Some(&comments), &mut errors, ); let errored = !errors.is_empty(); for e in errors { e.into_diagnostic(handler).emit(); } let input_program = match input_program { Ok(v) => v, Err(err) => { err.into_diagnostic(handler).emit(); return Err(()); } }; if errored { return Err(()); } let helpers = Helpers::new(output_path.is_some()); let (code_without_helper, output_program) = HELPERS.set(&helpers, || { let mut p = input_program.apply(pass); let code_without_helper = builder.print(&p); if output_path.is_none() { p.mutate(inject_helpers(builder.unresolved_mark)) } (code_without_helper, p) }); // Print output let code = builder.print(&output_program); println!( "\t>>>>> {} <<<<<\n{}\n\t>>>>> {} <<<<<\n{}", Color::Green.paint("Orig"), fm.src, Color::Green.paint("Code"), code_without_helper ); if let Some(output_path) = output_path { // Fixture test if !self.allow_error && handler.has_errors() { return Err(()); } NormalizedOutput::from(code) .compare_to_file(output_path) .unwrap(); } else if compare_stdout { // Execution test, but compare stdout let actual_stdout: String = stdout_of(&code).expect("failed to execute transfomred code"); let expected_stdout = stdout_of(&fm.src).expect("failed to execute transfomred code"); testing::assert_eq!(actual_stdout, expected_stdout); } else { // Execution test exec_with_node_test_runner(&format!("// {}\n{code}", self.input.display())) .expect("failed to execute transfomred code"); } Ok(()) }); if self.allow_error { match err { Ok(_) => {} Err(err) => { err.compare_to_file(self.input.with_extension("stderr")) .unwrap(); } } } } /// Execute using node.js and mocha pub fn exec_with_test_runner(self) { self.run(None, false) } /// Execute using node.js pub fn compare_stdout(self) { self.run(None, true) } /// Run a fixture test pub fn fixture(self, output: &Path) { self.run(Some(output), false) } } #[derive(Debug, Deserialize)] struct BabelOptions { #[serde(default)] assumptions: Assumptions, #[serde(default)] plugins: Vec<BabelPluginEntry>, } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase", untagged)] enum BabelPluginEntry { NameOnly(String), WithConfig(String, Value), } #[derive(Clone)] pub struct PassContext { pub cm: Lrc<SourceMap>, pub assumptions: Assumptions, pub unresolved_mark: Mark, pub top_level_mark: Mark, /// [SingleThreadedComments] is cheap to clone. pub comments: SingleThreadedComments, } impl PassContext { fn print(&mut self, program: &Program) -> String { let mut buf = Vec::new(); { let mut emitter = Emitter { cfg: Default::default(), cm: self.cm.clone(), wr: Box::new(swc_ecma_codegen::text_writer::JsWriter::new( self.cm.clone(), "\n", &mut buf, None, )), comments: Some(&self.comments), }; emitter.emit_program(program).unwrap(); } let s = String::from_utf8_lossy(&buf); s.to_string() } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_testing/src/lib.rs
Rust
#![deny(clippy::all)] #![deny(clippy::all)] #![deny(unused)] #![allow(clippy::result_unit_err)] use std::{ env, fs::{self, create_dir_all, read_to_string, OpenOptions}, io::Write, mem::{take, transmute}, panic, path::{Path, PathBuf}, process::Command, rc::Rc, }; use ansi_term::Color; use anyhow::Error; use base64::prelude::{Engine, BASE64_STANDARD}; use serde::de::DeserializeOwned; use sha2::{Digest, Sha256}; use swc_common::{ comments::{Comments, SingleThreadedComments}, errors::{Handler, HANDLER}, source_map::SourceMapGenConfig, sync::Lrc, FileName, Mark, SourceMap, DUMMY_SP, }; use swc_ecma_ast::*; use swc_ecma_codegen::{to_code_default, Emitter}; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax}; use swc_ecma_testing::{exec_node_js, JsExecOptions}; use swc_ecma_transforms_base::{ fixer, helpers::{inject_helpers, HELPERS}, hygiene, }; use swc_ecma_utils::{quote_ident, quote_str, ExprFactory}; use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, Fold, FoldWith, VisitMut}; use tempfile::tempdir_in; use testing::{ assert_eq, find_executable, NormalizedOutput, CARGO_TARGET_DIR, CARGO_WORKSPACE_ROOT, }; pub mod babel_like; pub struct Tester<'a> { pub cm: Lrc<SourceMap>, pub handler: &'a Handler, /// This will be changed to [SingleThreadedComments] once `cargo-mono` /// supports correct bumping logic, or we need to make a breaking change in /// a upstream crate of this crate. /// /// Although type is `Rc<SingleThreadedComments>`, it's fine to clone /// `SingleThreadedComments` without `Rc`. pub comments: Rc<SingleThreadedComments>, } impl Tester<'_> { pub fn run<F, Ret>(op: F) -> Ret where F: FnOnce(&mut Tester<'_>) -> Result<Ret, ()>, { let comments = Rc::new(SingleThreadedComments::default()); let out = ::testing::run_test(false, |cm, handler| { HANDLER.set(handler, || { HELPERS.set(&Default::default(), || { let cmts = comments.clone(); let c = Box::new(unsafe { // Safety: This is unsafe but it's used only for testing. transmute::<&dyn Comments, &'static dyn Comments>(&*cmts) }) as Box<dyn Comments>; swc_common::comments::COMMENTS.set(&c, || { op(&mut Tester { cm, handler, comments, }) }) }) }) }); match out { Ok(ret) => ret, Err(stderr) => panic!("Stderr:\n{}", stderr), } } pub(crate) fn run_captured<F, T>(op: F) -> (Option<T>, NormalizedOutput) where F: FnOnce(&mut Tester<'_>) -> Result<T, ()>, { let mut res = None; let output = ::testing::Tester::new().print_errors(|cm, handler| -> Result<(), _> { HANDLER.set(&handler, || { HELPERS.set(&Default::default(), || { let result = op(&mut Tester { cm, handler: &handler, comments: Default::default(), }); res = result.ok(); // We need stderr Err(()) }) }) }); let output = output .err() .unwrap_or_else(|| NormalizedOutput::from(String::from(""))); (res, output) } pub fn with_parser<F, T>( &mut self, file_name: &str, syntax: Syntax, src: &str, op: F, ) -> Result<T, ()> where F: FnOnce(&mut Parser<Lexer>) -> Result<T, swc_ecma_parser::error::Error>, { let fm = self .cm .new_source_file(FileName::Real(file_name.into()).into(), src.into()); let mut p = Parser::new(syntax, StringInput::from(&*fm), Some(&self.comments)); let res = op(&mut p).map_err(|e| e.into_diagnostic(self.handler).emit()); for e in p.take_errors() { e.into_diagnostic(self.handler).emit() } res } pub fn parse_module(&mut self, file_name: &str, src: &str) -> Result<Module, ()> { self.with_parser(file_name, Syntax::default(), src, |p| p.parse_module()) } pub fn parse_stmts(&mut self, file_name: &str, src: &str) -> Result<Vec<Stmt>, ()> { let stmts = self.with_parser(file_name, Syntax::default(), src, |p| { p.parse_script().map(|script| script.body) })?; Ok(stmts) } pub fn parse_stmt(&mut self, file_name: &str, src: &str) -> Result<Stmt, ()> { let mut stmts = self.parse_stmts(file_name, src)?; assert!(stmts.len() == 1); Ok(stmts.pop().unwrap()) } pub fn apply_transform<T: Pass>( &mut self, tr: T, name: &str, syntax: Syntax, is_module: Option<bool>, src: &str, ) -> Result<Program, ()> { let program = self.with_parser( name, syntax, src, |parser: &mut Parser<Lexer>| match is_module { Some(true) => parser.parse_module().map(Program::Module), Some(false) => parser.parse_script().map(Program::Script), None => parser.parse_program(), }, )?; Ok(program.apply(tr)) } pub fn print(&mut self, program: &Program, comments: &Rc<SingleThreadedComments>) -> String { to_code_default(self.cm.clone(), Some(comments), program) } } struct RegeneratorHandler; impl VisitMut for RegeneratorHandler { noop_visit_mut_type!(); fn visit_mut_module_item(&mut self, item: &mut ModuleItem) { if let ModuleItem::ModuleDecl(ModuleDecl::Import(import)) = item { if &*import.src.value != "regenerator-runtime" { return; } let s = import.specifiers.iter().find_map(|v| match v { ImportSpecifier::Default(rt) => Some(rt.local.clone()), _ => None, }); let s = match s { Some(v) => v, _ => return, }; let init = CallExpr { span: DUMMY_SP, callee: quote_ident!("require").as_callee(), args: vec![quote_str!("regenerator-runtime").as_arg()], ..Default::default() } .into(); let decl = VarDeclarator { span: DUMMY_SP, name: s.into(), init: Some(init), definite: Default::default(), }; *item = VarDecl { span: import.span, kind: VarDeclKind::Var, declare: false, decls: vec![decl], ..Default::default() } .into() } } } #[track_caller] pub fn test_transform<F, P>( syntax: Syntax, is_module: Option<bool>, tr: F, input: &str, expected: &str, ) where F: FnOnce(&mut Tester) -> P, P: Pass, { Tester::run(|tester| { let expected = tester.apply_transform( swc_ecma_utils::DropSpan, "output.js", syntax, is_module, expected, )?; let expected_comments = take(&mut tester.comments); println!("----- Actual -----"); let tr = (tr(tester), visit_mut_pass(RegeneratorHandler)); let actual = tester.apply_transform(tr, "input.js", syntax, is_module, input)?; match ::std::env::var("PRINT_HYGIENE") { Ok(ref s) if s == "1" => { let hygiene_src = tester.print( &actual.clone().fold_with(&mut HygieneVisualizer), &tester.comments.clone(), ); println!("----- Hygiene -----\n{}", hygiene_src); } _ => {} } let actual = actual .apply(::swc_ecma_utils::DropSpan) .apply(hygiene::hygiene()) .apply(fixer::fixer(Some(&tester.comments))); println!("{:?}", tester.comments); println!("{:?}", expected_comments); { let (actual_leading, actual_trailing) = tester.comments.borrow_all(); let (expected_leading, expected_trailing) = expected_comments.borrow_all(); if actual == expected && *actual_leading == *expected_leading && *actual_trailing == *expected_trailing { return Ok(()); } } let (actual_src, expected_src) = ( tester.print(&actual, &tester.comments.clone()), tester.print(&expected, &expected_comments), ); if actual_src == expected_src { return Ok(()); } println!(">>>>> {} <<<<<\n{}", Color::Green.paint("Orig"), input); println!(">>>>> {} <<<<<\n{}", Color::Green.paint("Code"), actual_src); if actual_src != expected_src { panic!( r#"assertion failed: `(left == right)` {}"#, ::testing::diff(&actual_src, &expected_src), ); } Err(()) }); } /// NOT A PUBLIC API. DO NOT USE. #[doc(hidden)] #[track_caller] pub fn test_inline_input_output<F, P>( syntax: Syntax, is_module: Option<bool>, tr: F, input: &str, output: &str, ) where F: FnOnce(&mut Tester) -> P, P: Pass, { let _logger = testing::init(); let expected = output; let expected_src = Tester::run(|tester| { let expected_program = tester.apply_transform(noop_pass(), "expected.js", syntax, is_module, expected)?; let expected_src = tester.print(&expected_program, &Default::default()); println!( "----- {} -----\n{}", Color::Green.paint("Expected"), expected_src ); Ok(expected_src) }); let actual_src = Tester::run_captured(|tester| { println!("----- {} -----\n{}", Color::Green.paint("Input"), input); let tr = tr(tester); println!("----- {} -----", Color::Green.paint("Actual")); let actual = tester.apply_transform(tr, "input.js", syntax, is_module, input)?; match ::std::env::var("PRINT_HYGIENE") { Ok(ref s) if s == "1" => { let hygiene_src = tester.print( &actual.clone().fold_with(&mut HygieneVisualizer), &Default::default(), ); println!( "----- {} -----\n{}", Color::Green.paint("Hygiene"), hygiene_src ); } _ => {} } let actual = actual .apply(crate::hygiene::hygiene()) .apply(crate::fixer::fixer(Some(&tester.comments))); let actual_src = tester.print(&actual, &Default::default()); Ok(actual_src) }) .0 .unwrap(); assert_eq!( expected_src, actual_src, "Exepcted:\n{expected_src}\nActual:\n{actual_src}\n", ); } /// NOT A PUBLIC API. DO NOT USE. #[doc(hidden)] #[track_caller] pub fn test_inlined_transform<F, P>( test_name: &str, syntax: Syntax, module: Option<bool>, tr: F, input: &str, ) where F: FnOnce(&mut Tester) -> P, P: Pass, { let loc = panic::Location::caller(); let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR")); let test_file_path = CARGO_WORKSPACE_ROOT.join(loc.file()); let snapshot_dir = manifest_dir.join("tests").join("__swc_snapshots__").join( test_file_path .strip_prefix(&manifest_dir) .expect("test_inlined_transform does not support paths outside of the crate root"), ); test_fixture_inner( syntax, Box::new(move |tester| Box::new(tr(tester))), input, &snapshot_dir.join(format!("{test_name}.js")), FixtureTestConfig { module, ..Default::default() }, ) } /// NOT A PUBLIC API. DO NOT USE. #[doc(hidden)] #[macro_export] macro_rules! test_location { () => {{ $crate::TestLocation {} }}; } #[macro_export] macro_rules! test_inline { (ignore, $syntax:expr, $tr:expr, $test_name:ident, $input:expr, $output:expr) => { #[test] #[ignore] fn $test_name() { $crate::test_inline_input_output($syntax, None, $tr, $input, $output) } }; ($syntax:expr, $tr:expr, $test_name:ident, $input:expr, $output:expr) => { #[test] fn $test_name() { $crate::test_inline_input_output($syntax, None, $tr, $input, $output) } }; } test_inline!( ignore, Syntax::default(), |_| noop_pass(), test_inline_ignored, "class Foo {}", "class Foo {}" ); test_inline!( Syntax::default(), |_| noop_pass(), test_inline_pass, "class Foo {}", "class Foo {}" ); #[test] #[should_panic] fn test_inline_should_fail() { test_inline_input_output( Default::default(), None, |_| noop_pass(), "class Foo {}", "", ); } #[macro_export] macro_rules! test { (ignore, $syntax:expr, $tr:expr, $test_name:ident, $input:expr) => { #[test] #[ignore] fn $test_name() { $crate::test_inlined_transform(stringify!($test_name), $syntax, None, $tr, $input) } }; ($syntax:expr, $tr:expr, $test_name:ident, $input:expr) => { #[test] fn $test_name() { $crate::test_inlined_transform(stringify!($test_name), $syntax, None, $tr, $input) } }; (module, $syntax:expr, $tr:expr, $test_name:ident, $input:expr) => { #[test] fn $test_name() { $crate::test_inlined_transform(stringify!($test_name), $syntax, Some(true), $tr, $input) } }; (script, $syntax:expr, $tr:expr, $test_name:ident, $input:expr) => { #[test] fn $test_name() { $crate::test_inlined_script_transform( stringify!($test_name), $syntax, Some(false), $tr, $input, ) } }; ($syntax:expr, $tr:expr, $test_name:ident, $input:expr, ok_if_code_eq) => { #[test] fn $test_name() { $crate::test_inlined_transform(stringify!($test_name), $syntax, None, $tr, $input) } }; } /// Execute `node` for `input` and ensure that it prints same output after /// transformation. pub fn compare_stdout<F, P>(syntax: Syntax, tr: F, input: &str) where F: FnOnce(&mut Tester<'_>) -> P, P: Pass, { Tester::run(|tester| { let tr = (tr(tester), visit_mut_pass(RegeneratorHandler)); let program = tester.apply_transform(tr, "input.js", syntax, Some(true), input)?; match ::std::env::var("PRINT_HYGIENE") { Ok(ref s) if s == "1" => { let hygiene_src = tester.print( &program.clone().fold_with(&mut HygieneVisualizer), &tester.comments.clone(), ); println!("----- Hygiene -----\n{}", hygiene_src); } _ => {} } let mut program = program .apply(hygiene::hygiene()) .apply(fixer::fixer(Some(&tester.comments))); let src_without_helpers = tester.print(&program, &tester.comments.clone()); program = program.apply(inject_helpers(Mark::fresh(Mark::root()))); let transformed_src = tester.print(&program, &tester.comments.clone()); println!( "\t>>>>> Orig <<<<<\n{}\n\t>>>>> Code <<<<<\n{}", input, src_without_helpers ); let expected = stdout_of(input).unwrap(); println!("\t>>>>> Expected stdout <<<<<\n{}", expected); let actual = stdout_of(&transformed_src).unwrap(); assert_eq!(expected, actual); Ok(()) }) } /// Execute `jest` after transpiling `input` using `tr`. pub fn exec_tr<F, P>(_test_name: &str, syntax: Syntax, tr: F, input: &str) where F: FnOnce(&mut Tester<'_>) -> P, P: Pass, { Tester::run(|tester| { let tr = (tr(tester), visit_mut_pass(RegeneratorHandler)); let program = tester.apply_transform( tr, "input.js", syntax, Some(true), &format!( "it('should work', async function () {{ {} }})", input ), )?; match ::std::env::var("PRINT_HYGIENE") { Ok(ref s) if s == "1" => { let hygiene_src = tester.print( &program.clone().fold_with(&mut HygieneVisualizer), &tester.comments.clone(), ); println!("----- Hygiene -----\n{}", hygiene_src); } _ => {} } let mut program = program .apply(hygiene::hygiene()) .apply(fixer::fixer(Some(&tester.comments))); let src_without_helpers = tester.print(&program, &tester.comments.clone()); program = program.apply(inject_helpers(Mark::fresh(Mark::root()))); let src = tester.print(&program, &tester.comments.clone()); println!( "\t>>>>> {} <<<<<\n{}\n\t>>>>> {} <<<<<\n{}", Color::Green.paint("Orig"), input, Color::Green.paint("Code"), src_without_helpers ); exec_with_node_test_runner(&src).map(|_| {}) }) } fn calc_hash(s: &str) -> String { let mut hasher = Sha256::new(); hasher.update(s.as_bytes()); let sum = hasher.finalize(); hex::encode(sum) } fn exec_with_node_test_runner(src: &str) -> Result<(), ()> { let root = CARGO_TARGET_DIR.join("swc-es-exec-testing"); create_dir_all(&root).expect("failed to create parent directory for temp directory"); let hash = calc_hash(src); let success_cache = root.join(format!("{}.success", hash)); if env::var("SWC_CACHE_TEST").unwrap_or_default() == "1" { println!("Trying cache as `SWC_CACHE_TEST` is `1`"); if success_cache.exists() { println!("Cache: success"); return Ok(()); } } let tmp_dir = tempdir_in(&root).expect("failed to create a temp directory"); create_dir_all(&tmp_dir).unwrap(); let path = tmp_dir.path().join(format!("{}.test.js", hash)); let mut tmp = OpenOptions::new() .create(true) .truncate(true) .write(true) .open(&path) .expect("failed to create a temp file"); write!(tmp, "{}", src).expect("failed to write to temp file"); tmp.flush().unwrap(); let test_runner_path = find_executable("mocha").expect("failed to find `mocha` from path"); let mut base_cmd = if cfg!(target_os = "windows") { let mut c = Command::new("cmd"); c.arg("/C").arg(&test_runner_path); c } else { Command::new(&test_runner_path) }; let output = base_cmd .arg(format!("{}", path.display())) .arg("--color") .current_dir(root) .output() .expect("failed to run mocha"); println!(">>>>> {} <<<<<", Color::Red.paint("Stdout")); println!("{}", String::from_utf8_lossy(&output.stdout)); println!(">>>>> {} <<<<<", Color::Red.paint("Stderr")); println!("{}", String::from_utf8_lossy(&output.stderr)); if output.status.success() { fs::write(&success_cache, "").unwrap(); return Ok(()); } let dir_name = path.display().to_string(); ::std::mem::forget(tmp_dir); panic!("Execution failed: {dir_name}") } fn stdout_of(code: &str) -> Result<String, Error> { exec_node_js( code, JsExecOptions { cache: true, module: false, ..Default::default() }, ) } /// Test transformation. #[macro_export] macro_rules! test_exec { (@check) => { if ::std::env::var("EXEC").unwrap_or(String::from("")) == "0" { return; } }; (ignore, $syntax:expr, $tr:expr, $test_name:ident, $input:expr) => { #[test] #[ignore] fn $test_name() { $crate::exec_tr(stringify!($test_name), $syntax, $tr, $input) } }; ($syntax:expr, $tr:expr, $test_name:ident, $input:expr) => { #[test] fn $test_name() { test_exec!(@check); $crate::exec_tr(stringify!($test_name), $syntax, $tr, $input) } }; } /// Test transformation by invoking it using `node`. The code must print /// something to stdout. #[macro_export] macro_rules! compare_stdout { ($syntax:expr, $tr:expr, $test_name:ident, $input:expr) => { #[test] fn $test_name() { $crate::compare_stdout($syntax, $tr, $input) } }; } /// Converts `foo#1` to `foo__1` so it can be verified by the test. pub struct HygieneTester; impl Fold for HygieneTester { fn fold_ident(&mut self, ident: Ident) -> Ident { Ident { sym: format!("{}__{}", ident.sym, ident.ctxt.as_u32()).into(), ..ident } } fn fold_member_prop(&mut self, p: MemberProp) -> MemberProp { match p { MemberProp::Computed(..) => p.fold_children_with(self), _ => p, } } fn fold_prop_name(&mut self, p: PropName) -> PropName { match p { PropName::Computed(..) => p.fold_children_with(self), _ => p, } } } pub struct HygieneVisualizer; impl Fold for HygieneVisualizer { fn fold_ident(&mut self, ident: Ident) -> Ident { Ident { sym: format!("{}{:?}", ident.sym, ident.ctxt).into(), ..ident } } } /// Just like babel, walk up the directory tree and find a file named /// `options.json`. pub fn parse_options<T>(dir: &Path) -> T where T: DeserializeOwned, { type Map = serde_json::Map<String, serde_json::Value>; let mut value = Map::default(); fn check(dir: &Path) -> Option<Map> { let file = dir.join("options.json"); if let Ok(v) = read_to_string(&file) { eprintln!("Using options.json at {}", file.display()); eprintln!("----- {} -----\n{}", Color::Green.paint("Options"), v); return Some(serde_json::from_str(&v).unwrap_or_else(|err| { panic!("failed to deserialize options.json: {}\n{}", err, v) })); } None } let mut c = Some(dir); while let Some(dir) = c { if let Some(new) = check(dir) { for (k, v) in new { if !value.contains_key(&k) { value.insert(k, v); } } } c = dir.parent(); } serde_json::from_value(serde_json::Value::Object(value.clone())) .unwrap_or_else(|err| panic!("failed to deserialize options.json: {}\n{:?}", err, value)) } /// Config for [test_fixture]. See [test_fixture] for documentation. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct FixtureTestConfig { /// If true, source map will be printed to the `.map` file. /// /// Defaults to false. pub sourcemap: bool, /// If true, diagnostics written to [HANDLER] will be printed as a fixture, /// with `.stderr` extension. /// /// If false, test will fail if diagnostics are emitted. /// /// Defaults to false. pub allow_error: bool, /// Determines what type of [Program] the source code is parsed as. /// /// - `Some(true)`: parsed as a [Program::Module] /// - `Some(false)`: parsed as a [Program::Script] /// - `None`: parsed as a [Program] (underlying type is auto-detected) pub module: Option<bool>, } /// You can do `UPDATE=1 cargo test` to update fixtures. pub fn test_fixture<P>( syntax: Syntax, tr: &dyn Fn(&mut Tester) -> P, input: &Path, output: &Path, config: FixtureTestConfig, ) where P: Pass, { let input = fs::read_to_string(input).unwrap(); test_fixture_inner( syntax, Box::new(|tester| Box::new(tr(tester))), &input, output, config, ); } fn test_fixture_inner<'a>( syntax: Syntax, tr: Box<dyn 'a + FnOnce(&mut Tester) -> Box<dyn 'a + Pass>>, input: &str, output: &Path, config: FixtureTestConfig, ) { let _logger = testing::init(); let expected = read_to_string(output); let _is_really_expected = expected.is_ok(); let expected = expected.unwrap_or_default(); let expected_src = Tester::run(|tester| { let expected_program = tester.apply_transform(noop_pass(), "expected.js", syntax, config.module, &expected)?; let expected_src = tester.print(&expected_program, &tester.comments.clone()); println!( "----- {} -----\n{}", Color::Green.paint("Expected"), expected_src ); Ok(expected_src) }); let mut src_map = if config.sourcemap { Some(Vec::new()) } else { None }; let mut sourcemap = None; let (actual_src, stderr) = Tester::run_captured(|tester| { eprintln!("----- {} -----\n{}", Color::Green.paint("Input"), input); let tr = tr(tester); eprintln!("----- {} -----", Color::Green.paint("Actual")); let actual = tester.apply_transform(tr, "input.js", syntax, config.module, input)?; eprintln!("----- {} -----", Color::Green.paint("Comments")); eprintln!("{:?}", tester.comments); match ::std::env::var("PRINT_HYGIENE") { Ok(ref s) if s == "1" => { let hygiene_src = tester.print( &actual.clone().fold_with(&mut HygieneVisualizer), &tester.comments.clone(), ); println!( "----- {} -----\n{}", Color::Green.paint("Hygiene"), hygiene_src ); } _ => {} } let actual = actual .apply(crate::hygiene::hygiene()) .apply(crate::fixer::fixer(Some(&tester.comments))); let actual_src = { let module = &actual; let comments: &Rc<SingleThreadedComments> = &tester.comments.clone(); let mut buf = vec![]; { let mut emitter = Emitter { cfg: Default::default(), cm: tester.cm.clone(), wr: Box::new(swc_ecma_codegen::text_writer::JsWriter::new( tester.cm.clone(), "\n", &mut buf, src_map.as_mut(), )), comments: Some(comments), }; // println!("Emitting: {:?}", module); emitter.emit_program(module).unwrap(); } if let Some(src_map) = &mut src_map { sourcemap = Some(tester.cm.build_source_map_with_config( src_map, None, SourceMapConfigImpl, )); } String::from_utf8(buf).expect("codegen generated non-utf8 output") }; Ok(actual_src) }); if config.allow_error { stderr .compare_to_file(output.with_extension("stderr")) .unwrap(); } else if !stderr.is_empty() { panic!("stderr: {}", stderr); } if let Some(actual_src) = actual_src { eprintln!("{}", actual_src); if let Some(sourcemap) = &sourcemap { eprintln!("----- ----- ----- ----- -----"); eprintln!("SourceMap: {}", visualizer_url(&actual_src, sourcemap)); } if actual_src != expected_src { NormalizedOutput::from(actual_src) .compare_to_file(output) .unwrap(); } } if let Some(sourcemap) = sourcemap { let map = { let mut buf = Vec::new(); sourcemap.to_writer(&mut buf).unwrap(); String::from_utf8(buf).unwrap() }; NormalizedOutput::from(map) .compare_to_file(output.with_extension("map")) .unwrap(); } } /// Creates a url for https://evanw.github.io/source-map-visualization/ fn visualizer_url(code: &str, map: &sourcemap::SourceMap) -> String { let map = { let mut buf = Vec::new(); map.to_writer(&mut buf).unwrap(); String::from_utf8(buf).unwrap() }; let code_len = format!("{}\0", code.len()); let map_len = format!("{}\0", map.len()); let hash = BASE64_STANDARD.encode(format!("{}{}{}{}", code_len, code, map_len, map)); format!("https://evanw.github.io/source-map-visualization/#{}", hash) } struct SourceMapConfigImpl; impl SourceMapGenConfig for SourceMapConfigImpl { fn file_name_to_source(&self, f: &swc_common::FileName) -> String { f.to_string() } fn inline_sources_content(&self, _: &swc_common::FileName) -> bool { true } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_testing/tests/visited.rs
Rust
use swc_ecma_ast::*; use swc_ecma_parser::{EsSyntax, Syntax}; use swc_ecma_transforms_testing::test_transform; use swc_ecma_visit::{fold_pass, Fold}; struct Panicking; impl Fold for Panicking { fn fold_jsx_opening_element(&mut self, node: JSXOpeningElement) -> JSXOpeningElement { let JSXOpeningElement { name, .. } = &node; println!("HMM"); if let JSXElementName::Ident(Ident { sym, .. }) = name { panic!("visited: {}", sym) } node } } #[test] #[should_panic = "visited"] fn ensure_visited() { test_transform( Syntax::Es(EsSyntax { jsx: true, ..Default::default() }), None, |_| fold_pass(Panicking), " import React from 'react'; const comp = () => <amp-something className='something' />; ", " import React from 'react'; const comp = () => <amp-something className='something' />; ", ); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/benches/assets/AjaxObservable.ts
TypeScript
/** @prettier */ import { Observable } from '../../Observable'; import { Subscriber } from '../../Subscriber'; import { TeardownLogic, PartialObserver } from '../../types'; export interface AjaxRequest { url?: string; body?: any; user?: string; async?: boolean; method?: string; headers?: object; timeout?: number; password?: string; hasContent?: boolean; crossDomain?: boolean; withCredentials?: boolean; createXHR?: () => XMLHttpRequest; progressSubscriber?: PartialObserver<ProgressEvent>; responseType?: string; } function isFormData(body: any): body is FormData { return typeof FormData !== 'undefined' && body instanceof FormData; } /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export class AjaxObservable<T> extends Observable<T> { private request: AjaxRequest; constructor(urlOrRequest: string | AjaxRequest) { super(); const request: AjaxRequest = { async: true, createXHR: () => new XMLHttpRequest(), crossDomain: true, withCredentials: false, headers: {}, method: 'GET', responseType: 'json', timeout: 0, }; if (typeof urlOrRequest === 'string') { request.url = urlOrRequest; } else { for (const prop in urlOrRequest) { if (urlOrRequest.hasOwnProperty(prop)) { (request as any)[prop] = (urlOrRequest as any)[prop]; } } } this.request = request; } /** @deprecated This is an internal implementation detail, do not use. */ _subscribe(subscriber: Subscriber<T>): TeardownLogic { return new AjaxSubscriber(subscriber, this.request); } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ export class AjaxSubscriber<T> extends Subscriber<Event> { // @ts-ignore: Property has no initializer and is not definitely assigned private xhr: XMLHttpRequest; private done: boolean = false; constructor(destination: Subscriber<T>, public request: AjaxRequest) { super(destination); const headers = (request.headers = request.headers || {}); // force CORS if requested if (!request.crossDomain && !this.getHeader(headers, 'X-Requested-With')) { (headers as any)['X-Requested-With'] = 'XMLHttpRequest'; } // ensure content type is set let contentTypeHeader = this.getHeader(headers, 'Content-Type'); if (!contentTypeHeader && typeof request.body !== 'undefined' && !isFormData(request.body)) { (headers as any)['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; } // properly serialize body request.body = this.serializeBody(request.body, this.getHeader(request.headers, 'Content-Type')); this.send(); } next(e: Event): void { this.done = true; const destination = this.destination as Subscriber<any>; let result: AjaxResponse; try { result = new AjaxResponse(e, this.xhr, this.request); } catch (err) { return destination.error(err); } destination.next(result); } private send(): void { const { request, request: { user, method, url, async, password, headers, body }, } = this; try { const xhr = (this.xhr = request.createXHR!()); // set up the events before open XHR // https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest // You need to add the event listeners before calling open() on the request. // Otherwise the progress events will not fire. this.setupEvents(xhr, request); // open XHR if (user) { xhr.open(method!, url!, async!, user, password); } else { xhr.open(method!, url!, async!); } // timeout, responseType and withCredentials can be set once the XHR is open if (async) { xhr.timeout = request.timeout!; xhr.responseType = request.responseType as any; } if ('withCredentials' in xhr) { xhr.withCredentials = !!request.withCredentials; } // set headers this.setHeaders(xhr, headers!); // finally send the request if (body) { xhr.send(body); } else { xhr.send(); } } catch (err) { this.error(err); } } private serializeBody(body: any, contentType?: string) { if (!body || typeof body === 'string') { return body; } else if (isFormData(body)) { return body; } if (contentType) { const splitIndex = contentType.indexOf(';'); if (splitIndex !== -1) { contentType = contentType.substring(0, splitIndex); } } switch (contentType) { case 'application/x-www-form-urlencoded': return Object.keys(body) .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(body[key])}`) .join('&'); case 'application/json': return JSON.stringify(body); default: return body; } } private setHeaders(xhr: XMLHttpRequest, headers: Object) { for (let key in headers) { if (headers.hasOwnProperty(key)) { xhr.setRequestHeader(key, (headers as any)[key]); } } } private getHeader(headers: {}, headerName: string): any { for (let key in headers) { if (key.toLowerCase() === headerName.toLowerCase()) { return (headers as any)[key]; } } return undefined; } private setupEvents(xhr: XMLHttpRequest, request: AjaxRequest) { const progressSubscriber = request.progressSubscriber; xhr.ontimeout = (e: ProgressEvent) => { progressSubscriber?.error?.(e); let error; try { error = new AjaxTimeoutError(xhr, request); // TODO: Make better. } catch (err) { error = err; } this.error(error); }; if (progressSubscriber) { xhr.upload.onprogress = (e: ProgressEvent) => { progressSubscriber.next?.(e); }; } xhr.onerror = (e: ProgressEvent) => { progressSubscriber?.error?.(e); this.error(new AjaxError('ajax error', xhr, request)); }; xhr.onload = (e: ProgressEvent) => { // 4xx and 5xx should error (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) if (xhr.status < 400) { progressSubscriber?.complete?.(); this.next(e); this.complete(); } else { progressSubscriber?.error?.(e); let error; try { error = new AjaxError('ajax error ' + xhr.status, xhr, request); } catch (err) { error = err; } this.error(error); } }; } unsubscribe() { const { done, xhr } = this; if (!done && xhr && xhr.readyState !== 4 && typeof xhr.abort === 'function') { xhr.abort(); } super.unsubscribe(); } } /** * A normalized AJAX response. * * @see {@link ajax} * * @class AjaxResponse */ export class AjaxResponse { /** @type {number} The HTTP status code */ status: number; /** @type {string|ArrayBuffer|Document|object|any} The response data */ response: any; /** @type {string} The raw responseText */ // @ts-ignore: Property has no initializer and is not definitely assigned responseText: string; /** @type {string} The responseType (e.g. 'json', 'arraybuffer', or 'xml') */ responseType: string; constructor(public originalEvent: Event, public xhr: XMLHttpRequest, public request: AjaxRequest) { this.status = xhr.status; this.responseType = xhr.responseType || request.responseType!; this.response = getXHRResponse(xhr); } } export type AjaxErrorNames = 'AjaxError' | 'AjaxTimeoutError'; /** * A normalized AJAX error. * * @see {@link ajax} * * @class AjaxError */ export interface AjaxError extends Error { /** * The XHR instance associated with the error */ xhr: XMLHttpRequest; /** * The AjaxRequest associated with the error */ request: AjaxRequest; /** *The HTTP status code */ status: number; /** *The responseType (e.g. 'json', 'arraybuffer', or 'xml') */ responseType: XMLHttpRequestResponseType; /** * The response data */ response: any; } export interface AjaxErrorCtor { /** * Internal use only. Do not manually create instances of this type. * @internal */ new(message: string, xhr: XMLHttpRequest, request: AjaxRequest): AjaxError; } const AjaxErrorImpl = (() => { function AjaxErrorImpl(this: any, message: string, xhr: XMLHttpRequest, request: AjaxRequest): AjaxError { Error.call(this); this.message = message; this.name = 'AjaxError'; this.xhr = xhr; this.request = request; this.status = xhr.status; this.responseType = xhr.responseType; let response: any; try { response = getXHRResponse(xhr); } catch (err) { response = xhr.responseText; } this.response = response; return this; } AjaxErrorImpl.prototype = Object.create(Error.prototype); return AjaxErrorImpl; })(); /** * Thrown when an error occurs during an AJAX request. * This is only exported because it is useful for checking to see if an error * is an `instanceof AjaxError`. DO NOT create new instances of `AjaxError` with * the constructor. * * @class AjaxError * @see ajax */ export const AjaxError: AjaxErrorCtor = AjaxErrorImpl as any; function getXHRResponse(xhr: XMLHttpRequest) { switch (xhr.responseType) { case 'json': { if ('response' in xhr) { return xhr.response; } else { // IE const ieXHR: any = xhr; return JSON.parse(ieXHR.responseText); } } case 'document': return xhr.responseXML; case 'text': default: { if ('response' in xhr) { return xhr.response; } else { // IE const ieXHR: any = xhr; return ieXHR.responseText; } } } } export interface AjaxTimeoutError extends AjaxError { } export interface AjaxTimeoutErrorCtor { /** * Internal use only. Do not manually create instances of this type. * @internal */ new(xhr: XMLHttpRequest, request: AjaxRequest): AjaxTimeoutError; } const AjaxTimeoutErrorImpl = (() => { function AjaxTimeoutErrorImpl(this: any, xhr: XMLHttpRequest, request: AjaxRequest) { AjaxError.call(this, 'ajax timeout', xhr, request); this.name = 'AjaxTimeoutError'; return this; } AjaxTimeoutErrorImpl.prototype = Object.create(AjaxError.prototype); return AjaxTimeoutErrorImpl; })(); /** * Thrown when an AJAX request timeout. Not to be confused with {@link TimeoutError}. * * This is exported only because it is useful for checking to see if errors are an * `instanceof AjaxTimeoutError`. DO NOT use the constructor to create an instance of * this type. * * @class AjaxTimeoutError * @see ajax */ export const AjaxTimeoutError: AjaxTimeoutErrorCtor = AjaxTimeoutErrorImpl as any;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/benches/compat.rs
Rust
use codspeed_criterion_compat::{black_box, criterion_group, criterion_main, Bencher, Criterion}; use swc_common::{comments::SingleThreadedComments, sync::Lrc, FileName, Mark, SourceMap}; use swc_ecma_ast::{Module, Pass, Program}; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax}; use swc_ecma_transforms_base::{helpers, resolver}; use swc_ecma_transforms_typescript::strip; use swc_ecma_visit::{fold_pass, Fold}; static SOURCE: &str = include_str!("assets/AjaxObservable.ts"); fn module(cm: Lrc<SourceMap>) -> Program { let fm = cm.new_source_file(FileName::Anon.into(), SOURCE.into()); let lexer = Lexer::new( Syntax::Typescript(Default::default()), Default::default(), StringInput::from(&*fm), None, ); let mut parser = Parser::new_from(lexer); parser .parse_module() .map(Program::Module) .map_err(|_| ()) .unwrap() } fn run<V>(b: &mut Bencher, tr: impl Fn(Mark) -> V) where V: Pass, { let _ = ::testing::run_test(false, |cm, _| { let module = module(cm); let unresolved_mark = Mark::fresh(Mark::root()); let top_level_mark = Mark::fresh(Mark::root()); let module = module .apply(resolver(unresolved_mark, top_level_mark, true)) .apply(strip(unresolved_mark, top_level_mark)); b.iter(|| { let module = module.clone(); helpers::HELPERS.set(&Default::default(), || { let tr = tr(unresolved_mark); black_box(module.apply(tr)); }); }); Ok(()) }); } fn baseline_group(c: &mut Criterion) { c.bench_function("es/transform/baseline/base", base); c.bench_function( "es/transform/baseline/common_reserved_word", common_reserved_word, ); c.bench_function("es/transform/baseline/common_typescript", common_typescript); } fn base(b: &mut Bencher) { struct Noop; impl Fold for Noop { #[inline] fn fold_module(&mut self, m: Module) -> Module { m } } run(b, |_| fold_pass(Noop)); } fn common_typescript(b: &mut Bencher) { let _ = ::testing::run_test(false, |cm, _| { let module = module(cm); let unresolved_mark = Mark::fresh(Mark::root()); let top_level_mark = Mark::fresh(Mark::root()); let module = module .apply(resolver(unresolved_mark, top_level_mark, true)) .apply(strip(unresolved_mark, top_level_mark)); b.iter(|| { let module = module.clone(); helpers::HELPERS.set(&Default::default(), || { black_box(module.apply(strip(unresolved_mark, top_level_mark))); }); }); Ok(()) }); } fn common_reserved_word(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::reserved_words::reserved_words() }); } fn version_group(c: &mut Criterion) { c.bench_function("es/target/es3", es3); c.bench_function("es/target/es2015", es2015); c.bench_function("es/target/es2016", es2016); c.bench_function("es/target/es2017", es2017); c.bench_function("es/target/es2018", es2018); c.bench_function("es/target/es2020", es2020); } fn single_tr_group(c: &mut Criterion) { c.bench_function("es2020_nullish_coalescing", es2020_nullish_coalescing); c.bench_function("es2020_optional_chaining", es2020_optional_chaining); c.bench_function("es2022_class_properties", es2022_class_properties); c.bench_function("es2018_object_rest_spread", es2018_object_rest_spread); c.bench_function( "es2019_optional_catch_binding", es2019_optional_catch_binding, ); c.bench_function("es2017_async_to_generator", es2017_async_to_generator); c.bench_function("es2016_exponentiation", es2016_exponentiation); c.bench_function("es2015_arrow", es2015_arrow); c.bench_function("es2015_block_scoped_fn", es2015_block_scoped_fn); c.bench_function("es2015_block_scoping", es2015_block_scoping); c.bench_function("es2015_classes", es2015_classes); c.bench_function("es2015_computed_props", es2015_computed_props); c.bench_function("es2015_destructuring", es2015_destructuring); c.bench_function("es2015_duplicate_keys", es2015_duplicate_keys); c.bench_function("es2015_parameters", es2015_parameters); c.bench_function("es2015_fn_name", es2015_fn_name); c.bench_function("es2015_for_of", es2015_for_of); c.bench_function("es2015_instanceof", es2015_instanceof); c.bench_function("es2015_shorthand_property", es2015_shorthand_property); c.bench_function("es2015_spread", es2015_spread); c.bench_function("es2015_sticky_regex", es2015_sticky_regex); c.bench_function("es2015_typeof_symbol", es2015_typeof_symbol); } fn es2020(b: &mut Bencher) { run(b, |unresolved_mark| { swc_ecma_transforms_compat::es2022(Default::default(), unresolved_mark) }); } fn es2020_nullish_coalescing(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2020::nullish_coalescing( swc_ecma_transforms_compat::es2020::nullish_coalescing::Config { no_document_all: false, }, ) }); } fn es2020_optional_chaining(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2020::optional_chaining(Default::default(), Mark::new()) }); } fn es2022_class_properties(b: &mut Bencher) { run(b, |unresolved_mark| { swc_ecma_transforms_compat::es2022::class_properties(Default::default(), unresolved_mark) }); } fn es2018(b: &mut Bencher) { run( b, |_| swc_ecma_transforms_compat::es2018(Default::default()), ); } fn es2018_object_rest_spread(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2018::object_rest_spread(Default::default()) }); } fn es2019_optional_catch_binding(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2019::optional_catch_binding() }); } fn es2017(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2017(Default::default(), Mark::new()) }); } fn es2017_async_to_generator(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2017::async_to_generator(Default::default(), Mark::new()) }); } fn es2016(b: &mut Bencher) { run(b, |_| swc_ecma_transforms_compat::es2016()); } fn es2016_exponentiation(b: &mut Bencher) { run(b, |_| swc_ecma_transforms_compat::es2016::exponentiation()); } fn es2015(b: &mut Bencher) { run(b, |unresolved_mark| { swc_ecma_transforms_compat::es2015( unresolved_mark, Some(SingleThreadedComments::default()), Default::default(), ) }); } fn es2015_arrow(b: &mut Bencher) { run( b, |_| swc_ecma_transforms_compat::es2015::arrow(Mark::new()), ); } fn es2015_block_scoped_fn(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2015::block_scoped_functions() }); } fn es2015_block_scoping(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2015::block_scoping(Mark::new()) }); } fn es2015_classes(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2015::classes(Default::default()) }); } fn es2015_computed_props(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2015::computed_properties(Default::default()) }); } fn es2015_destructuring(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2015::destructuring(Default::default()) }); } fn es2015_duplicate_keys(b: &mut Bencher) { run(b, |_| swc_ecma_transforms_compat::es2015::duplicate_keys()); } fn es2015_parameters(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2015::parameters(Default::default(), Mark::new()) }); } fn es2015_fn_name(b: &mut Bencher) { run(b, |_| swc_ecma_transforms_compat::es2015::function_name()); } fn es2015_for_of(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2015::for_of(Default::default()) }); } fn es2015_instanceof(b: &mut Bencher) { run(b, |_| swc_ecma_transforms_compat::es2015::instance_of()); } fn es2015_shorthand_property(b: &mut Bencher) { run(b, |_| swc_ecma_transforms_compat::es2015::shorthand()); } fn es2015_spread(b: &mut Bencher) { run(b, |_| { swc_ecma_transforms_compat::es2015::spread(Default::default()) }); } fn es2015_sticky_regex(b: &mut Bencher) { run(b, |_| swc_ecma_transforms_compat::es2015::sticky_regex()); } fn es2015_typeof_symbol(b: &mut Bencher) { run(b, |_| swc_ecma_transforms_compat::es2015::typeof_symbol()); } fn es3(b: &mut Bencher) { run(b, |_| swc_ecma_transforms_compat::es3(Default::default())); } fn full_es2016(b: &mut Bencher) { run(b, |unresolved_mark| { ( swc_ecma_transforms_compat::es2022(Default::default(), unresolved_mark), swc_ecma_transforms_compat::es2019(), swc_ecma_transforms_compat::es2018(Default::default()), swc_ecma_transforms_compat::es2017(Default::default(), Mark::new()), swc_ecma_transforms_compat::es2016(), ) }); } fn full_es2017(b: &mut Bencher) { run(b, |unresolved_mark| { ( swc_ecma_transforms_compat::es2022(Default::default(), unresolved_mark), swc_ecma_transforms_compat::es2019(), swc_ecma_transforms_compat::es2018(Default::default()), swc_ecma_transforms_compat::es2017(Default::default(), Mark::new()), ) }); } fn full_es2018(b: &mut Bencher) { run(b, |unresolved_mark| { ( swc_ecma_transforms_compat::es2022(Default::default(), unresolved_mark), swc_ecma_transforms_compat::es2019(), swc_ecma_transforms_compat::es2018(Default::default()), ) }); } fn full_group(c: &mut Criterion) { c.bench_function("es/full-target/es2016", full_es2016); c.bench_function("es/full-target/es2017", full_es2017); c.bench_function("es/full-target/es2018", full_es2018); } criterion_group!( benches, full_group, single_tr_group, baseline_group, version_group ); criterion_main!(benches);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/examples/ts_to_js.rs
Rust
//! Usage: cargo run --example ts_to_js path/to/ts //! //! This program will emit output to stdout. use std::{env, path::Path}; use swc_common::{ comments::SingleThreadedComments, errors::{ColorConfig, Handler}, sync::Lrc, Globals, Mark, SourceMap, GLOBALS, }; use swc_ecma_codegen::to_code_default; use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax, TsSyntax}; use swc_ecma_transforms_base::{fixer::fixer, hygiene::hygiene, resolver}; use swc_ecma_transforms_typescript::strip; fn main() { let cm: Lrc<SourceMap> = Default::default(); let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(cm.clone())); // Real usage // let fm = cm // .load_file(Path::new("test.js")) // .expect("failed to load test.js"); let input = env::args() .nth(1) .expect("please provide the path of input typescript file"); let fm = cm .load_file(Path::new(&input)) .expect("failed to load input typescript file"); let comments = SingleThreadedComments::default(); let lexer = Lexer::new( Syntax::Typescript(TsSyntax { tsx: input.ends_with(".tsx"), ..Default::default() }), Default::default(), StringInput::from(&*fm), Some(&comments), ); let mut parser = Parser::new_from(lexer); for e in parser.take_errors() { e.into_diagnostic(&handler).emit(); } let module = parser .parse_program() .map_err(|e| e.into_diagnostic(&handler).emit()) .expect("failed to parse module."); let globals = Globals::default(); GLOBALS.set(&globals, || { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); // Optionally transforms decorators here before the resolver pass // as it might produce runtime declarations. // Conduct identifier scope analysis let module = module.apply(resolver(unresolved_mark, top_level_mark, true)); // Remove typescript types let module = module.apply(strip(unresolved_mark, top_level_mark)); // Fix up any identifiers with the same name, but different contexts let module = module.apply(hygiene()); // Ensure that we have enough parenthesis. let program = module.apply(fixer(Some(&comments))); println!("{}", to_code_default(cm, Some(&comments), &program)); }) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/src/config.rs
Rust
use serde::{Deserialize, Serialize}; use swc_common::sync::Lrc; #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Config { /// https://www.typescriptlang.org/tsconfig#verbatimModuleSyntax #[serde(default)] pub verbatim_module_syntax: bool, /// Native class properties support #[serde(default)] pub native_class_properties: bool, /// https://www.typescriptlang.org/tsconfig/#importsNotUsedAsValues #[serde(default)] pub import_not_used_as_values: ImportsNotUsedAsValues, /// Don't create `export {}`. /// By default, strip creates `export {}` for modules to preserve module /// context. /// /// https://github.com/swc-project/swc/issues/1698 #[serde(default)] pub no_empty_export: bool, #[serde(default)] pub import_export_assign_config: TsImportExportAssignConfig, /// Disables an optimization that inlines TS enum member values /// within the same module that assumes the enum member values /// are never modified. /// /// Defaults to false. #[serde(default)] pub ts_enum_is_mutable: bool, } #[derive(Debug, Default, Serialize, Deserialize)] pub struct TsxConfig { /// Note: this pass handle jsx directives in comments #[serde(default)] pub pragma: Option<Lrc<String>>, /// Note: this pass handle jsx directives in comments #[serde(default)] pub pragma_frag: Option<Lrc<String>>, } #[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum TsImportExportAssignConfig { /// - Rewrite `import foo = require("foo")` to `var foo = require("foo")` /// - Rewrite `export =` to `module.exports = ` /// /// Note: This option is deprecated as all CJS/AMD/UMD can handle it /// themselves. #[default] Classic, /// preserve for CJS/AMD/UMD Preserve, /// Rewrite `import foo = require("foo")` to /// ```javascript /// import { createRequire as _createRequire } from "module"; /// const __require = _createRequire(import.meta.url); /// const foo = __require("foo"); /// ``` /// /// Report error for `export =` NodeNext, /// Both `import =` and `export =` are disabled. /// An error will be reported if an import/export assignment is found. EsNext, } #[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[non_exhaustive] pub enum ImportsNotUsedAsValues { #[serde(rename = "remove")] #[default] Remove, #[serde(rename = "preserve")] Preserve, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/src/lib.rs
Rust
#![deny(clippy::all)] #![allow(clippy::vec_box)] #![allow(clippy::mutable_key_type)] pub use self::{strip_type::*, typescript::*}; mod config; mod macros; mod strip_import_export; mod strip_type; mod transform; mod ts_enum; pub mod typescript; mod utils;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/src/macros.rs
Rust
#[macro_export] macro_rules! type_to_none { ($name:ident, $T:ty) => { fn $name(&mut self, node: &mut Option<$T>) { *node = None; } }; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/src/strip_import_export.rs
Rust
use rustc_hash::{FxHashMap, FxHashSet}; use swc_ecma_ast::*; use swc_ecma_utils::stack_size::maybe_grow_default; use swc_ecma_visit::{noop_visit_type, Visit, VisitMut, VisitMutWith, VisitWith}; use crate::{strip_type::IsConcrete, ImportsNotUsedAsValues}; #[derive(Debug, Default)] pub(crate) struct UsageCollect { id_usage: FxHashSet<Id>, import_chain: FxHashMap<Id, Id>, } impl From<FxHashSet<Id>> for UsageCollect { fn from(id_usage: FxHashSet<Id>) -> Self { Self { id_usage, import_chain: Default::default(), } } } impl Visit for UsageCollect { noop_visit_type!(); fn visit_ident(&mut self, n: &Ident) { self.id_usage.insert(n.to_id()); } fn visit_expr(&mut self, n: &Expr) { maybe_grow_default(|| n.visit_children_with(self)) } fn visit_binding_ident(&mut self, _: &BindingIdent) { // skip } fn visit_fn_decl(&mut self, n: &FnDecl) { // skip function ident n.function.visit_with(self); } fn visit_fn_expr(&mut self, n: &FnExpr) { // skip function ident n.function.visit_with(self); } fn visit_class_decl(&mut self, n: &ClassDecl) { // skip class ident n.class.visit_with(self); } fn visit_class_expr(&mut self, n: &ClassExpr) { // skip class ident n.class.visit_with(self); } fn visit_import_decl(&mut self, _: &ImportDecl) { // skip } fn visit_ts_import_equals_decl(&mut self, n: &TsImportEqualsDecl) { if n.is_type_only { return; } // skip id visit let TsModuleRef::TsEntityName(ts_entity_name) = &n.module_ref else { return; }; let id = get_module_ident(ts_entity_name); if n.is_export { id.visit_with(self); n.id.visit_with(self); return; } self.import_chain.insert(n.id.to_id(), id.to_id()); } fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) { if n.is_type_only { return; } n.orig.visit_with(self); } fn visit_named_export(&mut self, n: &NamedExport) { if n.type_only || n.src.is_some() { return; } n.visit_children_with(self); } fn visit_jsx_element_name(&mut self, n: &JSXElementName) { if matches!(n, JSXElementName::Ident(i) if i.sym.starts_with(|c: char| c.is_ascii_lowercase()) ) { return; } n.visit_children_with(self); } } impl UsageCollect { fn has_usage(&self, id: &Id) -> bool { self.id_usage.contains(id) } fn analyze_import_chain(&mut self) { if self.import_chain.is_empty() { return; } let mut new_usage = FxHashSet::default(); for id in &self.id_usage { let mut next = self.import_chain.remove(id); while let Some(id) = next { next = self.import_chain.remove(&id); new_usage.insert(id); } if self.import_chain.is_empty() { break; } } self.import_chain.clear(); self.id_usage.extend(new_usage); } } fn get_module_ident(ts_entity_name: &TsEntityName) -> &Ident { match ts_entity_name { TsEntityName::TsQualifiedName(ts_qualified_name) => { get_module_ident(&ts_qualified_name.left) } TsEntityName::Ident(ident) => ident, } } #[derive(Debug, Default)] pub(crate) struct DeclareCollect { id_type: FxHashSet<Id>, id_value: FxHashSet<Id>, } /// Only scan the top level of the module. /// Any inner declaration is ignored. impl Visit for DeclareCollect { fn visit_binding_ident(&mut self, n: &BindingIdent) { self.id_value.insert(n.to_id()); } fn visit_assign_pat_prop(&mut self, n: &AssignPatProp) { self.id_value.insert(n.key.to_id()); } fn visit_var_declarator(&mut self, n: &VarDeclarator) { n.name.visit_with(self); } fn visit_fn_decl(&mut self, n: &FnDecl) { self.id_value.insert(n.ident.to_id()); } fn visit_class_decl(&mut self, n: &ClassDecl) { self.id_value.insert(n.ident.to_id()); } fn visit_ts_enum_decl(&mut self, n: &TsEnumDecl) { self.id_value.insert(n.id.to_id()); } fn visit_export_default_decl(&mut self, n: &ExportDefaultDecl) { match &n.decl { DefaultDecl::Class(ClassExpr { ident: Some(ident), .. }) => { self.id_value.insert(ident.to_id()); } DefaultDecl::Fn(FnExpr { ident: Some(ident), .. }) => { self.id_value.insert(ident.to_id()); } _ => {} }; } fn visit_ts_import_equals_decl(&mut self, n: &TsImportEqualsDecl) { if n.is_type_only { self.id_type.insert(n.id.to_id()); } else { self.id_value.insert(n.id.to_id()); } } fn visit_ts_module_decl(&mut self, n: &TsModuleDecl) { if n.global { return; } if let TsModuleName::Ident(ident) = &n.id { if n.is_concrete() { self.id_value.insert(ident.to_id()); } else { self.id_type.insert(ident.to_id()); } } } fn visit_ts_interface_decl(&mut self, n: &TsInterfaceDecl) { self.id_type.insert(n.id.to_id()); } fn visit_ts_type_alias_decl(&mut self, n: &TsTypeAliasDecl) { self.id_type.insert(n.id.to_id()); } fn visit_import_decl(&mut self, n: &ImportDecl) { n.specifiers .iter() .for_each(|import_specifier| match import_specifier { ImportSpecifier::Named(named) => { if n.type_only || named.is_type_only { self.id_type.insert(named.local.to_id()); } } ImportSpecifier::Default(default) => { if n.type_only { self.id_type.insert(default.local.to_id()); } } ImportSpecifier::Namespace(namespace) => { if n.type_only { self.id_type.insert(namespace.local.to_id()); } } }); } fn visit_stmt(&mut self, n: &Stmt) { if !n.is_decl() { return; } n.visit_children_with(self); } fn visit_stmts(&mut self, _: &[Stmt]) { // skip } fn visit_block_stmt(&mut self, _: &BlockStmt) { // skip } } impl DeclareCollect { fn has_pure_type(&self, id: &Id) -> bool { self.id_type.contains(id) && !self.id_value.contains(id) } fn has_value(&self, id: &Id) -> bool { self.id_value.contains(id) } } /// https://www.typescriptlang.org/tsconfig#importsNotUsedAsValues /// /// These steps match tsc behavior: /// 1. Remove all import bindings that are not used. /// 2. Remove all export bindings that are defined as types. /// 3. If a local value declaration shares a name with an imported binding, /// treat the imported binding as a type import. /// 4. If a local type declaration shares a name with an imported binding and /// it's used in a value position, treat the imported binding as a value /// import. #[derive(Default)] pub(crate) struct StripImportExport { pub import_not_used_as_values: ImportsNotUsedAsValues, pub usage_info: UsageCollect, pub declare_info: DeclareCollect, } impl VisitMut for StripImportExport { fn visit_mut_module(&mut self, n: &mut Module) { n.visit_with(&mut self.usage_info); n.visit_with(&mut self.declare_info); self.usage_info.analyze_import_chain(); n.visit_mut_children_with(self); } fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) { let mut strip_ts_import_equals = StripTsImportEquals; n.retain_mut(|module_item| match module_item { ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { specifiers, type_only: false, .. })) if !specifiers.is_empty() => { // Note: If import specifiers is originally empty, then we leave it alone. // This is weird but it matches TS. specifiers.retain(|import_specifier| match import_specifier { ImportSpecifier::Named(named) => { if named.is_type_only { return false; } let id = named.local.to_id(); if self.declare_info.has_value(&id) { return false; } self.usage_info.has_usage(&id) } ImportSpecifier::Default(default) => { let id = default.local.to_id(); if self.declare_info.has_value(&id) { return false; } self.usage_info.has_usage(&id) } ImportSpecifier::Namespace(namespace) => { let id = namespace.local.to_id(); if self.declare_info.has_value(&id) { return false; } self.usage_info.has_usage(&id) } }); self.import_not_used_as_values == ImportsNotUsedAsValues::Preserve || !specifiers.is_empty() } ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport { specifiers, src, type_only: false, .. })) => { specifiers.retain(|export_specifier| match export_specifier { ExportSpecifier::Namespace(..) => true, ExportSpecifier::Default(..) => true, ExportSpecifier::Named(ExportNamedSpecifier { orig: ModuleExportName::Ident(ident), is_type_only: false, .. }) if src.is_none() => { let id = ident.to_id(); !self.declare_info.has_pure_type(&id) } ExportSpecifier::Named(ExportNamedSpecifier { is_type_only, .. }) => { !is_type_only } }); !specifiers.is_empty() } ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport { ref type_only, .. })) => !type_only, ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(ExportDefaultExpr { ref expr, .. })) => expr .as_ident() .map(|ident| { let id = ident.to_id(); !self.declare_info.has_pure_type(&id) }) .unwrap_or(true), ModuleItem::ModuleDecl(ModuleDecl::TsImportEquals(ts_import_equals_decl)) => { if ts_import_equals_decl.is_type_only { return false; } if ts_import_equals_decl.is_export { return true; } self.usage_info.has_usage(&ts_import_equals_decl.id.to_id()) } ModuleItem::Stmt(Stmt::Decl(Decl::TsModule(ref ts_module))) if ts_module.body.is_some() => { module_item.visit_mut_with(&mut strip_ts_import_equals); true } _ => true, }); } fn visit_mut_script(&mut self, n: &mut Script) { let mut visitor = StripTsImportEquals; for stmt in n.body.iter_mut() { if let Stmt::Decl(Decl::TsModule(..)) = stmt { stmt.visit_mut_with(&mut visitor); } } } } #[derive(Debug, Default)] struct StripTsImportEquals; impl VisitMut for StripTsImportEquals { fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) { let has_ts_import_equals = n.iter().any(|module_item| { matches!( module_item, ModuleItem::ModuleDecl(ModuleDecl::TsImportEquals(..)) ) }); // TS1235: A namespace declaration is only allowed at the top level of a // namespace or module. let has_ts_module = n.iter().any(|module_item| { matches!( module_item, ModuleItem::Stmt(Stmt::Decl(Decl::TsModule(..))) ) }); if has_ts_import_equals { let mut usage_info = UsageCollect::default(); n.visit_with(&mut usage_info); n.retain(|module_item| match module_item { ModuleItem::ModuleDecl(ModuleDecl::TsImportEquals(ts_import_equals_decl)) => { if ts_import_equals_decl.is_type_only { return false; } if ts_import_equals_decl.is_export { return true; } usage_info.has_usage(&ts_import_equals_decl.id.to_id()) } _ => true, }) } if has_ts_module { n.visit_mut_children_with(self); } } fn visit_mut_module_item(&mut self, n: &mut ModuleItem) { if let ModuleItem::Stmt(Stmt::Decl(Decl::TsModule(ref ts_module))) = n { if ts_module.body.is_some() { n.visit_mut_children_with(self) } } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/src/strip_type.rs
Rust
use swc_common::util::take::Take; use swc_ecma_ast::*; use swc_ecma_utils::stack_size::maybe_grow_default; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; use crate::type_to_none; pub fn strip_type() -> impl VisitMut { StripType::default() } /// This Module will strip all types/generics/interface/declares /// and type import/export #[derive(Default)] pub(crate) struct StripType {} impl VisitMut for StripType { noop_visit_mut_type!(fail); type_to_none!(visit_mut_opt_ts_type, Box<TsType>); type_to_none!(visit_mut_opt_ts_type_ann, Box<TsTypeAnn>); type_to_none!(visit_mut_opt_ts_type_param_decl, Box<TsTypeParamDecl>); type_to_none!( visit_mut_opt_ts_type_param_instantiation, Box<TsTypeParamInstantiation> ); fn visit_mut_array_pat(&mut self, n: &mut ArrayPat) { n.visit_mut_children_with(self); n.optional = false; } fn visit_mut_auto_accessor(&mut self, n: &mut AutoAccessor) { n.type_ann = None; n.accessibility = None; n.definite = false; n.is_override = false; n.is_abstract = false; n.visit_mut_children_with(self); } fn visit_mut_class(&mut self, n: &mut Class) { n.is_abstract = false; n.implements.clear(); n.visit_mut_children_with(self); } fn visit_mut_class_members(&mut self, n: &mut Vec<ClassMember>) { n.retain(|member| match member { ClassMember::TsIndexSignature(..) => false, ClassMember::Constructor(Constructor { body: None, .. }) => false, ClassMember::Method(ClassMethod { is_abstract, function, .. }) | ClassMember::PrivateMethod(PrivateMethod { is_abstract, function, .. }) => !is_abstract && function.body.is_some(), ClassMember::ClassProp( ClassProp { declare: true, .. } | ClassProp { is_abstract: true, .. }, ) | ClassMember::AutoAccessor(AutoAccessor { is_abstract: true, .. }) => false, _ => true, }); n.visit_mut_children_with(self); } fn visit_mut_class_method(&mut self, n: &mut ClassMethod) { n.accessibility = None; n.is_override = false; n.is_abstract = false; n.is_optional = false; n.visit_mut_children_with(self); } fn visit_mut_class_prop(&mut self, prop: &mut ClassProp) { prop.declare = false; prop.readonly = false; prop.is_override = false; prop.is_optional = false; prop.is_abstract = false; prop.definite = false; prop.accessibility = None; prop.visit_mut_children_with(self); } fn visit_mut_private_method(&mut self, n: &mut PrivateMethod) { n.accessibility = None; n.is_abstract = false; n.is_optional = false; n.is_override = false; n.visit_mut_children_with(self); } fn visit_mut_constructor(&mut self, n: &mut Constructor) { n.accessibility = None; n.visit_mut_children_with(self); } fn visit_mut_export_specifiers(&mut self, n: &mut Vec<ExportSpecifier>) { n.retain(|s| match s { ExportSpecifier::Named(ExportNamedSpecifier { is_type_only, .. }) => !is_type_only, _ => true, }) } fn visit_mut_expr(&mut self, n: &mut Expr) { // https://github.com/tc39/proposal-type-annotations#type-assertions // https://github.com/tc39/proposal-type-annotations#non-nullable-assertions while let Expr::TsAs(TsAsExpr { expr, .. }) | Expr::TsNonNull(TsNonNullExpr { expr, .. }) | Expr::TsTypeAssertion(TsTypeAssertion { expr, .. }) | Expr::TsConstAssertion(TsConstAssertion { expr, .. }) | Expr::TsInstantiation(TsInstantiation { expr, .. }) | Expr::TsSatisfies(TsSatisfiesExpr { expr, .. }) = n { *n = *expr.take(); } maybe_grow_default(|| n.visit_mut_children_with(self)); } // https://github.com/tc39/proposal-type-annotations#parameter-optionality fn visit_mut_ident(&mut self, n: &mut Ident) { n.optional = false; } fn visit_mut_import_specifiers(&mut self, n: &mut Vec<ImportSpecifier>) { n.retain(|s| !matches!(s, ImportSpecifier::Named(named) if named.is_type_only)); } fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) { n.retain(should_retain_module_item); n.visit_mut_children_with(self); } fn visit_mut_object_pat(&mut self, pat: &mut ObjectPat) { pat.visit_mut_children_with(self); pat.optional = false; } // https://github.com/tc39/proposal-type-annotations#this-parameters fn visit_mut_params(&mut self, n: &mut Vec<Param>) { if n.first() .filter(|param| { matches!( &param.pat, Pat::Ident(BindingIdent { id: Ident { sym, .. }, .. }) if &**sym == "this" ) }) .is_some() { n.drain(0..1); } n.visit_mut_children_with(self); } fn visit_mut_private_prop(&mut self, prop: &mut PrivateProp) { prop.readonly = false; prop.is_override = false; prop.is_optional = false; prop.definite = false; prop.accessibility = None; prop.visit_mut_children_with(self); } fn visit_mut_setter_prop(&mut self, n: &mut SetterProp) { n.this_param = None; n.visit_mut_children_with(self); } fn visit_mut_simple_assign_target(&mut self, n: &mut SimpleAssignTarget) { // https://github.com/tc39/proposal-type-annotations#type-assertions // https://github.com/tc39/proposal-type-annotations#non-nullable-assertions while let SimpleAssignTarget::TsAs(TsAsExpr { expr, .. }) | SimpleAssignTarget::TsNonNull(TsNonNullExpr { expr, .. }) | SimpleAssignTarget::TsTypeAssertion(TsTypeAssertion { expr, .. }) | SimpleAssignTarget::TsInstantiation(TsInstantiation { expr, .. }) | SimpleAssignTarget::TsSatisfies(TsSatisfiesExpr { expr, .. }) = n { *n = expr.take().try_into().unwrap(); } n.visit_mut_children_with(self); } fn visit_mut_stmts(&mut self, n: &mut Vec<Stmt>) { n.visit_mut_children_with(self); n.retain(|s| !matches!(s, Stmt::Empty(e) if e.span.is_dummy())); } fn visit_mut_stmt(&mut self, n: &mut Stmt) { if should_retain_stmt(n) { n.visit_mut_children_with(self); } else if !n.is_empty() { n.take(); } } fn visit_mut_ts_import_equals_decl(&mut self, _: &mut TsImportEqualsDecl) { // n.id.visit_mut_with(self); } fn visit_mut_ts_param_prop(&mut self, n: &mut TsParamProp) { // skip accessibility n.decorators.visit_mut_with(self); n.param.visit_mut_with(self); } } fn should_retain_module_item(module_item: &ModuleItem) -> bool { match module_item { ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) => { should_retain_decl(&export_decl.decl) } ModuleItem::Stmt(stmt) => should_retain_stmt(stmt), _ => module_item.is_concrete(), } } fn should_retain_stmt(stmt: &Stmt) -> bool { match stmt { Stmt::Decl(decl) => should_retain_decl(decl), _ => stmt.is_concrete(), } } fn should_retain_decl(decl: &Decl) -> bool { if decl.is_declare() { return false; } decl.is_concrete() } pub(crate) trait IsConcrete { fn is_concrete(&self) -> bool; } impl IsConcrete for TsModuleDecl { fn is_concrete(&self) -> bool { self.body .as_ref() .map(|body| body.is_concrete()) .unwrap_or_default() } } impl IsConcrete for TsNamespaceBody { fn is_concrete(&self) -> bool { match self { Self::TsModuleBlock(ts_module_block) => { ts_module_block.body.iter().any(|item| item.is_concrete()) } Self::TsNamespaceDecl(ts_namespace_decl) => ts_namespace_decl.body.is_concrete(), } } } impl IsConcrete for ModuleItem { fn is_concrete(&self) -> bool { match self { Self::ModuleDecl(module_decl) => module_decl.is_concrete(), Self::Stmt(stmt) => stmt.is_concrete(), } } } impl IsConcrete for ModuleDecl { fn is_concrete(&self) -> bool { match self { Self::Import(import_decl) => !import_decl.type_only, Self::ExportDecl(export_decl) => export_decl.decl.is_concrete(), Self::ExportNamed(named_export) => !named_export.type_only, Self::ExportDefaultDecl(export_default_decl) => export_default_decl.decl.is_concrete(), Self::ExportDefaultExpr(..) => true, Self::ExportAll(export_all) => !export_all.type_only, Self::TsImportEquals(ts_import_equals) => !ts_import_equals.is_type_only, Self::TsExportAssignment(..) => true, Self::TsNamespaceExport(..) => false, } } } impl IsConcrete for Decl { fn is_concrete(&self) -> bool { match self { Self::TsInterface(..) | Self::TsTypeAlias(..) => false, Self::Fn(r#fn) => r#fn.function.body.is_some(), Self::Class(..) | Self::Var(..) | Self::Using(..) | Self::TsEnum(..) => true, Self::TsModule(ts_module) => ts_module.is_concrete(), } } } impl IsConcrete for DefaultDecl { fn is_concrete(&self) -> bool { match self { Self::Class(_) => true, Self::Fn(r#fn) => r#fn.function.body.is_some(), Self::TsInterfaceDecl(..) => false, } } } impl IsConcrete for Stmt { fn is_concrete(&self) -> bool { match self { Self::Empty(..) => false, Self::Decl(decl) => decl.is_concrete(), _ => true, } } } trait IsDeclare { fn is_declare(&self) -> bool; } impl IsDeclare for Decl { fn is_declare(&self) -> bool { match self { Decl::Class(class) => class.declare, Decl::Fn(r#fn) => r#fn.declare, Decl::Var(var) => var.declare, Decl::Using(_) => false, // NOTE: TsInterface/TsTypeAlias is not relevant Decl::TsInterface(_) | Decl::TsTypeAlias(_) => true, Decl::TsEnum(ts_enum) => ts_enum.declare, Decl::TsModule(ts_module) => ts_module.declare || ts_module.global, } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/src/transform.rs
Rust
use std::{iter, mem}; use rustc_hash::{FxHashMap, FxHashSet}; use swc_atoms::Atom; use swc_common::{ errors::HANDLER, source_map::PURE_SP, util::take::Take, Mark, Span, Spanned, SyntaxContext, DUMMY_SP, }; use swc_ecma_ast::*; use swc_ecma_utils::{ alias_ident_for, constructor::inject_after_super, find_pat_ids, ident::IdentLike, is_literal, member_expr, private_ident, quote_ident, quote_str, stack_size::maybe_grow_default, ExprFactory, QueryRef, RefRewriter, StmtLikeInjector, }; use swc_ecma_visit::{ noop_visit_mut_type, noop_visit_type, visit_mut_pass, Visit, VisitMut, VisitMutWith, VisitWith, }; use crate::{ config::TsImportExportAssignConfig, ts_enum::{EnumValueComputer, TsEnumRecord, TsEnumRecordKey, TsEnumRecordValue}, utils::{assign_value_to_this_private_prop, assign_value_to_this_prop, Factory}, }; /// ## This Module will transform all TypeScript specific synatx /// /// - ### [namespace]/[modules]/[enums] /// - ### class constructor [parameter properties] /// /// ```TypeScript /// class Foo { /// constructor(public x: number) { /// // No body necessary /// } /// } /// ``` /// - ### [export and import require] /// /// ```TypeScript /// import foo = require("foo"); /// export = foo; /// ``` /// /// [namespace]: https://www.typescriptlang.org/docs/handbook/namespaces.html /// [modules]: https://www.typescriptlang.org/docs/handbook/modules.html /// [enums]: https://www.typescriptlang.org/docs/handbook/enums.html /// [parameter properties]: https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties /// [export and import require]: https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require #[derive(Default)] pub(crate) struct Transform { unresolved_ctxt: SyntaxContext, top_level_ctxt: SyntaxContext, import_export_assign_config: TsImportExportAssignConfig, ts_enum_is_mutable: bool, verbatim_module_syntax: bool, native_class_properties: bool, is_lhs: bool, ref_rewriter: Option<RefRewriter<ExportQuery>>, decl_id_record: FxHashSet<Id>, namespace_id: Option<Id>, exported_binding: FxHashMap<Id, Option<Id>>, enum_record: TsEnumRecord, const_enum: FxHashSet<Id>, var_list: Vec<Id>, export_var_list: Vec<Id>, in_class_prop: Vec<Id>, in_class_prop_init: Vec<Box<Expr>>, } pub fn transform( unresolved_mark: Mark, top_level_mark: Mark, import_export_assign_config: TsImportExportAssignConfig, ts_enum_is_mutable: bool, verbatim_module_syntax: bool, native_class_properties: bool, ) -> impl Pass { visit_mut_pass(Transform { unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark), top_level_ctxt: SyntaxContext::empty().apply_mark(top_level_mark), import_export_assign_config, ts_enum_is_mutable, verbatim_module_syntax, native_class_properties, ..Default::default() }) } impl Visit for Transform { noop_visit_type!(); fn visit_ts_enum_decl(&mut self, node: &TsEnumDecl) { node.visit_children_with(self); let TsEnumDecl { declare, is_const, id, members, .. } = node; if *is_const { self.const_enum.insert(id.to_id()); } debug_assert!(!declare); let mut default_init = 0.0.into(); for m in members { let value = Self::transform_ts_enum_member( m.clone(), &id.to_id(), &default_init, &self.enum_record, self.unresolved_ctxt, ); default_init = value.inc(); let key = TsEnumRecordKey { enum_id: id.to_id(), member_name: m.id.as_ref().clone(), }; self.enum_record.insert(key, value); } } fn visit_ts_namespace_decl(&mut self, n: &TsNamespaceDecl) { let id = n.id.to_id(); let namespace_id = self.namespace_id.replace(id); n.body.visit_with(self); self.namespace_id = namespace_id; } fn visit_ts_module_decl(&mut self, n: &TsModuleDecl) { let id = n.id.to_id(); let namespace_id = self.namespace_id.replace(id); n.body.visit_with(self); self.namespace_id = namespace_id; } fn visit_export_decl(&mut self, node: &ExportDecl) { node.visit_children_with(self); match &node.decl { Decl::Var(var_decl) => { self.exported_binding.extend({ find_pat_ids(&var_decl.decls) .into_iter() .zip(iter::repeat(self.namespace_id.clone())) }); } Decl::TsEnum(ts_enum_decl) => { self.exported_binding .insert(ts_enum_decl.id.to_id(), self.namespace_id.clone()); } Decl::TsModule(ts_module_decl) => { self.exported_binding .insert(ts_module_decl.id.to_id(), self.namespace_id.clone()); } _ => {} } } fn visit_export_named_specifier(&mut self, node: &ExportNamedSpecifier) { if let ModuleExportName::Ident(ident) = &node.orig { self.exported_binding .insert(ident.to_id(), self.namespace_id.clone()); } } fn visit_export_default_expr(&mut self, node: &ExportDefaultExpr) { node.visit_children_with(self); if let Expr::Ident(ident) = &*node.expr { self.exported_binding .insert(ident.to_id(), self.namespace_id.clone()); } } fn visit_ts_import_equals_decl(&mut self, node: &TsImportEqualsDecl) { node.visit_children_with(self); if node.is_export { self.exported_binding .insert(node.id.to_id(), self.namespace_id.clone()); } } fn visit_expr(&mut self, node: &Expr) { maybe_grow_default(|| node.visit_children_with(self)); } } impl VisitMut for Transform { noop_visit_mut_type!(); fn visit_mut_program(&mut self, node: &mut Program) { node.visit_with(self); if !self.exported_binding.is_empty() { self.ref_rewriter = Some(RefRewriter { query: ExportQuery { export_name: self.exported_binding.clone(), }, }); } node.visit_mut_children_with(self); } fn visit_mut_module(&mut self, node: &mut Module) { self.visit_mut_for_ts_import_export(node); node.visit_mut_children_with(self); if !self.export_var_list.is_empty() { let decls = self .export_var_list .take() .into_iter() .map(id_to_var_declarator) .collect(); node.body.push( ExportDecl { decl: VarDecl { decls, ..Default::default() } .into(), span: DUMMY_SP, } .into(), ) } } fn visit_mut_module_items(&mut self, node: &mut Vec<ModuleItem>) { let var_list = self.var_list.take(); node.retain_mut(|item| { let is_empty = item.as_stmt().map(Stmt::is_empty).unwrap_or(false); item.visit_mut_with(self); // Remove those folded into Empty is_empty || !item.as_stmt().map(Stmt::is_empty).unwrap_or(false) }); let var_list = mem::replace(&mut self.var_list, var_list); if !var_list.is_empty() { let decls = var_list.into_iter().map(id_to_var_declarator).collect(); node.push( VarDecl { decls, ..Default::default() } .into(), ) } } fn visit_mut_class_members(&mut self, node: &mut Vec<ClassMember>) { let prop_list = self.in_class_prop.take(); let init_list = self.in_class_prop_init.take(); node.visit_mut_children_with(self); let prop_list = mem::replace(&mut self.in_class_prop, prop_list); let init_list = mem::replace(&mut self.in_class_prop_init, init_list); if !prop_list.is_empty() { if self.native_class_properties { self.reorder_class_prop_decls(node, prop_list, init_list); } else { self.reorder_class_prop_decls_and_inits(node, prop_list, init_list); } } } fn visit_mut_constructor(&mut self, node: &mut Constructor) { node.params .iter_mut() .for_each(|param_or_ts_param_prop| match param_or_ts_param_prop { ParamOrTsParamProp::TsParamProp(ts_param_prop) => { let TsParamProp { span, decorators, param, .. } = ts_param_prop; let (pat, expr, id) = match param { TsParamPropParam::Ident(binding_ident) => { let id = binding_ident.to_id(); let prop_name = PropName::Ident(IdentName::from(&*binding_ident)); let value = Ident::from(&*binding_ident).into(); ( binding_ident.clone().into(), assign_value_to_this_prop(prop_name, value), id, ) } TsParamPropParam::Assign(assign_pat) => { let AssignPat { left, .. } = &assign_pat; let Pat::Ident(binding_ident) = &**left else { unreachable!("destructuring pattern inside TsParameterProperty"); }; let id = binding_ident.id.to_id(); let prop_name = PropName::Ident(binding_ident.id.clone().into()); let value = binding_ident.id.clone().into(); ( assign_pat.clone().into(), assign_value_to_this_prop(prop_name, value), id, ) } }; self.in_class_prop.push(id); self.in_class_prop_init.push(expr); *param_or_ts_param_prop = Param { span: *span, decorators: decorators.take(), pat, } .into(); } ParamOrTsParamProp::Param(..) => {} }); node.params.visit_mut_children_with(self); node.body.visit_mut_children_with(self); } fn visit_mut_stmts(&mut self, node: &mut Vec<Stmt>) { let var_list = self.var_list.take(); node.retain_mut(|stmt| { let is_empty = stmt.is_empty(); stmt.visit_mut_with(self); // Remove those folded into Empty is_empty || !stmt.is_empty() }); let var_list = mem::replace(&mut self.var_list, var_list); if !var_list.is_empty() { let decls = var_list.into_iter().map(id_to_var_declarator).collect(); node.push( VarDecl { decls, ..Default::default() } .into(), ) } } fn visit_mut_ts_namespace_decl(&mut self, node: &mut TsNamespaceDecl) { let id = node.id.to_id(); let namespace_id = self.namespace_id.replace(id); node.body.visit_mut_with(self); self.namespace_id = namespace_id; } fn visit_mut_ts_module_decl(&mut self, node: &mut TsModuleDecl) { let id = node.id.to_id(); let namespace_id = self.namespace_id.replace(id); node.body.visit_mut_with(self); self.namespace_id = namespace_id; } fn visit_mut_stmt(&mut self, node: &mut Stmt) { node.visit_mut_children_with(self); let Stmt::Decl(decl) = node else { return; }; match self.fold_decl(decl.take(), false) { FoldedDecl::Decl(var_decl) => *decl = var_decl, FoldedDecl::Expr(stmt) => *node = stmt, FoldedDecl::Empty => { node.take(); } } } fn visit_mut_module_item(&mut self, node: &mut ModuleItem) { node.visit_mut_children_with(self); if let Some(ExportDecl { decl, .. }) = node .as_mut_module_decl() .and_then(ModuleDecl::as_mut_export_decl) { match self.fold_decl(decl.take(), true) { FoldedDecl::Decl(var_decl) => *decl = var_decl, FoldedDecl::Expr(stmt) => *node = stmt.into(), FoldedDecl::Empty => { node.take(); } } } } fn visit_mut_export_default_decl(&mut self, node: &mut ExportDefaultDecl) { node.visit_mut_children_with(self); if let DefaultDecl::Class(ClassExpr { ident: Some(ref ident), .. }) | DefaultDecl::Fn(FnExpr { ident: Some(ref ident), .. }) = node.decl { self.decl_id_record.insert(ident.to_id()); } } fn visit_mut_export_decl(&mut self, node: &mut ExportDecl) { if self.ref_rewriter.is_some() { if let Decl::Var(var_decl) = &mut node.decl { // visit inner directly to bypass visit_mut_var_declarator for decl in var_decl.decls.iter_mut() { decl.name.visit_mut_with(self); decl.init.visit_mut_with(self); } return; } } node.visit_mut_children_with(self); } fn visit_mut_prop(&mut self, node: &mut Prop) { node.visit_mut_children_with(self); if let Some(ref_rewriter) = self.ref_rewriter.as_mut() { ref_rewriter.exit_prop(node); } } fn visit_mut_var_declarator(&mut self, n: &mut VarDeclarator) { let ref_rewriter = self.ref_rewriter.take(); n.name.visit_mut_with(self); self.ref_rewriter = ref_rewriter; n.init.visit_mut_with(self); } fn visit_mut_pat(&mut self, node: &mut Pat) { node.visit_mut_children_with(self); if let Some(ref_rewriter) = self.ref_rewriter.as_mut() { ref_rewriter.exit_pat(node); } } fn visit_mut_expr(&mut self, node: &mut Expr) { self.enter_expr_for_inline_enum(node); maybe_grow_default(|| node.visit_mut_children_with(self)); if let Some(ref_rewriter) = self.ref_rewriter.as_mut() { ref_rewriter.exit_expr(node); } } fn visit_mut_assign_expr(&mut self, n: &mut AssignExpr) { let is_lhs = mem::replace(&mut self.is_lhs, true); n.left.visit_mut_with(self); self.is_lhs = false; n.right.visit_mut_with(self); self.is_lhs = is_lhs; } fn visit_mut_assign_pat(&mut self, n: &mut AssignPat) { let is_lhs = mem::replace(&mut self.is_lhs, true); n.left.visit_mut_with(self); self.is_lhs = false; n.right.visit_mut_with(self); self.is_lhs = is_lhs; } fn visit_mut_update_expr(&mut self, n: &mut UpdateExpr) { let is_lhs = mem::replace(&mut self.is_lhs, true); n.arg.visit_mut_with(self); self.is_lhs = is_lhs; } fn visit_mut_assign_pat_prop(&mut self, n: &mut AssignPatProp) { n.key.visit_mut_with(self); let is_lhs = mem::replace(&mut self.is_lhs, false); n.value.visit_mut_with(self); self.is_lhs = is_lhs; } fn visit_mut_member_expr(&mut self, n: &mut MemberExpr) { let is_lhs = mem::replace(&mut self.is_lhs, false); n.visit_mut_children_with(self); self.is_lhs = is_lhs; } fn visit_mut_simple_assign_target(&mut self, node: &mut SimpleAssignTarget) { node.visit_mut_children_with(self); if let Some(ref_rewriter) = self.ref_rewriter.as_mut() { ref_rewriter.exit_simple_assign_target(node); } } fn visit_mut_jsx_element_name(&mut self, node: &mut JSXElementName) { node.visit_mut_children_with(self); if let Some(ref_rewriter) = self.ref_rewriter.as_mut() { ref_rewriter.exit_jsx_element_name(node); } } fn visit_mut_jsx_object(&mut self, node: &mut JSXObject) { node.visit_mut_children_with(self); if let Some(ref_rewriter) = self.ref_rewriter.as_mut() { ref_rewriter.exit_jsx_object(node); } } fn visit_mut_object_pat_prop(&mut self, n: &mut ObjectPatProp) { n.visit_mut_children_with(self); if let Some(ref_rewriter) = self.ref_rewriter.as_mut() { ref_rewriter.exit_object_pat_prop(n); } } } enum FoldedDecl { Empty, Decl(Decl), Expr(Stmt), } impl Transform { fn fold_decl(&mut self, node: Decl, is_export: bool) -> FoldedDecl { match node { Decl::TsModule(ts_module) => { let id = ts_module.id.to_id(); if self.decl_id_record.insert(id.clone()) { if is_export { if self.namespace_id.is_none() { self.export_var_list.push(id); } } else { self.var_list.push(id); } } self.transform_ts_module(*ts_module, is_export) } Decl::TsEnum(ts_enum) => { let id = ts_enum.id.to_id(); let is_first = self.decl_id_record.insert(id); self.transform_ts_enum(*ts_enum, is_first, is_export) } Decl::Fn(FnDecl { ref ident, .. }) | Decl::Class(ClassDecl { ref ident, .. }) => { self.decl_id_record.insert(ident.to_id()); FoldedDecl::Decl(node) } decl => FoldedDecl::Decl(decl), } } } struct InitArg<'a> { id: &'a Ident, namespace_id: Option<&'a Id>, } impl InitArg<'_> { // {} fn empty() -> ExprOrSpread { ExprOrSpread { spread: None, expr: ObjectLit::default().into(), } } // N fn get(&self) -> ExprOrSpread { self.namespace_id .cloned() .map_or_else( || -> Expr { self.id.clone().into() }, |namespace_id| namespace_id.make_member(self.id.clone().into()).into(), ) .into() } // N || {} fn or_empty(&self) -> ExprOrSpread { let expr = self.namespace_id.cloned().map_or_else( || -> Expr { self.id.clone().into() }, |namespace_id| namespace_id.make_member(self.id.clone().into()).into(), ); let bin = BinExpr { op: op!("||"), left: expr.into(), right: ObjectLit::default().into(), ..Default::default() }; ExprOrSpread { spread: None, expr: bin.into(), } } // N || (N = {}) fn or_assign_empty(&self) -> ExprOrSpread { let expr = self.namespace_id.cloned().map_or_else( || -> Expr { self.id.clone().into() }, |namespace_id| namespace_id.make_member(self.id.clone().into()).into(), ); let assign = self.namespace_id.cloned().map_or_else( || ObjectLit::default().make_assign_to(op!("="), self.id.clone().into()), |namespace_id| { ObjectLit::default().make_assign_to( op!("="), namespace_id.make_member(self.id.clone().into()).into(), ) }, ); let bin = BinExpr { op: op!("||"), left: expr.into(), right: assign.into(), ..Default::default() }; ExprOrSpread { spread: None, expr: bin.into(), } } } impl Transform { fn transform_ts_enum( &mut self, ts_enum: TsEnumDecl, is_first: bool, is_export: bool, ) -> FoldedDecl { let TsEnumDecl { span, declare, is_const, id, members, } = ts_enum; debug_assert!(!declare); let ts_enum_safe_remove = !self.verbatim_module_syntax && is_const && !is_export && !self.exported_binding.contains_key(&id.to_id()); let member_list: Vec<_> = members .into_iter() .map(|m| { let span = m.span; let name = m.id.as_ref().clone(); let key = TsEnumRecordKey { enum_id: id.to_id(), member_name: name.clone(), }; let value = self.enum_record.get(&key).unwrap().clone(); EnumMemberItem { span, name, value } }) .filter(|m| !ts_enum_safe_remove || !m.is_const()) .collect(); if member_list.is_empty() && is_const { return FoldedDecl::Empty; } let stmts = member_list .into_iter() .filter(|item| !ts_enum_safe_remove || !item.is_const()) .map(|item| item.build_assign(&id.to_id())); let namespace_export = self.namespace_id.is_some() && is_export; let iife = !is_first || namespace_export; let body = if !iife { let return_stmt: Stmt = ReturnStmt { arg: Some(id.clone().into()), ..Default::default() } .into(); let stmts = stmts.chain(iter::once(return_stmt)).collect(); BlockStmt { stmts, ..Default::default() } } else { BlockStmt { stmts: stmts.collect(), ..Default::default() } }; let var_kind = if is_export || id.ctxt == self.top_level_ctxt { VarDeclKind::Var } else { VarDeclKind::Let }; let init_arg = 'init_arg: { let init_arg = InitArg { id: &id, namespace_id: self.namespace_id.as_ref().filter(|_| is_export), }; if !is_first { break 'init_arg init_arg.get(); } if namespace_export { break 'init_arg init_arg.or_assign_empty(); } if is_export || var_kind == VarDeclKind::Let { InitArg::empty() } else { init_arg.or_empty() } }; let expr = Factory::function(vec![id.clone().into()], body) .as_call(if iife { DUMMY_SP } else { PURE_SP }, vec![init_arg]); if iife { FoldedDecl::Expr( ExprStmt { span, expr: expr.into(), } .into(), ) } else { let var_declarator = VarDeclarator { span, name: id.into(), init: Some(expr.into()), definite: false, }; FoldedDecl::Decl( VarDecl { span, kind: var_kind, decls: vec![var_declarator], ..Default::default() } .into(), ) } } fn transform_ts_enum_member( member: TsEnumMember, enum_id: &Id, default_init: &TsEnumRecordValue, record: &TsEnumRecord, unresolved_ctxt: SyntaxContext, ) -> TsEnumRecordValue { member .init .map(|expr| { EnumValueComputer { enum_id, unresolved_ctxt, record, } .compute(expr) }) .filter(TsEnumRecordValue::has_value) .unwrap_or_else(|| default_init.clone()) } } impl Transform { fn transform_ts_module(&self, ts_module: TsModuleDecl, is_export: bool) -> FoldedDecl { debug_assert!(!ts_module.declare); debug_assert!(!ts_module.global); let TsModuleDecl { span, id: TsModuleName::Ident(module_ident), body: Some(body), .. } = ts_module else { unreachable!(); }; let body = Self::transform_ts_namespace_body(module_ident.to_id(), body); let init_arg = InitArg { id: &module_ident, namespace_id: self.namespace_id.as_ref().filter(|_| is_export), } .or_assign_empty(); let expr = Factory::function(vec![module_ident.clone().into()], body) .as_call(DUMMY_SP, vec![init_arg]) .into(); FoldedDecl::Expr(ExprStmt { span, expr }.into()) } fn transform_ts_namespace_body(id: Id, body: TsNamespaceBody) -> BlockStmt { let TsNamespaceDecl { span, declare, global, id: local_name, body, } = match body { TsNamespaceBody::TsModuleBlock(ts_module_block) => { return Self::transform_ts_module_block(id, ts_module_block); } TsNamespaceBody::TsNamespaceDecl(ts_namespace_decl) => ts_namespace_decl, }; debug_assert!(!declare); debug_assert!(!global); let body = Self::transform_ts_namespace_body(local_name.to_id(), *body); let init_arg = InitArg { id: &local_name, namespace_id: Some(&id.to_id()), } .or_assign_empty(); let expr = Factory::function(vec![local_name.into()], body).as_call(DUMMY_SP, vec![init_arg]); BlockStmt { span, stmts: vec![expr.into_stmt()], ..Default::default() } } /// Note: /// All exported variable declarations are transformed into assignment to /// the namespace. All references to the exported binding will be /// replaced with qualified access to the namespace property. /// /// Exported function and class will be treat as const exported which is in /// line with how the TypeScript compiler handles exports. /// /// Inline exported syntax should not be used with function which will lead /// to issues with function hoisting. /// /// Input: /// ```TypeScript /// export const foo = init, { bar: baz = init } = init; /// /// export function a() {} /// /// export let b = init; /// ``` /// /// Output: /// ```TypeScript /// NS.foo = init, { bar: NS.baz = init } = init; /// /// function a() {} /// NS.a = a; /// /// NS.b = init; /// ``` fn transform_ts_module_block(id: Id, TsModuleBlock { span, body }: TsModuleBlock) -> BlockStmt { let mut stmts = Vec::new(); for module_item in body { match module_item { ModuleItem::Stmt(stmt) => stmts.push(stmt), ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { decl, span, .. })) => match decl { Decl::Class(ClassDecl { ref ident, .. }) | Decl::Fn(FnDecl { ref ident, .. }) => { let assign_stmt = Self::assign_prop(&id, ident, span); stmts.push(decl.into()); stmts.push(assign_stmt); } Decl::Var(var_decl) => { let mut exprs: Vec<Box<_>> = var_decl .decls .into_iter() .flat_map( |VarDeclarator { span, name, init, .. }| { let right = init?; let left = name.try_into().unwrap(); Some( AssignExpr { span, left, op: op!("="), right, } .into(), ) }, ) .collect(); if exprs.is_empty() { continue; } let expr = if exprs.len() == 1 { exprs.pop().unwrap() } else { SeqExpr { span: DUMMY_SP, exprs, } .into() }; stmts.push( ExprStmt { span: var_decl.span, expr, } .into(), ); } decl => unreachable!("{decl:?}"), }, ModuleItem::ModuleDecl(ModuleDecl::TsImportEquals(decl)) => { match decl.module_ref { TsModuleRef::TsEntityName(ts_entity_name) => { let init = Self::ts_entity_name_to_expr(ts_entity_name); // export impot foo = bar.baz let stmt = if decl.is_export { // Foo.foo = bar.baz let left = id.clone().make_member(decl.id.clone().into()); let expr = init.make_assign_to(op!("="), left.into()); ExprStmt { span: decl.span, expr: expr.into(), } .into() } else { // const foo = bar.baz let mut var_decl = init.into_var_decl(VarDeclKind::Const, decl.id.clone().into()); var_decl.span = decl.span; var_decl.into() }; stmts.push(stmt); } TsModuleRef::TsExternalModuleRef(..) => { // TS1147 HANDLER.with(|handler| { handler .struct_span_err( decl.span, r#"Import declarations in a namespace cannot reference a module."#, ) .emit(); }); } } } item => { HANDLER.with(|handler| { handler .struct_span_err( item.span(), r#"ESM-style module declarations are not permitted in a namespace."#, ) .emit(); }); } } } BlockStmt { span, stmts, ..Default::default() } } } impl Transform { fn reorder_class_prop_decls_and_inits( &mut self, class_member_list: &mut Vec<ClassMember>, prop_list: Vec<Id>, mut init_list: Vec<Box<Expr>>, ) { let mut constructor = None; let mut cons_index = 0; for (index, member) in class_member_list.iter_mut().enumerate() { match member { ClassMember::Constructor(..) => { let empty = EmptyStmt { span: member.span(), } .into(); constructor = mem::replace(member, empty).constructor(); cons_index = index; } ClassMember::ClassProp(ClassProp { key, value: value @ Some(..), is_static: false, .. }) => { let key = match &mut *key { PropName::Computed(ComputedPropName { span, expr }) if !is_literal(expr) => { let ident = alias_ident_for(expr, "_key"); self.var_list.push(ident.to_id()); **expr = expr.take().make_assign_to(op!("="), ident.clone().into()); PropName::Computed(ComputedPropName { span: *span, expr: ident.into(), }) } _ => key.clone(), }; init_list.push(assign_value_to_this_prop(key, *value.take().unwrap())); } ClassMember::PrivateProp(PrivateProp { key, value: value @ Some(..), is_static: false, .. }) => { init_list.push(assign_value_to_this_private_prop( key.clone(), *value.take().unwrap(), )); } _ => {} } } if let Some(mut constructor) = constructor { inject_after_super(&mut constructor, init_list); if let Some(c) = class_member_list .get_mut(cons_index) .filter(|m| m.is_empty() && m.span() == constructor.span) { *c = constructor.into(); } else { class_member_list.push(constructor.into()); } } class_member_list.splice( 0..0, prop_list .into_iter() .map(Ident::from) .map(PropName::from) .map(|key| ClassProp { key, ..Default::default() }) .map(ClassMember::ClassProp), ); } fn reorder_class_prop_decls( &mut self, class_member_list: &mut Vec<ClassMember>, prop_list: Vec<Id>, init_list: Vec<Box<Expr>>, ) { if let Some(constructor) = class_member_list .iter_mut() .find_map(|m| m.as_mut_constructor()) { inject_after_super(constructor, init_list); } class_member_list.splice( 0..0, prop_list .into_iter() .map(Ident::from) .map(PropName::from) .map(|key| ClassProp { key, ..Default::default() }) .map(ClassMember::ClassProp), ); } } impl Transform { // Foo.x = x; fn assign_prop(id: &Id, prop: &Ident, span: Span) -> Stmt { let expr = prop .clone() .make_assign_to(op!("="), id.clone().make_member(prop.clone().into()).into()); ExprStmt { span, expr: expr.into(), } .into() } fn ts_entity_name_to_expr(n: TsEntityName) -> Expr { match n { TsEntityName::Ident(i) => i.into(), TsEntityName::TsQualifiedName(q) => { let TsQualifiedName { span, left, right } = *q; MemberExpr { span, obj: Box::new(Self::ts_entity_name_to_expr(left)), prop: MemberProp::Ident(right), } .into() } } } } impl Transform { fn enter_expr_for_inline_enum(&mut self, node: &mut Expr) { if self.is_lhs { return; } if let Expr::Member(MemberExpr { obj, prop, .. }) = node { let Some(enum_id) = get_enum_id(obj) else { return; }; if self.ts_enum_is_mutable && !self.const_enum.contains(&enum_id) { return; } let Some(member_name) = get_member_key(prop) else { return; }; let key = TsEnumRecordKey { enum_id, member_name, }; let Some(value) = self.enum_record.get(&key) else { return; }; if value.is_const() { *node = value.clone().into(); } } } fn visit_mut_for_ts_import_export(&mut self, node: &mut Module) { let mut should_inject = false; let create_require = private_ident!("_createRequire"); let require = private_ident!("__require"); // NOTE: This is not correct! // However, all unresolved_span are used in TsImportExportAssignConfig::Classic // which is deprecated and not used in real world. let unresolved_ctxt = self.unresolved_ctxt; let cjs_require = quote_ident!(unresolved_ctxt, "require"); let cjs_exports = quote_ident!(unresolved_ctxt, "exports"); let mut cjs_export_assign = None; for module_item in &mut node.body { match module_item { ModuleItem::ModuleDecl(ModuleDecl::TsImportEquals(decl)) if !decl.is_type_only => { debug_assert_ne!( decl.id.ctxt, self.unresolved_ctxt, "TsImportEquals has top-level context and it should not be identical to \ the unresolved mark" ); debug_assert_eq!(decl.id.ctxt, self.top_level_ctxt); match &mut decl.module_ref { // import foo = bar.baz TsModuleRef::TsEntityName(ts_entity_name) => { let init = Self::ts_entity_name_to_expr(ts_entity_name.clone()); let mut var_decl = init.into_var_decl(VarDeclKind::Const, decl.id.take().into()); *module_item = if decl.is_export { ExportDecl { span: decl.span, decl: var_decl.into(), } .into() } else { var_decl.span = decl.span; var_decl.into() }; } // import foo = require("foo") TsModuleRef::TsExternalModuleRef(TsExternalModuleRef { expr, .. }) => { match self.import_export_assign_config { TsImportExportAssignConfig::Classic => { // require("foo"); let mut init = cjs_require .clone() .as_call(DUMMY_SP, vec![expr.take().as_arg()]); // exports.foo = require("foo"); if decl.is_export { init = init.make_assign_to( op!("="), cjs_exports .clone() .make_member(decl.id.clone().into()) .into(), ) } // const foo = require("foo"); // const foo = exports.foo = require("foo"); let mut var_decl = init .into_var_decl(VarDeclKind::Const, decl.id.take().into()); var_decl.span = decl.span; *module_item = var_decl.into(); } TsImportExportAssignConfig::Preserve => {} TsImportExportAssignConfig::NodeNext => { should_inject = true; let mut var_decl = require .clone() .as_call(DUMMY_SP, vec![expr.take().as_arg()]) .into_var_decl(VarDeclKind::Const, decl.id.take().into()); *module_item = if decl.is_export { ExportDecl { span: decl.span, decl: var_decl.into(), } .into() } else { var_decl.span = decl.span; var_decl.into() }; } TsImportExportAssignConfig::EsNext => { // TS1202 HANDLER.with(|handler| { handler.struct_span_err( decl.span, r#"Import assignment cannot be used when targeting ECMAScript modules. Consider using `import * as ns from "mod"`, `import {a} from "mod"`, `import d from "mod"`, or another module format instead."#, ) .emit(); }); } } } } } ModuleItem::ModuleDecl(ModuleDecl::TsExportAssignment(..)) => { let ts_export_assign = module_item .take() .module_decl() .unwrap() .ts_export_assignment() .unwrap(); cjs_export_assign.get_or_insert(ts_export_assign); } _ => {} } } if should_inject { node.body.prepend_stmts([ // import { createRequire } from "module"; ImportDecl { span: DUMMY_SP, specifiers: vec![ImportNamedSpecifier { span: DUMMY_SP, local: create_require.clone(), imported: Some(quote_ident!("createRequire").into()), is_type_only: false, } .into()], src: Box::new(quote_str!("module")), type_only: false, with: None, phase: Default::default(), } .into(), // const __require = _createRequire(import.meta.url); create_require .as_call( DUMMY_SP, vec![MetaPropExpr { span: DUMMY_SP, kind: MetaPropKind::ImportMeta, } .make_member(quote_ident!("url")) .as_arg()], ) .into_var_decl(VarDeclKind::Const, require.clone().into()) .into(), ]); } if let Some(cjs_export_assign) = cjs_export_assign { match self.import_export_assign_config { TsImportExportAssignConfig::Classic => { let TsExportAssignment { expr, span } = cjs_export_assign; let stmt = ExprStmt { span, expr: Box::new( expr.make_assign_to( op!("="), member_expr!(unresolved_ctxt, Default::default(), module.exports) .into(), ), ), } .into(); if let Some(item) = node .body .last_mut() .and_then(ModuleItem::as_mut_stmt) .filter(|stmt| stmt.is_empty()) { *item = stmt; } else { node.body.push(stmt.into()); } } TsImportExportAssignConfig::Preserve => { node.body.push(cjs_export_assign.into()); } TsImportExportAssignConfig::NodeNext | TsImportExportAssignConfig::EsNext => { // TS1203 HANDLER.with(|handler| { handler .struct_span_err( cjs_export_assign.span, r#"Export assignment cannot be used when targeting ECMAScript modules. Consider using `export default` or another module format instead."#, ) .emit() }); } } } } } struct ExportQuery { export_name: FxHashMap<Id, Option<Id>>, } impl QueryRef for ExportQuery { fn query_ref(&self, export_name: &Ident) -> Option<Box<Expr>> { self.export_name .get(&export_name.to_id())? .clone() .map(|namespace_id| namespace_id.make_member(export_name.clone().into()).into()) } fn query_lhs(&self, ident: &Ident) -> Option<Box<Expr>> { self.query_ref(ident) } fn query_jsx(&self, ident: &Ident) -> Option<JSXElementName> { self.export_name .get(&ident.to_id())? .clone() .map(|namespace_id| { JSXMemberExpr { span: DUMMY_SP, obj: JSXObject::Ident(namespace_id.into()), prop: ident.clone().into(), } .into() }) } } struct EnumMemberItem { span: Span, name: Atom, value: TsEnumRecordValue, } impl EnumMemberItem { fn is_const(&self) -> bool { self.value.is_const() } fn build_assign(self, enum_id: &Id) -> Stmt { let is_string = self.value.is_string(); let value: Expr = self.value.into(); let inner_assign = value.make_assign_to( op!("="), Ident::from(enum_id.clone()) .computed_member(self.name.clone()) .into(), ); let outer_assign = if is_string { inner_assign } else { let value: Expr = self.name.clone().into(); value.make_assign_to( op!("="), Ident::from(enum_id.clone()) .computed_member(inner_assign) .into(), ) }; ExprStmt { span: self.span, expr: outer_assign.into(), } .into() } } trait ModuleId { fn to_id(&self) -> Id; } impl ModuleId for TsModuleName { fn to_id(&self) -> Id { self.as_ident() .expect("Only ambient modules can use quoted names.") .to_id() } } fn id_to_var_declarator(id: Id) -> VarDeclarator { VarDeclarator { span: DUMMY_SP, name: id.into(), init: None, definite: false, } } fn get_enum_id(e: &Expr) -> Option<Id> { if let Expr::Ident(ident) = e { Some(ident.to_id()) } else { None } } fn get_member_key(prop: &MemberProp) -> Option<Atom> { match prop { MemberProp::Ident(ident) => Some(ident.sym.clone()), MemberProp::Computed(ComputedPropName { expr, .. }) => match &**expr { Expr::Lit(Lit::Str(Str { value, .. })) => Some(value.clone()), Expr::Tpl(Tpl { exprs, quasis, .. }) => match (exprs.len(), quasis.len()) { (0, 1) => quasis[0].cooked.as_ref().map(|v| Atom::from(&**v)), _ => None, }, _ => None, }, MemberProp::PrivateName(_) => None, } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/src/ts_enum.rs
Rust
use rustc_hash::FxHashMap; use swc_atoms::Atom; use swc_common::{SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{ number::{JsNumber, ToJsString}, ExprFactory, }; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(crate) struct TsEnumRecordKey { pub enum_id: Id, pub member_name: Atom, } pub(crate) type TsEnumRecord = FxHashMap<TsEnumRecordKey, TsEnumRecordValue>; #[derive(Debug, Clone)] pub(crate) enum TsEnumRecordValue { String(Atom), Number(JsNumber), Opaque(Box<Expr>), Void, } impl TsEnumRecordValue { pub fn inc(&self) -> Self { match self { Self::Number(num) => Self::Number((**num + 1.0).into()), _ => Self::Void, } } pub fn is_const(&self) -> bool { matches!( self, TsEnumRecordValue::String(..) | TsEnumRecordValue::Number(..) ) } pub fn is_string(&self) -> bool { matches!(self, TsEnumRecordValue::String(..)) } pub fn has_value(&self) -> bool { !matches!(self, TsEnumRecordValue::Void) } } impl From<TsEnumRecordValue> for Expr { fn from(value: TsEnumRecordValue) -> Self { match value { TsEnumRecordValue::String(string) => Lit::Str(string.into()).into(), TsEnumRecordValue::Number(num) if num.is_nan() => Ident { span: DUMMY_SP, sym: "NaN".into(), ..Default::default() } .into(), TsEnumRecordValue::Number(num) if num.is_infinite() => { let value: Expr = Ident { span: DUMMY_SP, sym: "Infinity".into(), ..Default::default() } .into(); if num.is_sign_negative() { UnaryExpr { span: DUMMY_SP, op: op!(unary, "-"), arg: value.into(), } .into() } else { value } } TsEnumRecordValue::Number(num) => Lit::Num(Number { span: DUMMY_SP, value: *num, raw: None, }) .into(), TsEnumRecordValue::Void => *Expr::undefined(DUMMY_SP), TsEnumRecordValue::Opaque(expr) => *expr, } } } impl From<f64> for TsEnumRecordValue { fn from(value: f64) -> Self { Self::Number(value.into()) } } pub(crate) struct EnumValueComputer<'a> { pub enum_id: &'a Id, pub unresolved_ctxt: SyntaxContext, pub record: &'a TsEnumRecord, } /// https://github.com/microsoft/TypeScript/pull/50528 impl EnumValueComputer<'_> { pub fn compute(&mut self, expr: Box<Expr>) -> TsEnumRecordValue { let mut expr = self.compute_rec(expr); if let TsEnumRecordValue::Opaque(expr) = &mut expr { expr.visit_mut_with(self); } expr } fn compute_rec(&self, expr: Box<Expr>) -> TsEnumRecordValue { match *expr { Expr::Lit(Lit::Str(s)) => TsEnumRecordValue::String(s.value), Expr::Lit(Lit::Num(n)) => TsEnumRecordValue::Number(n.value.into()), Expr::Ident(Ident { ctxt, sym, .. }) if &*sym == "NaN" && ctxt == self.unresolved_ctxt => { TsEnumRecordValue::Number(f64::NAN.into()) } Expr::Ident(Ident { ctxt, sym, .. }) if &*sym == "Infinity" && ctxt == self.unresolved_ctxt => { TsEnumRecordValue::Number(f64::INFINITY.into()) } Expr::Ident(ref ident) => self .record .get(&TsEnumRecordKey { enum_id: self.enum_id.clone(), member_name: ident.sym.clone(), }) .cloned() .map(|value| match value { TsEnumRecordValue::String(..) | TsEnumRecordValue::Number(..) => value, _ => TsEnumRecordValue::Opaque( self.enum_id .clone() .make_member(ident.clone().into()) .into(), ), }) .unwrap_or_else(|| TsEnumRecordValue::Opaque(expr)), Expr::Paren(e) => self.compute_rec(e.expr), Expr::Unary(e) => self.compute_unary(e), Expr::Bin(e) => self.compute_bin(e), Expr::Member(e) => self.compute_member(e), Expr::Tpl(e) => self.compute_tpl(e), _ => TsEnumRecordValue::Opaque(expr), } } fn compute_unary(&self, expr: UnaryExpr) -> TsEnumRecordValue { if !matches!(expr.op, op!(unary, "+") | op!(unary, "-") | op!("~")) { return TsEnumRecordValue::Opaque(expr.into()); } let inner = self.compute_rec(expr.arg); let TsEnumRecordValue::Number(num) = inner else { return TsEnumRecordValue::Opaque( UnaryExpr { span: expr.span, op: expr.op, arg: Box::new(inner.into()), } .into(), ); }; match expr.op { op!(unary, "+") => TsEnumRecordValue::Number(num), op!(unary, "-") => TsEnumRecordValue::Number(-num), op!("~") => TsEnumRecordValue::Number(!num), _ => unreachable!(), } } fn compute_bin(&self, expr: BinExpr) -> TsEnumRecordValue { let origin_expr = expr.clone(); if !matches!( expr.op, op!(bin, "+") | op!(bin, "-") | op!("*") | op!("/") | op!("%") | op!("**") | op!("<<") | op!(">>") | op!(">>>") | op!("|") | op!("&") | op!("^"), ) { return TsEnumRecordValue::Opaque(origin_expr.into()); } let left = self.compute_rec(expr.left); let right = self.compute_rec(expr.right); match (left, right, expr.op) { (TsEnumRecordValue::Number(left), TsEnumRecordValue::Number(right), op) => { let value = match op { op!(bin, "+") => left + right, op!(bin, "-") => left - right, op!("*") => left * right, op!("/") => left / right, op!("%") => left % right, op!("**") => left.pow(right), op!("<<") => left << right, op!(">>") => left >> right, op!(">>>") => left.unsigned_shr(right), op!("|") => left | right, op!("&") => left & right, op!("^") => left ^ right, _ => unreachable!(), }; TsEnumRecordValue::Number(value) } (TsEnumRecordValue::String(left), TsEnumRecordValue::String(right), op!(bin, "+")) => { TsEnumRecordValue::String(format!("{}{}", left, right).into()) } (TsEnumRecordValue::Number(left), TsEnumRecordValue::String(right), op!(bin, "+")) => { let left = left.to_js_string(); TsEnumRecordValue::String(format!("{}{}", left, right).into()) } (TsEnumRecordValue::String(left), TsEnumRecordValue::Number(right), op!(bin, "+")) => { let right = right.to_js_string(); TsEnumRecordValue::String(format!("{}{}", left, right).into()) } (left, right, _) => { let mut origin_expr = origin_expr; if left.is_const() { origin_expr.left = Box::new(left.into()); } if right.is_const() { origin_expr.right = Box::new(right.into()); } TsEnumRecordValue::Opaque(origin_expr.into()) } } } fn compute_member(&self, expr: MemberExpr) -> TsEnumRecordValue { if matches!(expr.prop, MemberProp::PrivateName(..)) { return TsEnumRecordValue::Opaque(expr.into()); } let opaque_expr = TsEnumRecordValue::Opaque(expr.clone().into()); let member_name = match expr.prop { MemberProp::Ident(ident) => ident.sym, MemberProp::Computed(ComputedPropName { expr, .. }) => { let Expr::Lit(Lit::Str(s)) = *expr else { return opaque_expr; }; s.value } _ => return opaque_expr, }; let Expr::Ident(ident) = *expr.obj else { return opaque_expr; }; self.record .get(&TsEnumRecordKey { enum_id: ident.to_id(), member_name, }) .cloned() .filter(TsEnumRecordValue::has_value) .unwrap_or(opaque_expr) } fn compute_tpl(&self, expr: Tpl) -> TsEnumRecordValue { let opaque_expr = TsEnumRecordValue::Opaque(expr.clone().into()); let Tpl { exprs, quasis, .. } = expr; let mut quasis_iter = quasis.into_iter(); let Some(mut string) = quasis_iter.next().map(|q| q.raw.to_string()) else { return opaque_expr; }; for (q, expr) in quasis_iter.zip(exprs) { let expr = self.compute_rec(expr); let expr = match expr { TsEnumRecordValue::String(s) => s.to_string(), TsEnumRecordValue::Number(n) => n.to_js_string(), _ => return opaque_expr, }; string.push_str(&expr); string.push_str(&q.raw); } TsEnumRecordValue::String(string.into()) } } impl VisitMut for EnumValueComputer<'_> { noop_visit_mut_type!(); fn visit_mut_expr(&mut self, expr: &mut Expr) { expr.visit_mut_children_with(self); let Expr::Ident(ident) = expr else { return }; if self.record.contains_key(&TsEnumRecordKey { enum_id: self.enum_id.clone(), member_name: ident.sym.clone(), }) { *expr = self .enum_id .clone() .make_member(ident.clone().into()) .into(); } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/src/typescript.rs
Rust
use std::mem; use rustc_hash::FxHashSet; use swc_common::{comments::Comments, sync::Lrc, util::take::Take, Mark, SourceMap, Span, Spanned}; use swc_ecma_ast::*; use swc_ecma_transforms_react::{parse_expr_for_jsx, JsxDirectives}; use swc_ecma_visit::{visit_mut_pass, VisitMut, VisitMutWith}; pub use crate::config::*; use crate::{strip_import_export::StripImportExport, strip_type::StripType, transform::transform}; #[cfg(feature = "concurrent")] macro_rules! static_str { ($s:expr) => {{ static VAL: once_cell::sync::Lazy<Lrc<String>> = once_cell::sync::Lazy::new(|| Lrc::new($s.into())); VAL.clone() }}; } #[cfg(not(feature = "concurrent"))] macro_rules! static_str { ($s:expr) => { Lrc::new($s.into()) }; } pub fn typescript(config: Config, unresolved_mark: Mark, top_level_mark: Mark) -> impl Pass { debug_assert_ne!(unresolved_mark, top_level_mark); visit_mut_pass(TypeScript { config, unresolved_mark, top_level_mark, id_usage: Default::default(), }) } pub fn strip(unresolved_mark: Mark, top_level_mark: Mark) -> impl Pass { typescript(Config::default(), unresolved_mark, top_level_mark) } pub(crate) struct TypeScript { pub config: Config, pub unresolved_mark: Mark, pub top_level_mark: Mark, id_usage: FxHashSet<Id>, } impl VisitMut for TypeScript { fn visit_mut_program(&mut self, n: &mut Program) { let was_module = n.as_module().and_then(|m| self.get_last_module_span(m)); if !self.config.verbatim_module_syntax { n.visit_mut_with(&mut StripImportExport { import_not_used_as_values: self.config.import_not_used_as_values, usage_info: mem::take(&mut self.id_usage).into(), ..Default::default() }); } n.visit_mut_with(&mut StripType::default()); n.mutate(transform( self.unresolved_mark, self.top_level_mark, self.config.import_export_assign_config, self.config.ts_enum_is_mutable, self.config.verbatim_module_syntax, self.config.native_class_properties, )); if let Some(span) = was_module { let module = n.as_mut_module().unwrap(); Self::restore_esm_ctx(module, span); } } fn visit_mut_script(&mut self, _: &mut Script) { #[cfg(debug_assertions)] unreachable!("Use Program as entry"); #[cfg(not(debug_assertions))] unreachable!(); } fn visit_mut_module(&mut self, _: &mut Module) { #[cfg(debug_assertions)] unreachable!("Use Program as entry"); #[cfg(not(debug_assertions))] unreachable!(); } } impl TypeScript { fn get_last_module_span(&self, n: &Module) -> Option<Span> { if self.config.no_empty_export { return None; } n.body .iter() .rev() .find(|m| m.is_es_module_decl()) .map(Spanned::span) } fn restore_esm_ctx(n: &mut Module, span: Span) { if n.body.iter().any(ModuleItem::is_es_module_decl) { return; } n.body.push( NamedExport { span, ..NamedExport::dummy() } .into(), ); } } trait EsModuleDecl { fn is_es_module_decl(&self) -> bool; } impl EsModuleDecl for ModuleDecl { fn is_es_module_decl(&self) -> bool { // Do not use `matches!` // We should cover all cases explicitly. match self { ModuleDecl::Import(..) | ModuleDecl::ExportDecl(..) | ModuleDecl::ExportNamed(..) | ModuleDecl::ExportDefaultDecl(..) | ModuleDecl::ExportDefaultExpr(..) | ModuleDecl::ExportAll(..) => true, ModuleDecl::TsImportEquals(..) | ModuleDecl::TsExportAssignment(..) | ModuleDecl::TsNamespaceExport(..) => false, } } } impl EsModuleDecl for ModuleItem { fn is_es_module_decl(&self) -> bool { self.as_module_decl() .map_or(false, ModuleDecl::is_es_module_decl) } } pub fn tsx<C>( cm: Lrc<SourceMap>, config: Config, tsx_config: TsxConfig, comments: C, unresolved_mark: Mark, top_level_mark: Mark, ) -> impl Pass where C: Comments, { visit_mut_pass(TypeScriptReact { config, tsx_config, id_usage: Default::default(), comments, cm, top_level_mark, unresolved_mark, }) } /// Get an [Id] which will used by expression. /// /// For `React#1.createElement`, this returns `React#1`. fn id_for_jsx(e: &Expr) -> Option<Id> { match e { Expr::Ident(i) => Some(i.to_id()), Expr::Member(MemberExpr { obj, .. }) => Some(id_for_jsx(obj)).flatten(), Expr::Lit(Lit::Null(..)) => Some(("null".into(), Default::default())), _ => None, } } struct TypeScriptReact<C> where C: Comments, { config: Config, tsx_config: TsxConfig, id_usage: FxHashSet<Id>, comments: C, cm: Lrc<SourceMap>, top_level_mark: Mark, unresolved_mark: Mark, } impl<C> VisitMut for TypeScriptReact<C> where C: Comments, { fn visit_mut_module(&mut self, n: &mut Module) { // We count `React` or pragma from config as ident usage and do not strip it // from import statement. // But in `verbatim_module_syntax` mode, we do not remove any unused imports. // So we do not need to collect usage info. if !self.config.verbatim_module_syntax { let pragma = parse_expr_for_jsx( &self.cm, "pragma", self.tsx_config .pragma .clone() .unwrap_or_else(|| static_str!("React.createElement")), self.top_level_mark, ); let pragma_frag = parse_expr_for_jsx( &self.cm, "pragma", self.tsx_config .pragma_frag .clone() .unwrap_or_else(|| static_str!("React.Fragment")), self.top_level_mark, ); let pragma_id = id_for_jsx(&pragma).unwrap(); let pragma_frag_id = id_for_jsx(&pragma_frag).unwrap(); self.id_usage.insert(pragma_id); self.id_usage.insert(pragma_frag_id); } if !self.config.verbatim_module_syntax { let span = if n.shebang.is_some() { n.span .with_lo(n.body.first().map(|s| s.span_lo()).unwrap_or(n.span.lo)) } else { n.span }; let JsxDirectives { pragma, pragma_frag, .. } = self.comments.with_leading(span.lo, |comments| { JsxDirectives::from_comments(&self.cm, span, comments, self.top_level_mark) }); if let Some(pragma) = pragma { if let Some(pragma_id) = id_for_jsx(&pragma) { self.id_usage.insert(pragma_id); } } if let Some(pragma_frag) = pragma_frag { if let Some(pragma_frag_id) = id_for_jsx(&pragma_frag) { self.id_usage.insert(pragma_frag_id); } } } } fn visit_mut_script(&mut self, _: &mut Script) { // skip script } fn visit_mut_program(&mut self, n: &mut Program) { n.visit_mut_children_with(self); n.visit_mut_with(&mut TypeScript { config: mem::take(&mut self.config), unresolved_mark: self.unresolved_mark, top_level_mark: self.top_level_mark, id_usage: mem::take(&mut self.id_usage), }); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/src/utils.rs
Rust
use swc_common::DUMMY_SP; use swc_ecma_ast::*; use swc_ecma_utils::ExprFactory; /// /// this.prop = value pub(crate) fn assign_value_to_this_prop(prop_name: PropName, value: Expr) -> Box<Expr> { let target = MemberExpr { obj: ThisExpr { span: DUMMY_SP }.into(), span: DUMMY_SP, prop: prop_name.into(), }; let expr = value.make_assign_to(op!("="), target.into()); Box::new(expr) } /// this.#prop = value pub(crate) fn assign_value_to_this_private_prop( private_name: PrivateName, value: Expr, ) -> Box<Expr> { let target = MemberExpr { obj: ThisExpr { span: DUMMY_SP }.into(), span: DUMMY_SP, prop: MemberProp::PrivateName(private_name), }; let expr = value.make_assign_to(op!("="), target.into()); Box::new(expr) } pub(crate) struct Factory; impl Factory { pub(crate) fn function(params: Vec<Param>, body: BlockStmt) -> Function { Function { params, decorators: Default::default(), span: DUMMY_SP, body: Some(body), is_generator: false, is_async: false, ..Default::default() } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/bin_01.js
JavaScript
a + b + c;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/class_expression_sequence.js
JavaScript
var _class; const A = (_class = class { }, _class.a = 1, _class);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/compile_to_class_constructor_collision_ignores_types.js
JavaScript
class C { // Output should not use `_initialiseProps` x; y = 0; constructor(T){} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/constructor_1.js
JavaScript
export class Query { }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/constructor_2.js
JavaScript
var _store = /*#__PURE__*/ new WeakMap(), _body = /*#__PURE__*/ new WeakMap(); export class Context { constructor(optionsOrContext){ _class_private_field_init(this, _store, { writable: true, value: void 0 }); _class_private_field_init(this, _body, { writable: true, value: void 0 }); this.response = { headers: new Headers() }; this.params = {}; if (optionsOrContext instanceof Context) { Object.assign(this, optionsOrContext); this.customContext = this; return; } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/deno_10462.js
JavaScript
const _ = null; console.log({ foo: 1 });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/deno_10684.js
JavaScript
const a = null; console.log(a); const b = { Foo: 1 }; console.log(b.Foo);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/deno_12395_import_equals_1.js
JavaScript
import * as mongo from 'https://deno.land/x/mongo@v0.27.0/mod.ts'; const MongoClient = mongo.MongoClient; const mongoClient = new MongoClient();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/deno_12395_import_equals_2.js
JavaScript
const mongoClient = {};
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/deno_12532_declare_class_prop.js
JavaScript
export class Foo { x; constructor(x){ this.x = x; } } export class Bar extends Foo { constructor(){ super(123); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/deno_7413_2.js
JavaScript
import './foo';
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/deno_7413_3.js
JavaScript
import './foo'; import './types';
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/deno_8978.js
JavaScript
import { any } from './dep.ts'; export { any };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/deno_9097.js
JavaScript
(function(util) { function assertNever(_x) { throw new Error(); } util.assertNever = assertNever; util.arrayToEnum = (items)=>{}; util.getValidEnumValues = (obj)=>{}; util.getValues = (obj)=>{}; util.objectValues = (obj)=>{}; })(util || (util = {})); export var util;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/deno_9289_1.js
JavaScript
export class TestClass { testMethod(args) { return args.param1; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/__swc_snapshots__/tests/strip.rs/enum_export_str.js
JavaScript
export var State = /*#__PURE__*/ function(State) { State["closed"] = "closed"; State["opened"] = "opened"; State["mounted"] = "mounted"; State["unmounted"] = "unmounted"; return State; }({});
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University